Sub topic 1
How a Coding Agent Acts: The Model, the Tools, and the Loop
A coding agent is a language model connected to tools and run in a loop. The model never touches your files or terminal itself. Every effect on your system comes from a tool call that the surrounding program carries out. This chapter explains that mechanism, because every permission control in the later chapters sits somewhere inside it.
Prerequisites
This chapter assumes you:
- Are comfortable in a terminal and know basic shell commands.
- Know basic git and use a code editor.
- Have used or seen an AI coding assistant that edits files or runs commands.
You don't need to know how language models work internally. You only need to know that a model takes text in and produces text out.
The three parts of an agent
A coding agent has three parts.
- The model reads text and produces text. It has no access to your machine. It can only describe what it wants to happen.
- The tools are functions the host program exposes, such as "read a file," "write a file," or "run a shell command." Each tool has a name and a description. It also has a schema, which lists the arguments the tool accepts.
- The harness is the program you install and run. It sends text to the model, receives replies, runs tools, and shows you the results. It is also called the runtime or the client.
The harness is the only part that acts on your system. Permission systems live in the harness, not in the model. That is why a rule like "never delete files" can be enforced reliably, while a request to the model to "please be careful" cannot.
From model output to a tool call
Along with your request, the harness sends the model a list of the available tools and their schemas. When the model decides it needs a tool, it doesn't reply with prose. It replies with a structured message, often JSON, that names a tool and supplies arguments. For example:
{
"type": "tool_call",
"name": "run_shell",
"args": { "command": "pytest tests/test_parser.py" }
}This message is only a request. Nothing has happened yet. The harness parses it, finds the tool called run_shell, and decides whether to run it. If it runs, the harness captures the output and sends it back to the model as a new message. The model reads the result and decides what to do next.
Two consequences follow.
- The model's output is untrusted input to the harness. The harness must validate and check it, as a web server checks a form submission.
- The harness sees the exact tool name and arguments before anything runs. That moment is where permission checks can happen.
The agent loop
The loop repeats until the model stops asking for tools.
Each pass through the loop is called a step or a turn. In each step:
- The harness sends the full conversation so far to the model. That includes your task, earlier replies, and all earlier tool results.
- The model replies with either a tool call or a final answer.
- For a tool call, the harness checks permission, runs the tool if allowed, and appends the result to the conversation.
- The loop goes back to step 1.
A denial is not the end of the task. The harness reports the refusal to the model as a tool result, and the model can try a different approach. This is useful, but it has a side effect covered below: an agent that is blocked may look for another route to the same goal.
A minimal agent in code
The following Python program is a complete agent loop with a scripted stand-in for the model, so it runs without any API key. The structure matches real agents. Only the model call differs.
import subprocess
from pathlib import Path
def read_file(path: str) -> str:
return Path(path).read_text()
def run_shell(command: str) -> str:
result = subprocess.run(
command, shell=True, capture_output=True, text=True, timeout=30
)
return result.stdout + result.stderr
TOOLS = {"read_file": read_file, "run_shell": run_shell}
def fake_model(messages):
"""Stand-in for a real model: asks for one tool call, then answers."""
last = messages[-1]
if last["role"] == "user":
return {
"type": "tool_call",
"name": "run_shell",
"args": {"command": "echo hello from the tool"},
}
return {"type": "text", "text": "The command printed: " + last["content"].strip()}
def agent_loop(task, model, max_steps=10):
messages = [{"role": "user", "content": task}]
for _ in range(max_steps):
reply = model(messages)
if reply["type"] == "text":
return reply["text"]
# A permission check would go here, before the tool runs.
tool = TOOLS[reply["name"]]
result = tool(**reply["args"])
messages.append({"role": "assistant", "content": str(reply)})
messages.append({"role": "tool", "content": result})
return "Stopped: step limit reached"
print(agent_loop("Say hello using the shell", fake_model))The output is The command printed: hello from the tool.
Look at the comment inside the loop. As written, this agent runs whatever the model asks for, with your user account's full authority. Adding a decision at that point is what the rest of this tutorial covers. Notice also max_steps. Without a step limit, a confused model could loop forever, so real harnesses cap steps, time, or cost.
What the model sees and what it controls
The model controls only the text it produces: which tool to call and what arguments to give. It does not control:
- Which tools exist. The harness decides that.
- Whether a call is allowed. The harness decides that too.
- What the tool does when run. That is fixed in the tool's code.
The model's choices are influenced by everything in the conversation. That includes your instructions, project files it has read, command output, and web pages it fetched. The model cannot reliably tell your instructions apart from instructions written inside a file it read. This is the root of prompt injection, a later chapter's topic. For now, remember that the conversation is the model's only input, and anything that reaches the conversation can steer the next tool call.
Why the loop makes permissions necessary
A single chat reply from a model is harmless until you act on it. An agent removes that gap. It acts on its own output, many times in a row, often without you reading each step. A task such as "fix the failing test" may produce a dozen tool calls: read files, run the test, edit a file, run the test again, and so on.
A few properties of the loop raise the stakes.
- Compounding. A wrong early step, such as a misread file, shapes every later step.
- Speed. The agent can issue calls faster than you can review them.
- Authority. Tools run with your user account's permissions. Unless a sandbox limits them, they can reach any file you can read and any credential in your environment variables.
- Indirect input. Content the agent reads can change what it does next.
None of this means agents are unsafe by nature. It means the tool call is the right place to put controls, because it is the one point where the model's intent becomes a real effect.
Kinds of tools
Most coding agents ship with a similar set of built-in tools. Later chapters sort these by risk, but a first pass looks like this.
| Tool type | Typical example | What it touches |
|---|---|---|
| File read | Open a file, list a directory, search text | Local files, no changes |
| File write | Create or edit a file | Local files, changes on disk |
| Shell execution | Run a command | Anything your account can reach |
| Network | Fetch a URL, search the web | Remote servers and their content |
| External tools | Tools added by plugins or servers | Whatever that tool connects to |
Shell execution deserves special attention. A shell tool is a general-purpose tool. One call can read, write, delete, and contact the network, depending on the command string. A file-read tool does one narrow thing and is easy to reason about. A shell command can do almost anything, so it is hard to judge from a short string.
Common mistakes
- Treating the model as the enforcer. Telling the model "don't touch the
.envfile" is a request, not a control. Enforcement has to be in the harness or the operating system. - Assuming a denied action stops the goal. The model sees the denial and may try another tool to get the same result, for example editing a file through a shell command after the edit tool is blocked.
- Forgetting the conversation is input. Any text the agent reads becomes part of what it reasons about.
- Ignoring step limits. Long loops cost money and time, and give a mistake more room to compound.
Exercise
In the agent loop, the model returns {"type": "toolcall", "name": "runshell", "args": {"command": "rm -rf build"}}. Has the build directory been deleted at that point? Which part of the system can prevent the deletion, and what happens to the model afterwards if it does?
Show answer
No. The model's reply is only a request, so nothing has been deleted yet. The harness decides whether to run the tool, and its permission check sits between the request and the execution. If the harness refuses, it appends an error message to the conversation as the tool result. The model reads that result on its next step and may try a different approach.