Sub topic 13
Timeouts and Keeping Hooks Fast
This chapter assumes you can write a basic hook that reads an event from stdin and exits with code 2 to block. It also assumes you know what a matcher is.
Why speed matters
A pre-action hook runs synchronously. The agent pauses at the proposed tool call, starts your script, and waits for the exit code. Every tool call that matches the hook pays your script's run time. If a hook takes two seconds and the agent makes 200 shell calls in a session, you have added about seven minutes of waiting.
Agents also enforce a timeout on hook scripts. The default and the setting name differ between agents, so check your agent's documentation. The risk is the same everywhere. When the timeout hits, the agent kills the hook and has to decide what to do.
A timeout can fail open
Many agents treat only exit code 2 as a block. A hook that is killed for running too long never exits with 2. Depending on the agent, the action may then proceed. This is a fail-open path, and it undoes the work from the fail-closed chapter.
Do not rely on the agent's timeout. Set a shorter deadline inside the script, and block when it expires.
#!/usr/bin/env python3
import json
import re
import signal
import sys
BLOCKED = [
re.compile(p, re.IGNORECASE)
for p in (r"\bgit\s+push\b.*--force", r"\bdrop\s+table\b")
]
def on_timeout(signum, frame):
print("Blocked: hook ran out of time, so the action was not allowed.", file=sys.stderr)
sys.exit(2)
signal.signal(signal.SIGALRM, on_timeout)
signal.alarm(2) # well below the agent's own timeout
try:
command = json.load(sys.stdin)["tool_input"]["command"]
except (json.JSONDecodeError, KeyError, TypeError):
print("Blocked: hook could not read the tool call.", file=sys.stderr)
sys.exit(2)
for pattern in BLOCKED:
if pattern.search(command):
print(f"Blocked: command matches {pattern.pattern!r}.", file=sys.stderr)
sys.exit(2)
sys.exit(0)signal.alarm works on Linux and macOS only. On Windows, use a watchdog thread or keep the script simple enough that it cannot stall.
Common causes of slow hooks
- Network calls. Calling an API or a policy server adds latency and a new failure mode. Prefer local rules.
- Heavy imports. Python start-up and large libraries can cost hundreds of milliseconds. Stick to the standard library.
- Rebuilding patterns on every call. Compile regexes once at module level, as above.
- Scanning the repository. Check the single path or command in the event. Do not walk the whole tree.
- Reading unbounded input. A very large command or file body can make a regex slow. Patterns with nested repetition can backtrack badly, so keep them simple.
- A missing matcher. A hook with no matcher runs for every tool, including cheap reads. Scope it to the tools it checks.
Measure it
Time the hook with a sample event, as in the testing chapter:
time (echo '{"tool_name":"shell","tool_input":{"command":"ls -la"}}' | python3 guard.py)Run it a few times and use the typical value. For a pattern check, aim for well under a few hundred milliseconds. If the number is much larger, look at imports and external calls first.
Keep slow work out of the hook
Some checks are expensive, such as scanning a file for secrets. Do the cheap decision in the pre-action hook. Move slow analysis to a post-action hook or to CI. This costs you prevention, because the action has already run by then. Reserve the pre-action hook for checks that must stop the action.
Exercise
Your pre-action hook calls a remote policy service. The service goes down, and the agent kills the hook at its timeout. Why is this risky, and what two changes reduce the risk?
Show answer
A killed hook never exits with code 2, so the agent may let the tool call run unchecked (fail open). First, set a short internal deadline and exit with code 2 when it passes. Second, replace the remote call with local rules, or limit it to a fast local cache, so the hook rarely needs to wait.