Sub topic 9
Telling the agent why it was blocked
This chapter assumes you can write a pre-action hook that reads a tool-call event from stdin and exits with code 2 to block it. It also assumes you know how to match a shell command against deny patterns. Here the focus is the message a blocked agent receives, because that message decides what the agent does next.
Why the message matters
A hook that only exits with code 2 stops one action. The agent still has its goal, so it will try something else. If the hook gave it nothing useful, the agent has to guess.
Guessing produces three bad outcomes:
- The agent retries the same command with small changes, such as a different flag order, until it gets through or wastes the session.
- The agent drops the task and reports failure, even though a safe route existed.
- The agent works around the rule in a way you never intended, for example by writing a script file that contains the blocked command.
A good message gives the agent the information a colleague would give when declining a request: what was refused, why, and what to do instead.
Where the message goes
Most hook systems follow the same convention. Check your agent's documentation for the exact behavior, because details differ between products.
| Exit code | Typical effect | Who sees stderr |
|---|---|---|
| 0 | The tool call proceeds. | Usually nobody. |
| 2 | The tool call is blocked. | The agent, as the tool result. |
| Any other non-zero code | The hook is treated as having failed. The call may still proceed. | Often only the user, as a warning. |
The last row is a trap. If your script crashes with a Python traceback, the exit code is 1, and many systems treat that as a non-blocking error. The agent sees nothing and the action may run. This is why the earlier chapter on failing closed matters. Your hook must catch its own errors and exit with 2 itself.
The flow of a block
The second attempt only works because the first message named an alternative. Without that, the agent would have no way to know that --force-with-lease was acceptable.
What a good message contains
Write each message with four parts, in this order:
- What was blocked. Name the rule with a short, stable identifier such as
no-force-push. The agent and your logs can refer to it later. - Why. One sentence on the harm the rule prevents. Agents follow rules better when they understand the reason.
- What to do instead. A concrete safe alternative, or a statement that none exists.
- What to do if the alternative does not fit. Usually this means stopping and asking the user.
Compare these messages for the same blocked command.
| Quality | Message |
|---|---|
| Vague | `Blocked.` |
| Accusing | `Dangerous command detected. This is not allowed.` |
| Useful | `Blocked by rule no-force-push: force pushes can overwrite teammates' commits. Instead: use git push --force-with-lease on your own feature branch. If that does not fit, stop and ask the user.` |
The first gives the agent nothing. The second gives it a reason to argue or work around the rule. The third lets it recover in one step.
A hook that builds structured messages
Keep rules as data, with an identifier, a reason, and an alternative next to each pattern. A single function then formats every block the same way, so no message ends up missing a field.
#!/usr/bin/env python3
import json
import re
import sys
RULES = [
{
"id": "no-force-push",
"pattern": r"\bgit\s+push\b.*--force(?!-with-lease)",
"reason": "Force pushes can overwrite other people's commits on the remote.",
"instead": "Use 'git push --force-with-lease' on your own feature branch.",
},
{
"id": "no-root-delete",
"pattern": r"\brm\s+-[a-zA-Z]*r[a-zA-Z]*f[a-zA-Z]*\s+/(\s|$)",
"reason": "Recursively deleting the filesystem root destroys the machine.",
"instead": "Delete a specific path inside the project, such as ./build.",
},
{
"id": "no-drop-table",
"pattern": r"\bdrop\s+table\b",
"reason": "Dropping a table deletes data that may not be recoverable.",
"instead": "Write a reviewed migration file and ask the user to run it.",
},
]
def block(message):
print(message, file=sys.stderr)
sys.exit(2)
def explain(rule):
return (
f"Blocked by rule {rule['id']}: {rule['reason']}\n"
f"Instead: {rule['instead']}\n"
"Do not retry this command in another form. "
"If no alternative fits the task, stop and ask the user."
)
try:
event = json.load(sys.stdin)
command = event["tool_input"]["command"]
if not isinstance(command, str):
raise TypeError("command is not a string")
except (json.JSONDecodeError, KeyError, TypeError):
block("Blocked by rule bad-hook-input: the hook could not read this tool call, "
"so it was not allowed. Ask the user to check the hook configuration.")
for rule in RULES:
if re.search(rule["pattern"], command, re.IGNORECASE):
block(explain(rule))
sys.exit(0)Three details are worth noting:
- The
(?!-with-lease)lookahead keeps the force-push rule from blocking the very alternative the message recommends. A rule that blocks its own suggested fix sends the agent into a loop. - The parse-failure message is also written for the agent, but it tells the agent to involve the user, since the agent cannot fix a broken hook.
- The line "Do not retry this command in another form" discourages small variations. It does not stop a determined bypass, which is covered in the chapter on hook limits.
Test the messages
Treat the message text as part of the behavior you test. Pipe events in and read what comes out.
echo '{"tool_name":"shell","tool_input":{"command":"git push origin main --force"}}' | python3 guard.py
echo "exit code: $?"
echo '{"tool_name":"shell","tool_input":{"command":"git push --force-with-lease"}}' | python3 guard.py
echo "exit code: $?"The first command should print the no-force-push message and then exit code: 2. The second should print only exit code: 0. If the second one is blocked, your pattern catches its own recommended alternative.
Keep the message safe
The agent's context may be logged, shared, or sent to a model provider. Apply the same care you would to any output.
- Do not echo the full command back. It may contain a password, token, or connection string. The rule identifier is enough for the agent to know what happened.
- Do not reveal the internals of the rule. Printing the full regular expression tells an agent, or a prompt injection attack, exactly how to phrase a command to slip past it. The reason and the alternative are what the agent needs.
- Do not include secrets in alternatives. Say "use the project's deploy script", not a command with a hard-coded credential.
- Keep it short. A few lines is enough. Long messages crowd the agent's context and are skimmed.
Handling repeated blocks
Agents sometimes hit the same rule several times in a row. Two habits help.
First, make the message consistent. The same rule should always produce the same text, so the agent recognizes a repeat and changes strategy.
Second, escalate in the text, not in logic. The line "If no alternative fits the task, stop and ask the user" gives the agent a defined way out. Without it, a determined agent may keep trying variations because it has no other instruction.
If you need to detect repeats, log each block with its rule identifier and count them across a session. That is the subject of the audit logging chapter.
Common mistakes
- Writing the explanation to stdout. In many systems stdout from a blocking hook is ignored or shown only in a transcript. Use stderr.
- Exiting with 1 after printing. The message is shown to the user as a warning, and the action may run.
- Blaming the agent. Words like "illegal" or "forbidden" add nothing. State the harm and the alternative.
- Offering an alternative that is also blocked. Test every suggested command against your own rules.
- Giving different messages for the same rule. Inconsistency makes repeat detection harder and confuses the agent.
Exercise
A hook blocks git reset --hard with the message "Blocked." and exit code 2. Rewrite the message so the agent can recover, and name two things it should not contain.
Show answer
A good message is: "Blocked by rule no-hard-reset: git reset --hard discards uncommitted work that cannot be recovered. Instead: use git stash to save changes, or git restore on specific files. If neither fits the task, stop and ask the user." It should not contain the full command text, which may include sensitive values, and it should not contain the regular expression that matched, which shows how to evade the rule. It also should not suggest an alternative that another rule blocks.
Exercise
Your hook crashes with an unhandled exception and exits with code 1. Why might the agent run the dangerous command anyway, and how do you prevent it?
Show answer
Many hook systems treat exit codes other than 2 as a non-blocking error. They show the stderr text to the user and let the tool call proceed, so the agent never sees a block. Prevent this by wrapping the parsing and checking logic in a try/except that calls sys.exit(2) with a clear message, so any failure fails closed.