Hooks in Your Agent
mini now asks before it writes a file. But Leila has two more rules. Her folder has a .env file with the company's passwords in it, and mini must never read it, not even with her permission at two in the morning. And a command that prints 50,000 lines must not pour all of them into the context. Neither of these is a question to ask the person. They are rules that should hold every single time.
Leila I could add both to check_permission. One more if for .env, and the long output... no, that one happens after the tool runs. check_permission is too early.
Omid So there are two moments: before a tool runs, and after it has run. How many rules will there be at each moment, a year from now?
Leila More than two. Somebody will want to log every command, or remove passwords from the output, or format every file mini writes.
Omid Would you want to edit run_tool for each one?
Leila Not really. I'd rather have a list for each moment, and add a function to it.
Omid That's exactly what a hook system is. Claude Code reads its lists from a settings file, and its hooks are usually shell commands. In mini, a hook is a Python function, and the list is a Python list.
Two lists of functions
A hook in mini is a plain function that run_tool calls at a fixed moment of every tool call: the idea from agent hooks, in your own code. There are two moments, so there are two lists:
def no_secrets(name, args): # a before-hook: blocks, every time
if ".env" in args.get("path", ""):
return "mini never reads .env files"
def cut_long_output(name, args, output): # an after-hook: changes the result
if len(output) > MAX_OUTPUT:
return output[:MAX_OUTPUT] + f"\n[... {len(output) - MAX_OUTPUT} more characters cut]"
return output
BEFORE_TOOL = [no_secrets]
AFTER_TOOL = [cut_long_output]The two kinds have different jobs, and their shapes show it:
- A before-hook gets the tool's name and inputs. It returns
Noneto let the call go on, or a reason to block it, just likecheck_permission. - An after-hook gets the name, the inputs and the tool's output, and returns the output to use: the same text, or a changed version.
no_secrets has no "ask" and no exceptions. That's the point: a rule in a hook can't be argued with, by the model or by a person in a hurry. And cut_long_output is the cut from Tools That Touch Files, moved to the one place where it applies to every tool at once.
Running the hooks
Here is run_tool with both lists in it. This is the version in mini from now on:
def run_tool(block, allowed):
name, args = block.name, block.input
reason = None if name in allowed else f"no tool called {name}"
for hook in BEFORE_TOOL:
reason = reason or hook(name, args)
reason = reason or check_permission(name, args)
if reason:
return {"type": "tool_result", "tool_use_id": block.id, "content": f"Blocked: {reason}", "is_error": True}
try:
output = str(TOOLS[name][0](**args))
except Exception as error:
return {"type": "tool_result", "tool_use_id": block.id, "content": f"Error: {error}", "is_error": True}
for hook in AFTER_TOOL:
output = hook(name, args, output)
return {"type": "tool_result", "tool_use_id": block.id, "content": output}What to notice:
reason or hook(...)calls a hook only while nothing has blocked the call yet. So the first hook to block wins, and its reason is what the model reads.- Before-hooks run before the permission question. If
no_secretsblocks a read of.env, Leila is never even asked. A rule that can't be overridden shouldn't ask. - After-hooks run in order, each on the last one's output. Order matters: a hook that removes passwords should run before one that cuts the text short, or a password could sit right at the cut.
- After-hooks don't run when the tool failed. An error goes straight back to the model.
A check before stopping
Claude Code has hooks at more moments than these two, and one of them is especially useful: a check when the agent is about to say it's done. In mini, "about to say it's done" is the line in the loop where stop_reason is "end_turn". A check there could run the tests, and if they fail, send the model back to work instead of finishing:
if response.stop_reason == "end_turn":
tests = run_command("python -m pytest -q")
if not tests.startswith("exit code 0") and checks_left > 0:
checks_left -= 1
messages.append({"role": "user", "content": "The tests fail, so the task isn't done yet:\n" + tests})
continue
return "".join(b.text for b in response.content if b.type == "text")This isn't in mini.py, because not every project has tests. It's a change you can make for one that does. Two details matter. The failure goes back as an ordinary user message, because the last message was the model's final answer, and roles must take turns. And checks_left (say, 3, set before the loop) stops the two of them going round for ever on a test the model can't fix.
Try it
Add a third before-hook to mini that blocks any
write_filewhose path ends in.pyunless the content contains noTODO. (Its body is three lines.) Then ask mini to "write a Python file with a TODO in it" and read the Blocked result it gets. No key? Write the hook anyway, and call it by hand:print(no_todo("write_file", {"path": "a.py", "content": "# TODO"})).
Using it well
- Use a before-hook for a rule with no exceptions. If you'd never answer yes, don't ask the question: block it in a hook.
- Use an after-hook to change every result in the same way. Cutting long output, hiding secrets, adding a note: write it once and it applies to every tool, including ones added later.
- Think about order. Hooks in a list run one after another; put the ones that remove things before the ones that shorten or reformat.
- Give every loop an exit. A check that can send the agent back to work needs a limit, or one failing test becomes an endless, expensive session.
Words to know
- before-hook - a function the harness runs before every tool call; it can block the call with a reason
- after-hook - a function the harness runs after every successful tool call; it gets the output and returns the output to use
- stop check - code that runs when the agent is about to finish, and can send it back to work, for example when the tests fail
Big idea
In your own agent, hooks are just lists of functions that run at fixed moments of every tool call: before (they can block) and after (they can change the result). A rule there holds every time, because it's your code that runs it, not the model that remembers it.