Sub topic 1
How an agent acts: the loop and its tool calls
Prerequisites
Assume you can run shell commands, read JSON, and write basic Python. You should also understand that an AI coding agent can call tools such as a shell, file editor, or test runner.
The agent loop
An agent repeats a simple cycle:
- It reads the task and current context.
- It chooses an action, such as running a command.
- It sends a structured tool call to the tool.
- It receives the result.
- It uses that result to choose the next action.
A hook is a script that runs at a defined point in this cycle. A pre-action hook runs after the agent proposes a tool call but before the tool executes.
What counts as risky
Risk depends on the tool, target, and possible impact. Common examples include:
- Deleting files or directories.
- Force-pushing Git history.
- Dropping database tables.
- Writing outside the project directory.
- Changing production infrastructure.
- Reading secrets or modifying access controls.
A useful check considers both the operation and its target. For example, rm is not always dangerous, but rm -rf / is catastrophic. A write to .env or infra/prod deserves more protection than a write to a temporary test file.
Where hooks run
Hooks commonly run before or after tool use. A pre-action hook can inspect and stop a proposed call. A post-action hook can record the result, run validation, or alert a reviewer. Only the pre-action position can reliably prevent that specific tool call from starting.
The hook sees the event supplied by the agent. It does not automatically control actions that bypass the agent, use another process, or occur after approval.
The hook contract
The usual contract is:
- The agent writes an event as JSON to the hook's standard input.
- The hook inspects fields such as
tool_nameandtool_input. - Exit code
0allows the call. - A nonzero exit code, often
2, denies it. - A message explains the decision so the agent or user can recover.
import json
import sys
try:
event = json.load(sys.stdin)
command = event["tool_input"]["command"]
except (json.JSONDecodeError, KeyError, TypeError):
print("Blocked: invalid tool event.", file=sys.stderr)
sys.exit(2)
if command.strip().startswith("rm -rf /"):
print("Blocked: refusing to delete the root directory.", file=sys.stderr)
sys.exit(2)
sys.exit(0)The exact field names and exit meanings vary by agent. Confirm the host agent's documentation before deploying a hook.
Exercise
At what point can a pre-action hook prevent a shell command from running?
Show answer
After the agent proposes the tool call and before the shell tool executes it.