Knaph

Keeping It Safe20 of 37

A Hook Pipeline

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.

What's already there

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).

The input

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"}

What to write

Fill in run_tool(block, before, after). It returns one tool_result dict, and main prints it as JSON. The rules, in order:

  1. An unknown tool is blocked with the reason no tool called <name>.
  2. The before-hooks run in order. As soon as one returns a reason, stop: the call is blocked, and the later hooks don't run.
  3. A blocked call returns "content": "Blocked: <reason>" with "is_error": True, and nothing else happens.
  4. Otherwise the tool runs, called with the inputs as keyword arguments: 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.
  5. Then the after-hooks run in order, each one on the output of the one before.
  6. A result that worked has no 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.