Sub topic 1
How an Agent Acts: The Loop and Its Tool Calls
An AI coding agent does more than produce text. It reads files, edits code, and runs commands. A hook that blocks risky actions only makes sense once you know how those actions are requested and carried out. This chapter builds that working model. Later chapters add the hook itself.
Prerequisites
This chapter assumes you can:
- Use a shell and read a short shell command.
- Read and write JSON (objects, arrays, strings).
- Read basic Python. The examples use functions, dictionaries, and loops.
- Describe in general terms what an AI coding agent is, such as a tool that edits code and runs commands for you.
You do not need to have written a hook before.
The agent loop
An agent is a program wrapped around a language model. The model only produces text. The surrounding program, often called the harness, turns some of that text into real actions. The harness repeats the same cycle until the task is done:
- Send the conversation so far to the model.
- Read the model's reply. It is either a final answer or a request to use a tool.
- If it is a tool request, run the tool.
- Append the tool's output to the conversation and go back to step 1.
The model never touches your machine. It asks, and the harness decides whether and how to act. This split is what makes hooks possible. The harness is a program, so you can place checks inside it.
What a tool call contains
A tool is a named capability the harness offers to the model. Typical tools are a shell tool, a file-read tool, a file-write or edit tool, and a search tool. When the model wants one, it emits a structured request. The exact shape differs between products, but it always has the same parts:
- The tool name, such as
shellorwrite_file. - The input, a JSON object with arguments for that tool.
- Often an identifier, so the result can be matched to the request.
A shell tool call might look like this:
{
"tool_name": "shell",
"tool_input": {
"command": "ls -la"
}
}The command value is a string chosen by the model. Treat it like any other untrusted input. It comes from a system that reads web pages, issue text, and file contents, and any of those can influence what the model writes. That is why a check before execution is worth having.
A minimal loop in code
The script below is a complete agent loop with a scripted stand-in for the model, so it runs without any API key. The structure matches a real harness: ask the model, run the requested tool, feed the result back, and stop on a final answer or a step limit.
import subprocess
MAX_STEPS = 5
def run_shell(command):
done = subprocess.run(
command, shell=True, capture_output=True, text=True, timeout=10
)
return done.stdout + done.stderr
def read_file(path):
with open(path, encoding="utf-8") as handle:
return handle.read()
TOOLS = {"run_shell": run_shell, "read_file": read_file}
SCRIPT = [
{"type": "tool_call", "name": "run_shell", "input": {"command": "echo hello"}},
{"type": "final", "text": "The command printed hello."},
]
def fake_model(messages, step):
return SCRIPT[step]
messages = [{"role": "user", "content": "Say hello from the shell"}]
for step in range(MAX_STEPS):
reply = fake_model(messages, step)
if reply["type"] == "final":
print("Agent:", reply["text"])
break
tool = TOOLS.get(reply["name"])
if tool is None:
result = f"Error: unknown tool {reply['name']!r}"
else:
# A pre-action hook would run here, before the tool executes.
result = tool(**reply["input"])
messages.append({"role": "assistant", "tool_call": reply})
messages.append({"role": "tool", "content": result})
print("Tool result:", result.strip())
else:
print("Stopped: step limit reached")Running it prints the tool result hello, then the agent's final message. Three details matter for hooks:
- The comment marks the gap between "the model asked" and "the tool ran". A pre-action hook lives in that gap.
- The tool result is appended to the conversation, so whatever the harness returns shapes the model's next move. This includes error messages, which later chapters use to steer the agent.
MAX_STEPSis a basic guard. Without it, a confused model could loop indefinitely.
Who decides what runs
In practice the harness does not run every request blindly. Most agents have layers of control, and it helps to keep them separate in your head:
| Layer | Question it answers | Typical form |
|---|---|---|
| Tool availability | Which tools exist for this agent at all? | Agent configuration |
| Permissions | Is this tool allowed, denied, or ask-first? | Allow and deny lists, user prompts |
| Hooks | Does this specific call pass my custom check? | Your script, run at a fixed point |
| Sandbox | What can the process reach even if it runs? | Container, restricted user, filesystem limits |
Permissions usually work at the level of a tool or a command prefix. Hooks are different because they run your own code on the exact input of each call. They can check things a permission list cannot express, such as "any git push that includes --force" or "any write that resolves into infra/prod".
Side effects are what you protect
Some tool calls only read. Others change the world, and a few are hard or impossible to undo. Before you write any check, sort the tools you expose by what they can change:
- Reading files and searching change nothing on disk, though they can expose secrets to the model.
- Writing or editing files changes your working tree. Version control can usually recover this.
- Running shell commands can do anything the user account can do, including delete files, push to remotes, and call network services.
- Calls to external systems, such as cloud APIs or databases, change state that your local undo tools cannot reach.
The shell tool deserves the most attention. It is a general-purpose door. Every other capability, including file deletion and network access, can be reached through it. The later chapters on command checks and path protection concentrate on this tool and the file-writing tools for that reason.
Common errors in the mental model
These mistakes show up repeatedly when people first design hooks.
- Assuming the model is the actor. The model only proposes. The harness acts. If you think of the model as the one with access, you will look for controls in the wrong place. Controls belong in the harness, at the point where proposals become actions.
- Assuming one request means one action. A single shell string can chain several commands with
;,&&, pipes, or substitution. One tool call can contain many operations. A check that looks at only the first word will miss most of them. - Assuming tool names are stable across products. One agent calls its shell tool
shell, anotherBash, anotherexecute_bash. Always read your agent's documentation for the real names and field names. - Ignoring indirect effects. A harmless-looking file write can still do damage, for example when it edits a script that runs later or a configuration file that other tools trust.
- Forgetting that results feed back. Whatever you return from a failed or blocked action becomes input to the model's next turn. Vague errors lead to retries and workarounds. Clear ones lead to recovery.
Where this leads
You now have the pieces the rest of the tutorial uses. The loop gives you a fixed point before each tool runs. The tool call gives you structured data to inspect: a name and an input. The harness gives you a place to stop an action and a way to report why. The next chapters ask what counts as risky, define the lifecycle points where hooks run, and then build the hook contract.
Exercise
In the agent loop, which component actually executes a shell command: the model or the harness? Explain why this matters for where you place a safety check.
Show answer
The harness executes it. The model only produces a structured request naming the tool and its input. Because the harness sits between the request and the execution, a safety check placed there can inspect the exact tool call and stop it before it runs. A check inside the model's prompt cannot guarantee this, because the model's output is only a proposal.
Exercise
A shell tool call contains the command cd build && rm -rf cache; echo done. How many separate operations does this one tool call contain, and what does this imply for a check that only looks at the first word of the command?
Show answer
It contains three operations: cd build, rm -rf cache, and echo done. A check that looks only at the first word (cd) would see a harmless command and miss the rm -rf. Checks need to examine the whole command string, not just its start.