Sub topic 1
Starting point: how a single coding agent works
Subagents only make sense once you know what they replace. This chapter describes the loop that every coding agent runs, the pieces it is made of, and the places where one agent starts to struggle. Later chapters build on this model.
Prerequisites
This chapter assumes you have:
- Used an AI coding assistant or agent in a terminal or editor, and seen it read files or run commands.
- Read basic Python (functions, dictionaries, lists,
try/except). - A general idea of what a model's context window is (the text the model can see at once) and what a tool call is (a structured request from the model to run a function).
You don't need to have called a model API yourself. The code example uses a scripted stand-in for the model, so it runs offline.
The loop
A coding agent is a program wrapped around a language model. The model only reads text and writes text. The program gives that text consequences by running tools the model asks for.
Each cycle has three steps:
- Prompt. The program sends the model the conversation so far: instructions, your task, and everything that has happened.
- Tool call or answer. The model replies with either a tool call (for example, "read
src/cli.py") or a final answer. - Observation. If the reply was a tool call, the program runs the tool, takes its output, and appends it to the conversation. This output is the observation. The loop then returns to step 1.
The loop ends when the model produces a final answer, when it hits a step limit, or when a human stops it.
The key detail is the arrow from the observation back to the conversation history. The agent has no memory other than that history. Everything it "knows" about your repository is text that is currently in the conversation.
The parts of a coding agent
| Part | What it is | Example |
|---|---|---|
| System prompt | Standing instructions the model sees on every turn | "You are a coding agent. Prefer small edits." |
| Task | The user's request | "Fix the failing test in `tests/test_cli.py`." |
| Tools | Functions the model may request, each with a name and typed arguments | `read_file`, `edit_file`, `run_command`, `search` |
| Conversation history | Every message, tool call, and observation so far | A growing list of messages |
| Harness | The program that runs the loop, executes tools, and enforces limits | Your terminal agent |
The harness is the part you control. It decides which tools exist, which ones need your approval, how many steps are allowed, and what happens on errors. When a later chapter talks about scoping a subagent's tools, it is changing the harness configuration, not the model.
A minimal loop in code
The script below is a complete agent loop. The fake_model function stands in for a real model and follows a fixed script: list the directory, read this script's own file, then answer. Replacing it with a real API call is the only change a real agent would need in this part of the code.
from pathlib import Path
def read_file(path: str) -> str:
return Path(path).read_text()
def list_dir(path: str) -> str:
return "\n".join(sorted(p.name for p in Path(path).iterdir()))
TOOLS = {"read_file": read_file, "list_dir": list_dir}
def fake_model(messages: list[dict]) -> dict:
"""Scripted stand-in for a model call. Returns a tool call or a final answer."""
observations = [m for m in messages if m["role"] == "tool"]
if len(observations) == 0:
return {"type": "tool_call", "name": "list_dir", "args": {"path": "."}}
if len(observations) == 1:
return {
"type": "tool_call",
"name": "read_file",
"args": {"path": Path(__file__).name},
}
line_count = len(observations[-1]["content"].splitlines())
return {"type": "final", "content": f"The script has {line_count} lines."}
def run_agent(task: str, max_steps: int = 10) -> str:
messages = [{"role": "user", "content": task}]
for step in range(1, max_steps + 1):
reply = fake_model(messages)
if reply["type"] == "final":
return reply["content"]
messages.append({"role": "assistant", "content": str(reply)})
try:
observation = TOOLS[reply["name"]](**reply["args"])
except Exception as exc: # the error becomes an observation
observation = f"error: {exc}"
messages.append({"role": "tool", "content": observation})
size = sum(len(m["content"]) for m in messages)
print(f"step {step}: {reply['name']} -> context is now {size} characters")
return "stopped: step limit reached"
if __name__ == "__main__":
print(run_agent("How many lines does this script have?"))Run it and you will see the context size grow at each step, followed by the answer. Three details are worth noticing:
- Errors are observations. If a tool raises an exception, the loop does not crash. It writes
error: ...into the conversation so the model can read it and try something else. Real agents rely on this to recover from typos in file paths or failing commands. - The step limit is a safety net. Without
max_steps, a model that keeps asking for tools would loop forever. - Nothing is removed. Messages are only appended. Every earlier observation stays in the history and is sent again on every call.
What a real session looks like
Suppose you ask an agent to "add a --verbose flag to the CLI and update the docs." A typical single-agent run goes like this:
- Search the repository for the argument parser.
- Read
src/cli.py. - Edit
src/cli.pyto add the flag. - Run the test suite and read the failures.
- Read two test files to understand the failures.
- Edit the tests.
- Re-run the tests.
- Read
README.md, edit the usage section, and answer.
Each step is one trip around the loop. Notice that the agent works through these steps in order, one at a time, and that every file it read in steps 1 to 5 is still in the conversation when it edits the README in step 8. The README edit does not need the test failure output, but it is there anyway.
Where one agent starts to strain
The loop is simple and works well for small tasks. Three properties of it become limits on larger ones.
The history only grows. Each observation adds text. Reading a 500-line file or running a verbose test suite can add thousands of tokens in one step. The model has a fixed context window, so a long task eventually fills it. Before that point, quality often degrades: the model may overlook details buried in a long history. The next chapter covers this in detail.
Work is sequential. The model produces one reply at a time, and each reply depends on the previous observation. Two unrelated jobs, such as updating docs and writing tests, still run one after the other. The total time is the sum of all steps.
One context holds everything. Exploration, dead ends, failed attempts, and finished work all share a single history. The agent's final steps are made with a context full of material from earlier, unrelated steps.
Common errors with the single-agent loop
Most multi-agent problems are single-agent problems in disguise, so it helps to know the basic failure modes first.
- Runaway loops. The model repeats the same failing command. A step limit and a repeated-call check in the harness catch this.
- Oversized observations. A tool returns a whole log file or directory tree. Truncate or summarize tool output before it enters the history.
- Silent assumptions. The model edits code it has not read, because the file was never loaded into the conversation. Good agents read before they edit.
- Stale context. The model reads a file, edits it, and later reasons from the old copy still in the history. Re-read after edits when exactness matters.
- Unchecked claims. The final answer says "tests pass" without a test run in the history. Check the observations, not the summary.
How this leads to subagents
A subagent is a second run of this same loop, started by the first one, with its own fresh history. Everything in this chapter applies to it unchanged. It has a prompt, tools, observations, and a step limit. What changes is who starts it, what it is told, and what comes back. The next chapters explain why a long task strains the context window, then show how a subagent's separate history solves part of the problem.
Exercise
In the loop code above, you ask the agent to read a file that does not exist. What does the harness do, and why is that useful?
Show answer
The tool raises an exception, the except block catches it, and the message error: ... is appended to the conversation as the observation. The loop keeps going, so the model sees the error on the next turn and can correct its approach, for example by listing the directory to find the right path. If the exception crashed the loop, the whole task would fail on a simple typo.
Exercise
An agent has run 40 steps on a task. At step 41 it needs to make a small edit that depends only on the last file it read. Why does the full 40-step history still matter to this step?
Show answer
The model is sent the entire conversation on every call, because the harness only appends and never removes messages. The earlier observations take up context window space and add cost and latency to step 41, and they may distract the model, even though the edit does not need them. This is the pressure that motivates giving some work to a separate context.