Sub topic 2
How the agent loop works
This chapter explains the cycle that Claude Code, Codex CLI, and Copilot CLI all run. It assumes you can use a shell, you know roughly what a large language model is, and you have seen a chat API that takes a list of messages. You don't need to have installed any of the tools yet.
The loop in one sentence
A terminal coding agent repeats three steps until the model decides it is done:
- Model call. The tool sends the conversation so far to the model.
- Tool call. The model replies with text, or with a request to run a tool such as "read this file" or "run
npm test". - Observation. The tool runs the request on your machine and appends the result to the conversation. Then it goes back to step 1.
The model never touches your files or shell. It only produces text, some of which is structured as a tool request. The program around it, often called the harness, decides whether to run the request, runs it, and reports the result back. Everything the agent "knows" about your project comes from observations that earlier iterations put into the conversation.
What the model actually receives
On every iteration the model gets the full history, not just the latest observation. That history contains:
- A system prompt written by the tool's authors. It describes the agent's role and rules.
- Tool definitions. Each one has a name, a description, and a schema for its arguments.
- Your instruction file, such as CLAUDE.md or AGENTS.md, if one exists.
- Your messages, the model's earlier replies, and every observation so far.
Tool definitions are why the model can ask for run_shell with a command argument instead of free-form prose. The model chooses a tool in the same way it chooses words, by predicting the most likely continuation. Tool use is therefore usually right but not guaranteed. A model can name a file that doesn't exist, pass a malformed argument, or run the wrong test command. Those mistakes come back as observations, and the model often corrects itself on the next turn.
A runnable miniature
The sketch below contains no real model. fake_model is a stub that asks for one shell command and then answers, so you can watch the loop's structure. In a real tool, the stub is replaced by an API call.
import subprocess
ALLOWED_PREFIXES = ("echo ",) # stand-in for a permission rule
def fake_model(messages):
"""Stand-in for a real model call."""
if not any(m["role"] == "tool" for m in messages):
return {"type": "tool_call", "command": "echo hello from the tool"}
return {"type": "text", "text": "The command printed: " + messages[-1]["content"].strip()}
def is_allowed(command):
return command.startswith(ALLOWED_PREFIXES)
def run_tool(command):
result = subprocess.run(
command, shell=True, capture_output=True, text=True, timeout=30
)
return result.stdout + result.stderr
def agent(task, max_turns=10):
messages = [{"role": "user", "content": task}]
for _ in range(max_turns):
reply = fake_model(messages)
if reply["type"] == "text": # no tool request: the loop ends
return reply["text"]
command = reply["command"]
if is_allowed(command):
observation = run_tool(command)
else:
observation = "Denied: command is not allowed."
messages.append({"role": "assistant", "content": command})
messages.append({"role": "tool", "content": observation})
return "Stopped: reached the turn limit."
print(agent("Say hello using the shell"))Running it prints The command printed: hello from the tool. Four details matter, and they match real tools:
- The loop ends when the model answers without a tool request. Nothing else decides that the task is finished.
- A denial is an observation like any other. The model sees "Denied" and can try a different approach.
- A turn limit stops runaway loops.
- The tool call and its result are both appended to the history, so later turns can use them.
Turns, cost, and speed
Each iteration is a full model call over a growing history. A task that takes 15 tool calls costs 15 model calls, and the later calls are larger than the earlier ones. Two consequences follow:
- Latency adds up. Reading ten files one at a time takes ten round trips. Most tools let the model request several independent tools in one reply and run them together, which is why a well-behaved agent often reads many files at once.
- Context fills up. Large outputs such as a 2,000-line test log or a whole generated file consume the model's context window. Tools usually truncate big outputs or cache the repeated prefix of the history to reduce cost. They can't remove the underlying growth. The next chapters cover how to manage it.
Where control enters the loop
You can influence the loop at four points:
| Point in the loop | Mechanism | Covered later |
|---|---|---|
| Before the first call | Instruction files and your prompt | Instruction files, prompting workflow |
| Between request and execution | Permissions and approval modes | Permissions and approvals |
| Around execution | Sandbox limits on files and network | Sandboxing |
| After the loop ends | Your tests, diff review, and git | Verification, git workflow |
The permission check is the most important of these. Without it, whatever the model asks for runs with your user's privileges.
Common errors and gotchas
- Treating the final message as proof. The model's closing text says what it believes happened. A claim such as "all tests pass" is only reliable if an observation in the history shows a test run. Check the transcript or run the tests yourself.
- Stale knowledge. The model sees a file only when it reads it. If you edit a file in your editor during a session, the agent's earlier read of it is out of date until it reads the file again.
- Loops that don't converge. The agent can repeat a failing command with small variations. Interrupt it, state what you have observed, and narrow the task. Waiting rarely helps.
- Error output as instructions. Observations come from files, web pages, and command output, and that text can contain sentences that look like instructions. The model has no hard boundary between your request and text it read, which is the root of prompt injection. The security chapter returns to this.
- Non-determinism. The same prompt can take different paths on different runs. Treat a good run as evidence, not as a guarantee.
Exercises
Exercise
In the Python sketch, what happens if fake_model asks for rm -rf build instead of an echo command? What does the model see on its next turn, and why is that design useful?
Show answer
is_allowed returns False, so the command is never run. The harness appends the observation "Denied: command is not allowed." to the history. On the next turn the model sees that message and can choose another approach or explain that it was blocked. Returning the denial as an observation, instead of crashing, keeps the loop running and lets the model adapt. The check is also in the harness, so the model cannot skip it.
Exercise
An agent finishes with "I fixed the bug and all tests pass." The transcript contains no test run. What should you do, and what does this show about the loop?
Show answer
Run the tests yourself, or ask the agent to run them and read the output. The loop ends when the model stops requesting tools, not when the work is verified. The closing message is the model's prediction of a good summary. Only observations produced by real tool runs show what happened.