Keeping It Safe20 of 37
In Hooks in Your Agent you gave mini two lists of hooks: before-hooks that can block a tool call, and after-hooks that can change its output. Here you'll write the function that runs them, run_tool, the same way mini does. Nothing here calls a model: the tool calls come in as input, as if the model had written them.
The starter gives you a pretend folder of files and two tools:
read_file(path) returns a file's text, or raises FileNotFoundError for a file that isn't there;run_command(command) just returns ran: <command>.It also has six hooks. The before-hooks are no_secrets (blocks any path with .env in it), no_rm (blocks commands with rm in them) and only_txt (blocks reading a file that doesn't end in .txt). The after-hooks are cut_long (keeps the first 40 characters and adds [cut]), hide_keys (turns sk-... keys into sk-***) and tag (puts [tool name] in front of the output).
Two lines say which hooks are switched on, in order. Then a line with ---, then one tool call per line: its id, the tool's name, and its inputs as JSON:
before: no_secrets
after: cut_long
---
t1 read_file {"path": "notes.txt"}
t2 read_file {"path": ".env"}
t3 run_command {"command": "ls"}Fill in run_tool(block, before, after). It returns one tool_result dict, and main prints it as JSON. The rules, in order:
no tool called <name>."content": "Blocked: <reason>" with "is_error": True, and nothing else happens.TOOLS[name](**args). If it raises an error, return "content": "Error: <the error's message>" with "is_error": True. The after-hooks don't run.is_error key at all.For the example above, the output is:
{"content": "Buy milk.\nCall Sara about the March repo [cut]", "tool_use_id": "t1", "type": "tool_result"}
{"content": "Blocked: never read .env files", "is_error": true, "tool_use_id": "t2", "type": "tool_result"}
{"content": "ran: ls", "tool_use_id": "t3", "type": "tool_result"}mini's own run_tool uses reason = reason or hook(name, args) in a loop. That calls each hook only while nothing has blocked the call yet. Start with reason = None if name in TOOLS else f"no tool called {name}".
When it works, notice what you've built: mini's rules are no longer spread across its tools. Every call, from every tool, passes through the same few lines, in the same order, every time.
Sign in to try this exercise.