Sub topic 3
Where hooks run in the agent lifecycle
This chapter places hooks inside the agent loop. You will learn which events a hook can attach to, what each point can and cannot control, and why the pre-action point is the one that matters for blocking risky actions.
It assumes you can read JSON, run shell commands, and read short Python scripts. It also assumes you know that an AI coding agent proposes tool calls, such as running a shell command or editing a file, and that something executes them.
The loop that hooks attach to
An agent works in a loop. The model reads the conversation so far and either writes a reply or asks for a tool call. The agent runtime, which is the program around the model, runs the tool and appends the result to the conversation. The model then reads that result and decides what to do next.
The model never touches your machine directly. It only produces text that describes a tool call, for example "run npm test". The runtime turns that description into an action. This split is what makes hooks possible. A hook is a script the runtime runs at a fixed point in the loop, outside the model, so the model cannot talk its way past it.
A hook is plain code. It is not another model call, so it behaves the same way every time. If a rule says "never run git push --force", a hook enforces it with a pattern match, and a persuasive prompt does not change the outcome.
The lifecycle events
Hook systems expose a small set of named events. The names differ between products. Claude Code writes PreToolUse, and Kiro CLI uses camelCase names such as preToolUse. The shape is nearly the same everywhere.
| Event (typical name) | When it fires | Typical use |
|---|---|---|
| Session or agent start | When a session begins | Load project context, check the environment |
| User prompt submit | After the user sends a message, before the model sees it | Add context, reject prompts that contain secrets |
| Pre-tool-use | After the model requests a tool call, before the tool runs | Allow, block, or inspect the action |
| Post-tool-use | After the tool finishes | Format files, run linters, log results |
| Stop | When the agent finishes its turn | Run final checks, send notifications |
This tutorial is mostly about the pre-tool-use event. It is the only point where the action has been proposed but has not yet happened, so it is the only point where a hook can prevent something.
What the pre-tool hook can control
A pre-tool hook sits between the model's request and the tool. It receives the proposed call and answers with a decision. Because it runs before execution, it can do three things.
- Let the call through. The tool runs as the model asked.
- Stop the call. The tool never runs. The runtime sends the hook's message back to the model as the outcome of the call, so the model can adjust.
- Escalate to the user. Some systems let a hook turn the call into a confirmation prompt. The later chapter on allow, deny, and ask covers this.
The hook also gets to see the complete arguments. For a shell tool that is the full command string. For a file tool it is the target path and often the new content. Rules can therefore match on what the action will actually do, and not only on which tool was chosen.
What the pre-tool hook cannot control
Knowing the limits early prevents wrong assumptions later.
- It cannot see the model's reasoning. It sees the request only, not why the model made it.
- It cannot see what a command will do internally. A hook sees the string
bash deploy.sh. It does not see whatdeploy.shruns. The stringpython -c "..."hides its payload from simple pattern checks. A later chapter covers these bypass risks. - It does not cover actions that bypass the tool layer. Anything a tool does as a side effect, and anything done by a process the agent starts earlier, is outside its view.
- It does not replace permissions. The hook is one decision point among several, and a sandbox or operating-system permissions still apply when the hook allows a call.
What the other events are for
The pre-tool event gets the most attention here, but the other events have clear roles, and picking the wrong one is a common mistake.
Post-tool hooks run after the action. The effect has already happened, so a post-tool hook cannot undo it. Use it for work that follows an action, such as running a formatter on a file that was just edited, recording an audit entry, or checking that the result looks right. If your goal is "this must not happen", a post-tool hook is the wrong place. It can warn, and in some systems it can feed a message back to the model, but the file has already been written.
Prompt hooks run before the model reasons. They can add context or reject a message, but they do not see tool calls. A prompt hook cannot tell whether the model later decides to run a destructive command.
Start and stop hooks bracket the session. A start hook is a good place for one-time setup, such as printing the branch name into the context. A stop hook runs when the agent believes it is done, so it suits final checks such as "did the tests pass?". Neither is a safety gate for individual actions.
A useful rule is to match the hook to the question. To ask "should this action happen?", use pre-tool. To ask "what should follow this action?", use post-tool. To ask "what should the model know?", use start or prompt.
Registering a hook
Hooks are configured in the agent's settings. The runtime reads the configuration, and for each event it runs the commands listed under it. The sketch below follows the general shape of Kiro CLI's agent configuration. Treat the key names as illustrative and check your agent's documentation for the exact fields.
{
"name": "careful-agent",
"hooks": {
"preToolUse": [
{
"matcher": "execute_bash",
"command": "python3 guard.py"
}
],
"postToolUse": [
{
"matcher": "fs_write",
"command": "python3 log_edit.py"
}
]
}
}Two details matter here. Each event holds a list, so you can attach several hooks to the same point. The matcher field limits a hook to certain tools, so guard.py is not started for every file read. The chapter on matchers covers this field in detail.
Seeing the lifecycle yourself
Before you write any blocking logic, it helps to watch which events fire. The script below records every event it receives to a log file and always allows the action. Run it from a pre-tool slot and a post-tool slot, and the log shows the order of events.
#!/usr/bin/env python3
import json
import sys
import time
try:
event = json.load(sys.stdin)
except json.JSONDecodeError:
event = {"unreadable": True}
record = {
"time": time.strftime("%H:%M:%S"),
"event": event.get("hook_event_name", "unknown"),
"tool": event.get("tool_name", "unknown"),
}
with open("hook-trace.log", "a", encoding="utf-8") as log:
log.write(json.dumps(record) + "\n")
sys.exit(0)This script is only a probe, so it exits 0 even when the input is unreadable. A real guard should not do that. The chapter on failing closed explains why. Field names such as hook_event_name vary between products, which is why the script uses .get() with defaults instead of assuming a fixed shape.
After one agent turn that edits a file, the trace typically shows the pre-tool entry first and the post-tool entry second, with the tool's work between them. That ordering is the whole point of the lifecycle. The pre-tool entry exists while the file is still unchanged, and the post-tool entry exists after the change is on disk.
Common mistakes at this stage
- Putting a safety rule in a post-tool hook. The rule runs, but only after the damage is done.
- Assuming the model learns from a silent block. A hook that blocks without a message leaves the model guessing. It often retries the same call. Always return a reason.
- Assuming one event name works everywhere. If you move a hook between agents, re-check the event names and the fields in the JSON.
- Treating the pre-tool hook as the only guard. It is the first line of defense, and the sections on limits and layering explain what else you need.
Exercise
A teammate wants to stop the agent from overwriting .env files. They propose a post-tool hook on the file-write tool that deletes the write if the path is .env. Which event should they use instead, and why?
Show answer
They should use a pre-tool hook. A pre-tool hook runs after the model requests the write and before the tool executes, so it can stop the write and return a reason to the model. A post-tool hook runs after the file has already been changed, so it can only react to damage that has happened. Deleting or restoring afterward is also fragile, because the original contents may already be lost.