Sub topic 13
Timeouts and Keeping Hooks Fast
This chapter assumes you can write a pre-action hook that reads a tool-call event as JSON from stdin and exits with code 2 to block. It also assumes you know what a matcher is. The chapter covers how much time a hook gets, what happens when it runs out, and how to keep a hook quick without making it unsafe.
Why speed matters
A pre-action hook sits in the critical path. The agent proposes a tool call, then waits for every matching hook to finish before the call runs. A hook that takes 300 ms on every file read and shell command adds up over a session with hundreds of calls. A hook that hangs stalls the whole agent.
Speed also affects safety. If a slow hook is easy to hit its time limit, someone will be tempted to raise the limit or remove the hook. A fast hook is one people leave enabled.
What happens when a hook times out
Most agents give each hook a time limit. The default and the setting name vary, so check your agent's documentation. Some use milliseconds and some use seconds. The limit is often tens of seconds, which is long enough to freeze a session without anyone noticing why.
The important question is what the agent does when the limit is reached. Many agents treat a timeout as a non-blocking error: they log it and run the tool call anyway. That is the opposite of failing closed. If your hook can be made slow, whether by a huge input, a hung network call, or a pathological regex, then the check it was supposed to enforce can silently disappear.
Because of this, don't rely on the agent's timeout as your safety net. Set a shorter deadline inside the hook, and make it block when the deadline passes.
Where the time goes
For a script hook, the agent starts a new process for every matching tool call. The cost breaks down like this:
| Cost | Typical size | What to do |
|---|---|---|
| Interpreter startup | 10 to 50 ms for Python | Avoid heavy imports. |
| Imports | 0 to several hundred ms | Import only what the hook uses. |
| Parsing the event | Under 1 ms | Nothing needed. |
| Pattern matching | Under 1 ms for typical commands | Avoid nested quantifiers. |
| File system calls | Under 1 ms each, more on network mounts | Do them only when needed. |
| Network or subprocess calls | 10 ms to seconds | Set your own timeout. |
Matching a few regular expressions is almost never the bottleneck. Starting the process and calling out to other programs are. Because each run is a fresh process, precompiling regexes saves little: Python compiles them once per run either way. The real savings come from importing less and skipping work.
Keep the common path cheap
Order your checks from cheapest to most expensive, and exit as soon as you have an answer. Most tool calls are harmless, so the typical run should parse the event, run a few quick checks, and exit with 0.
This version of the guard reads the event, rejects oversized input, and does only string matching:
#!/usr/bin/env python3
import json
import re
import sys
MAX_COMMAND_LENGTH = 10_000
BLOCKED = [
re.compile(p, re.IGNORECASE)
for p in (
r"\brm\s+-[a-zA-Z]*r[a-zA-Z]*f[a-zA-Z]*\s+/(\s|$)",
r"\bgit\s+push\b.*--force",
r"\bdrop\s+table\b",
)
]
def block(message):
print(message, file=sys.stderr)
sys.exit(2)
try:
event = json.load(sys.stdin)
command = event["tool_input"]["command"]
except (json.JSONDecodeError, KeyError, TypeError):
block("Blocked: hook could not read the tool call, so it was not allowed.")
if not isinstance(command, str):
block("Blocked: command was not a string.")
if len(command) > MAX_COMMAND_LENGTH:
block("Blocked: command is too long to check. Split it into smaller steps.")
for pattern in BLOCKED:
if pattern.search(command):
block(f"Blocked: command matches risky pattern {pattern.pattern!r}. Use a safer alternative.")
sys.exit(0)Three details matter here:
- The imports are all from the standard library and all small. Avoid pulling in large packages such as
requestsoryamlfor a hook that only needsjsonandre. - The length cap protects against slow matching. A very long string can make a poorly written regex run for a long time. Blocking oversized input is the fail-closed choice. Silently truncating it would let a dangerous command hide past the cut-off.
- The hook exits on the first match. It does not collect every violation.
Avoid slow regular expressions
Python's re module can take exponential time on patterns with nested quantifiers, such as (a+)+$, when the input almost matches. Python's re has no built-in timeout, and a long-running match holds the interpreter, so a signal handler or timer thread cannot interrupt it. Prevention is therefore the only defense:
- Do not nest quantifiers like
(x+)+or(x*)*. - Prefer specific character classes over
.*in the middle of a pattern. - Keep input short with a length cap, as above.
- Test each new pattern against a long string of near-matches before you ship it.
Put a deadline on everything you call
If a hook runs another program, such as git, a secret scanner, or a policy service, give that call its own timeout. Handle the timeout by blocking:
#!/usr/bin/env python3
import subprocess
import sys
DEADLINE_SECONDS = 2
def block(message):
print(message, file=sys.stderr)
sys.exit(2)
try:
result = subprocess.run(
["git", "status", "--porcelain"],
capture_output=True,
text=True,
timeout=DEADLINE_SECONDS,
check=False,
)
except subprocess.TimeoutExpired:
block("Blocked: the repository check took too long, so the action was not allowed.")
except FileNotFoundError:
block("Blocked: git is not installed, so the repository check could not run.")
if result.stdout.strip():
print("Note: the working tree has uncommitted changes.", file=sys.stderr)
sys.exit(0)Keep the hook's total deadline below the agent's limit. If the agent allows 30 seconds and your hook makes two calls with a 2 second timeout each, the worst case is about 4 seconds plus startup. That leaves plenty of margin.
On Linux and macOS you can also set a watchdog for the whole script with signal.alarm. Register a handler for SIGALRM that prints a message to stderr and calls os._exit(2), then call signal.alarm(5) at the top of the script. This catches slow file system calls and similar waits. As noted above, it will not interrupt a regex match in progress. It also does not exist on Windows.
Let matchers do the first filter
The cheapest hook run is the one that never starts. A matcher scopes a hook to specific tools, so a shell guard does not run for file reads or searches. If your command check applies only to shell calls, set the matcher to the shell tool. If your path check applies only to write tools, scope it to those. This removes process startup from most tool calls.
Inside the hook, still check the tool name and exit quickly if it is not one you handle. Matchers can be misconfigured, and the extra check costs almost nothing. Decide deliberately what an unexpected tool name means: for a hook scoped to shell calls, a different tool name is not a risk to block, but a missing command field on a shell call is.
Measure it
Do not guess at hook speed. Time the full process with the same sample events you use for testing:
time (echo '{"tool_name":"shell","tool_input":{"command":"ls -la"}}' | python3 guard.py)
echo "exit code: $?"
LONG=$(python3 -c "print('a' * 20000)")
time (printf '{"tool_name":"shell","tool_input":{"command":"%s"}}' "$LONG" | python3 guard.py)
echo "exit code: $?"The first run shows the normal cost, which should be dominated by interpreter startup. The second confirms that oversized input is rejected quickly with exit code 2. As a rough target, aim for a typical run well under 100 ms. If it is much slower, run python3 -X importtime guard.py < event.json to see which import is responsible.
Common errors
- Assuming a timeout blocks. Many agents let the tool run when a hook times out. Enforce deadlines inside the hook.
- Network calls with no timeout. One unreachable server can stall every tool call until the agent gives up.
- Heavy imports at the top of the file. A large library adds startup time to every call, including harmless ones.
- Unbounded input. A very large command or file path list can make matching slow. Cap the length and block when it is exceeded.
- Slow code that is never measured. A hook that felt fast on your laptop may be slow on a network drive or in a container.
- Raising the timeout to fix flakiness. A longer limit hides the problem and makes a hang more costly. Find what is slow.
The time budget at a glance
Exercise
Your hook calls an internal policy server over HTTP before allowing each shell command. The agent's hook limit is 30 seconds, and you learn that the agent allows the tool call when a hook times out. The server is sometimes unreachable. What would you change in the hook?
Show answer
Add a short timeout to the HTTP request, for example 2 seconds, and treat a timeout or connection error as a block with a clear stderr message, so the agent does not wait for its own limit and the tool call is not allowed by default. Run the fast local deny-pattern checks first so most dangerous commands are blocked without any network call. Consider caching recent answers for a short time, or scoping the matcher so the server is only asked about shell calls.
Exercise
You run the guard on a 20,000-character command and it returns exit code 2 in a few milliseconds, but a colleague says it should truncate the command to 10,000 characters and check that part instead. Why is blocking the safer choice?
Show answer
A truncated check only inspects part of the command. A dangerous instruction placed after the cut-off would never be examined and would be allowed to run. Blocking oversized input means anything the hook cannot fully check is not allowed, which is the fail-closed behavior. The message should tell the agent to split the work into smaller commands.