Sub topic 8
Allow, deny, or ask the user
This chapter assumes you can write a small Python script, read JSON, and already know the hook contract from earlier chapters: the agent sends the tool-call event on stdin, and the hook answers with an exit code and a message. Here we look at the decision a hook makes after it inspects a call. A hook can do more than "block or not block". Usually three outcomes are available, and picking the right one for each rule decides whether the hook is useful or annoying.
The three outcomes
| Decision | Meaning | Typical use |
|---|---|---|
| Allow | The call runs with no interruption. | Reads, listing files, running tests. |
| Deny | The call never runs, and the agent is told why. | Actions that are never acceptable in this project. |
| Ask | The call pauses until a human approves or rejects it. | Actions that are sometimes right and are hard to undo. |
Allow is the default. A hook that has no opinion about a call should stay silent and exit with code 0. Deny and ask each cost something. A deny wastes a turn if the agent has to find another route. An ask interrupts the person, and if it happens too often they stop reading the prompts.
How each decision is expressed
The common convention for a pre-action hook is:
- Exit code 0 means allow.
- Exit code 2 means deny. The text the hook writes to stderr goes back to the agent.
- Any other exit code means the hook itself failed.
The last item is a trap. In some agents, including Kiro CLI at the time of writing, an exit code other than 0 or 2 shows a warning and the tool still runs. That makes a crashed hook fail open. The next chapters cover failing closed, so for now remember to exit with code 2 deliberately and not let an uncaught exception decide for you.
Ask is the least standardized. Some agents let a hook print a JSON object to stdout with exit code 0, containing a permission decision of allow, deny, or ask and a reason. Claude Code works this way: it uses a hookSpecificOutput object with permissionDecision and permissionDecisionReason fields. Other agents have no ask output for hooks. There, the way to get a human confirmation is to leave the call alone (exit 0) and let the agent's own permission prompt handle it, or to deny it and tell the agent to ask the user in the conversation. Check your agent's documentation for the exact field names before relying on any of this.
Choosing between deny and ask
Use these questions for each rule.
- Is there ever a legitimate reason to do this in this project? If not, deny.
- Can the effect be undone cheaply, for example with
git revert? If so, allow, or at most ask. - Would a human know something the hook does not, such as whether this push is meant for the release branch? If so, ask.
- Is the agent likely to run unattended, such as in CI? If so, ask has no one to answer it. Deny, or make sure the agent's non-interactive mode treats an unanswered ask as a rejection.
Some examples:
rm -rf /has no legitimate use here. Deny.git push --forceis rarely right and can destroy shared history. Deny, with a message that points to--force-with-leaseor to asking the user.- A plain
git pushis routine but publishes work. Ask. terraform applychanges real infrastructure. Ask.ls,cat,pytest. Allow.
A hook with all three outcomes
The script below checks deny rules first, then ask rules, and allows everything else. Order matters. git push --force matches both a deny rule and the ask rule for git push, and the deny must win. Evaluating the strictest decision first keeps a looser rule from hiding a stricter one.
#!/usr/bin/env python3
import json
import re
import sys
DENY = [
(r"\brm\s+-[a-zA-Z]*r[a-zA-Z]*f[a-zA-Z]*\s+/(\s|$)",
"Deleting the filesystem root is never allowed."),
(r"\bgit\s+push\b.*--force(?!-with-lease)",
"Force pushes can destroy shared history. Use --force-with-lease or ask the user."),
]
ASK = [
(r"\bgit\s+push\b", "This publishes commits to a remote."),
(r"\bnpm\s+publish\b", "This publishes a package."),
(r"\bterraform\s+apply\b", "This changes real infrastructure."),
]
def decide(command):
for pattern, reason in DENY:
if re.search(pattern, command, re.IGNORECASE):
return "deny", reason
for pattern, reason in ASK:
if re.search(pattern, command, re.IGNORECASE):
return "ask", reason
return "allow", ""
def main():
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):
print("Blocked: hook could not read the tool call, so it was not allowed.",
file=sys.stderr)
sys.exit(2)
decision, reason = decide(command)
if decision == "deny":
print(f"Blocked: {reason}", file=sys.stderr)
sys.exit(2)
if decision == "ask":
print(json.dumps({
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "ask",
"permissionDecisionReason": reason,
}
}))
sys.exit(0)
sys.exit(0)
main()Save it as guard.py. The JSON on stdout is the ask format described above. If your agent does not read that format, it ignores the output and the call is allowed, so confirm how your agent treats it before you depend on ask.
The force-push pattern uses a negative lookahead, (?!-with-lease), so the safer --force-with-lease flag is not denied. It is a rough pattern. For example, it will still deny a command that contains --force-with-lease and, separately, --force.
Testing each outcome
Pipe sample events into the script, as covered in the testing chapter, and check both the exit code and the output.
echo '{"tool_name":"shell","tool_input":{"command":"rm -rf /"}}' | python3 guard.py
echo "exit code: $?"
echo '{"tool_name":"shell","tool_input":{"command":"git push origin main"}}' | python3 guard.py
echo "exit code: $?"
echo '{"tool_name":"shell","tool_input":{"command":"pytest -q"}}' | python3 guard.py
echo "exit code: $?"
echo 'not json' | python3 guard.py
echo "exit code: $?"Expected results:
| Input | Exit code | Output |
|---|---|---|
| `rm -rf /` | 2 | stderr: `Blocked: Deleting the filesystem root is never allowed.` |
| `git push origin main` | 0 | stdout: JSON with `permissionDecision` set to `ask` |
| `pytest -q` | 0 | nothing |
| `not json` | 2 | stderr: `Blocked: hook could not read the tool call...` |
Only the second row distinguishes ask from allow, and only by its stdout. A test that checks the exit code alone cannot tell them apart, so assert on the output as well.
Common mistakes
- Asking too often. If every
git committriggers a prompt, people approve without reading. Keep ask for actions that are rare and consequential, and allow the rest. - Denying without a way forward. "Blocked." gives the agent nothing to act on. A reason that names the safer alternative lets it recover in the same turn, as the next chapter shows.
- Depending on ask in unattended runs. With no human present, an ask may hang or be treated as approval, depending on the agent. Test the unattended case explicitly.
- Rule order that hides stricter rules. Check deny before ask, and ask before allow.
- Treating ask as a security boundary. A person who is tired or in a hurry will approve it. Anything that must never happen belongs in deny, or in a layer outside the agent.
Exercise
A hook has the rules "ask before any git push" and "deny any git push with --force". The command is git push --force origin main. In which order must the hook evaluate the rules, and what should the result be? What would go wrong with the opposite order?
Show answer
Evaluate deny rules first, then ask rules. The command matches both, and the strictest decision wins, so the result is deny: exit code 2 with a reason on stderr. If the ask rule ran first, the hook would return ask and a person could approve a force push that the policy says must never happen, possibly by clicking through a prompt without reading it.
Exercise
Your agent runs unattended in CI and has no way to answer prompts. You want terraform apply to require a human in interactive sessions. How would you handle that rule, and how would you verify it?
Show answer
First find out how the agent treats an ask when no one can answer. If it rejects or hangs, either is acceptable only if it never approves by default. If the behavior is unclear, make the hook detect the non-interactive case (for example, an environment variable that your CI sets) and deny with a message such as "terraform apply needs human approval; run it interactively." Verify by piping a terraform apply event into the hook with and without that variable set, and check that the CI case exits with code 2 and the interactive case produces the ask output.