Block rm -rf in Kimi Code CLI with a PreToolUse hook and check the exit codes
Add a PreToolUse rule to config.toml. The script reads the JSON on stdin and exits with code 2 when it sees rm -rf. Pipe-test codes 0 and 2 first, then trigger it in a session. Kimi Code was not run for this batch.
Task and deliverable · Prerequisites · How a hook decides to allow or block
At a glance
A hook in Kimi Code CLI is a trigger rule written in ~/.kimi-code/config.toml. When the named event fires, the CLI passes the event details to your script as JSON on stdin, then reads the exit code to decide whether to allow or block. The "Blocking Dangerous Shell Commands" example on the official Hooks page matches the Bash tool on the PreToolUse event and makes the script exit with code 2 when the command contains rm -rf. This article walks through that example as one complete task: save the script, pipe JSON into it to check exit codes 0 and 2, add the [[hooks]] rule, trigger it in a session, and finally see why fail-open means the hook cannot be your only safeguard. Kimi Code CLI was not installed, signed into or run for this batch. The pipe checks only ran the official script with Node on a local machine. What happens inside a session is behavior the official pages describe, and this site did not test it.
From PreToolUse trigger to allow or block
The rule matches
When the agent in a session is about to call the Bash tool, the CLI fires the
PreToolUseevent before the permission check.matcheris a regular expression that filters event targets; forPreToolUseit is matched against the tool name, and the example usesBash. The official page does not say whether the expression must match the whole name.JSON arrives on stdin
The CLI packs the event details into JSON and passes them to the script on standard input. The base fields are
hook_event_name,session_id,session_title,client_typeandcwd, all in snake_case. The official script also readstool_input.command.The script picks an exit code
The official script checks whether
commandcontains the stringrm -rf. If it does, the script writes a reason to stderr and exits with code 2. If not, it ends normally with exit code 0.How the CLI reacts
Exit code 0 allows. Exit code 2 blocks, and the stderr text is used as the reason and written back into the context. Any other non-zero exit code, a timeout or a crash allows the call anyway; this is called fail-open.
Check in layers
Pipe-test codes 0 and 2 first, then trigger the rule once in a session. Because of fail-open, a script that errors or times out means this hook does not block the call; the official page says high-risk operations should also rely on permission approval and manual confirmation.
Task and deliverable
The task is to add one small guard to the command-line version of Kimi Code: when a Bash command the agent wants to run contains rm -rf, stop it before it runs and hand the reason back to the model so it can pick a safer approach. The official Hooks page lists this kind of use as "security interception", and the example uses the PreToolUse event.
There are two deliverables: a [[hooks]] rule in ~/.kimi-code/config.toml and a guard script that reads JSON from stdin. You can judge completion at three levels. First, the script passes the pipe test: input with rm -rf gives exit code 2 and a reason on stderr, and input without it gives exit code 0. Second, the rule fires in a new session and you can confirm that the target Bash call was blocked by this hook; if you cannot confirm it, record the test as inconclusive. Third, you know that a script error or timeout means this hook does not block, so the hook cannot carry the safety burden alone.
This article uses only the official Hooks page and the configuration files page. Where a page is silent, the text says "the page does not say" and does not guess. Kimi Code CLI was not installed, signed into or run for this batch. Material labelled "site illustration" was written by this site to make checking easier and is not official text.
Prerequisites
- Kimi Code CLI installed, with the ability to open a session in a local project directory. The two documentation pages used here do not cover installation or sign-in, and this batch installed and signed into nothing, so that part is not expanded. The pipe test needs no sign-in.
noderunnable from the shell on the machine that runs Kimi Code. The officialcommandisnode ~/.kimi-code/hooks/block-dangerous-bash.mjs. The page does not say which Node version is required, whether the CLI bundles Node, or how~is expanded on Windows.- Permission to edit the user-level config
~/.kimi-code/config.toml. The configuration page says the CLI reads its configuration there and creates the file on first run; if theKIMI_CODE_HOMEenvironment variable is set, the path becomes$KIMI_CODE_HOME/config.toml. Hook rules live only in this user-level file and in local plugins, and the Hooks page states there is no project-level hook file. - A throwaway directory holding one unimportant file, for the in-session test. Step 4 asks the agent to run
rm -rfagainst it, and if the hook fails to block, the command may really run. - If you already have a config, append to it and do not overwrite it. Each
[[hooks]]entry allows only the four fieldsevent,matcher,commandandtimeout; any extra field makes the config file fail to load.
How a hook decides to allow or block
A rule answers three questions: which event triggers it (event), which targets it matches (matcher, optional, a regular expression, matching everything when omitted), and which command it runs (command, one shell command). There is also an optional timeout in seconds, from 1 to 600 and defaulting to 30; the official example sets 5. When several rules match one event, all matching hooks run in parallel, and rules with identical command values run only once. The page does not say how blocking results from several hooks are combined.
PreToolUse is one row in the event reference: the matcher matches the tool name, blocking is supported, it fires before a tool call and before permission checks, and the tool does not execute if blocked. Only PreToolUse, Stop and UserPromptSubmit return values that affect the main flow. Every other event is observation-only and fires and forgets, so putting a guard script on an event such as PostToolUse changes nothing.
On each trigger the CLI passes base information to the script as JSON on stdin. This is the example from the page, with every field name in snake_case:
{
"hook_event_name": "PreToolUse",
"session_id": "session_abc",
"session_title": "Fix the login page",
"client_type": "kimi_code_cli",
"cwd": "/path/to/project"
}Specific events add more fields. The page gives tool name and command content as examples, but the event reference does not list the PreToolUse payload field by field. The official script reads payload.tool_input?.command, the only PreToolUse field path that appears on the page, and the pipe tests below use only that field.
The script talks back through two channels: the exit code and stdout. Exit code 2 means block, and then the stderr content is the reason for blocking. After a block, the CLI writes the reason back into the context, and the model can use it to choose a safer alternative. The page also shows a second way to block: print JSON to stdout with permissionDecision set to deny. The page does not say whether that form also needs a particular exit code, and the example in this article does not use it.
A blocked call also triggers PostToolUseFailure, which the page describes as firing "after a tool fails or is blocked". It is an observation-only event. The page gives no example of using it to count blocks, so this article does not go further.
Exit codes and what the CLI does
The first three columns of the table below come from the official "Return Values" section. The last column is what this site observed locally when pipe-testing the official script, and it only shows how the script itself behaves.
| Exit code or case | Meaning on the page | CLI behavior on the page | Matching input in this site's pipe test |
|---|---|---|---|
| 0 | Normal exit, allow | Continue execution; stdout content, if any, may be appended to the context | JSON for ls -la: the script prints nothing and exits 0 |
| 2 | Intentional block | Stop the current operation; stderr content is used as the reason for blocking | JSON for rm -rf ./dist: stderr shows "Dangerous command detected, blocked" and the exit code is 2 |
| Other non-zero | Script error | Default allow (fail-open) | not json: JSON.parse throws an uncaught exception and Node exits with code 1, which falls in this row, so by the page the call is allowed |
| Timeout or crash | Script exception | Default allow (fail-open) | Not simulated in this batch; the timeout is set by the timeout field, 1 to 600 seconds, 30 by default |
When a hook cannot start, times out or exits with an error code, the CLI logs the failure and shows a one-time warning in the session; later failures are only logged. The page does not say where the log lives. Blocking decisions stay fail-open: a failed hook never blocks an operation. On non-Windows platforms, hook processes run in a separate process group, and on timeout the CLI first sends a signal so the script can clean up, then forcibly terminates it.
Steps to complete the task
Step 1, save the script. Create the directory with mkdir -p ~/.kimi-code/hooks, then save the official script from the example below as ~/.kimi-code/hooks/block-dangerous-bash.mjs. The page does not say whether the CLI creates the hooks directory for you, so mkdir -p is the safe choice. After saving, run node --check ~/.kimi-code/hooks/block-dangerous-bash.mjs; no output and exit code 0 means the syntax is fine.
Step 2, pipe-test the script before touching the config. Feed it JSON on stdin and check the exit code and stderr: input containing rm -rf should give exit code 2 and one line of reason, and input without it should print nothing and exit 0. Then feed it something that is not JSON; the exit code should be neither 0 nor 2, which the page says defaults to allow (fail-open). This step needs no sign-in and does not start Kimi Code.
Step 3, add the rule. Append the official [[hooks]] block to the config.toml the CLI actually reads: ~/.kimi-code/config.toml by default, or $KIMI_CODE_HOME/config.toml if KIMI_CODE_HOME is set. Editing the wrong file means the rule never takes effect. The official command below points at ~/.kimi-code/hooks/; where the script should live when KIMI_CODE_HOME is set, the official page does not say, so make sure command points at the script's real location. Then check four things: only the keys event, matcher, command and timeout appear; event is spelled PreToolUse as in the event reference; matcher is Bash, which matches the tool name; and the script path in command matches where you saved it in step 1. Then open a new session, as the official quick start also says after saving the config. The configuration page mentions that /reload reloads config.toml, but neither page says whether hook rules are refreshed by it, so this article does not rely on it.
If you add an extra field, the Hooks page says the config file fails to load. The configuration page adds that when the user config.toml cannot be read, parsed or validated, sessions continue with default or last-known-good validated values, and errors appear in config diagnostics. Neither page says whether a new rule takes effect in that situation, so the in-session trigger in step 4 is not optional.
Step 4, trigger it in a session. Start Kimi Code CLI in the project directory and explicitly ask it to delete the old-build subdirectory of the throwaway directory with rm -rf, using the real path printed by echo in step 1. Put the command into the prompt verbatim: if the model picks a different way to delete, such as rm -fr, the script still runs as long as the call goes through the Bash tool, but it does not return 2, so the test cannot show that the blocking rule works. What the official page states is this: a blocked tool does not execute, the reason (the text the script writes to stderr) is written back into the context, and the model "can" use it to choose a safer alternative. The page does not say that the model always does so, and does not say how the interface shows a block. This step was not tested. The pass criterion is that you can confirm this Bash call was blocked by this hook, for example by seeing the script's reason "Dangerous command detected, blocked" in the interface or in the model's reply. Seeing old-build still in place is not enough, because a declined permission approval also leaves the directory intact; if you cannot confirm it, record the test as inconclusive and go back to step 3. If the hook fails to block, the command may really delete the directory, which is why only a throwaway directory should be used. The configuration page says default_permission_mode defaults to manual, with manual, yolo and auto as options; this article did not check how they differ, so if a confirmation prompt appears when the hook has not blocked, decline it.
Step 5, run a control. Ask the agent to run a harmless command, such as listing the contents of the test directory. It should run as usual, which shows the rule is not blocking every command.
Step 6, note the boundary. Write down what the rm -fr input did in step 2: the script does plain substring matching, so another spelling gets through. For stricter blocking, the official page suggests whitelists or a dedicated shell parser, and high-risk operations still need permission approval and manual confirmation.
Running example
The running example is a throwaway directory created with mktemp -d (a path like /tmp/kimi-hook-demo.XXXXXX, different each time, so it cannot overwrite an existing directory) that holds an old-build/ directory with one file in it. The goal is for the hook to block the agent when it runs rm -rf on old-build. Prepare the directory first, then look at the official rule and script, and finally run the pipe checks.
mkdir -p ~/.kimi-code/hooks
DEMO=$(mktemp -d /tmp/kimi-hook-demo.XXXXXX)
mkdir "$DEMO/old-build"
echo stale > "$DEMO/old-build/stale.txt"
echo "$DEMO"config.toml the CLI reads (~/.kimi-code/config.toml by default)[[hooks]]
event = "PreToolUse"
matcher = "Bash"
command = "node ~/.kimi-code/hooks/block-dangerous-bash.mjs"
timeout = 5~/.kimi-code/hooks/block-dangerous-bash.mjs// block-dangerous-bash.mjs
// Read event data passed by the CLI from stdin
let input = '';
process.stdin.on('data', (chunk) => { input += chunk; });
process.stdin.on('end', () => {
const payload = JSON.parse(input); // Parse event data
const command = payload.tool_input?.command ?? '';
if (command.includes('rm -rf')) {
// Explain the blocking reason via stderr; exit code 2 means block
console.error('Dangerous command detected, blocked');
process.exit(2);
}
// Normal exit (exit code 0) means allow
});The Chinese version of the page has the same script; only the comments and the stderr text are in Chinese, and the logic is identical. This site ran inputs 1, 2, 3 and 4 against both versions and got the same exit codes.
Run the pipe test below with bash after step 1. The four inputs were built by this site from the base fields on the page and the tool_input.command path the script reads.
SCRIPT=~/.kimi-code/hooks/block-dangerous-bash.mjs
# 1. Contains rm -rf: expect the reason on stderr and exit code 2
printf '%s' '{"hook_event_name":"PreToolUse","cwd":"/tmp/demo","tool_input":{"command":"rm -rf ./dist"}}' | node "$SCRIPT"
echo "exit=$?"
# 2. Harmless command: expect no output and exit code 0
printf '%s' '{"hook_event_name":"PreToolUse","cwd":"/tmp/demo","tool_input":{"command":"ls -la"}}' | node "$SCRIPT"
echo "exit=$?"
# 3. Not JSON: JSON.parse throws, so the script exits with a code other than 0 or 2
printf '%s' 'not json' | node "$SCRIPT" 2>/dev/null
echo "exit=$?"
# 4. A spelling the substring check misses: expect exit code 0
printf '%s' '{"hook_event_name":"PreToolUse","cwd":"/tmp/demo","tool_input":{"command":"rm -fr ./dist"}}' | node "$SCRIPT"
echo "exit=$?"Dangerous command detected, blocked
exit=2
exit=0
exit=1
exit=0Reading the results one by one: input 1 prints the reason on stderr and exits with 2, which the CLI treats as a block. Input 2 prints nothing and exits 0, an allow. Input 3 makes JSON.parse throw, Node exits with code 1, and the stack trace is discarded by 2>/dev/null; 1 falls under "Other non-zero", which the CLI allows. Input 4 writes the same deletion as rm -fr, and the substring check misses it. These results prove only the script logic, and none of them went through Kimi Code CLI.
A prompt for the session can look like this, with the command given verbatim so the model does not pick another way to delete. Replace XXXXXX in the path with the directory printed by echo in step 1:
Please run this shell command exactly as written: rm -rf /tmp/kimi-hook-demo.XXXXXX/old-buildResult checks and troubleshooting
- Pipe test passes: with
rm -rfthe exit code is 2 and stderr has the reason, withls -lathe exit code is 0 and nothing is printed, and withnot jsonthe exit code is neither 0 nor 2. Once all three match, move on to the session test. - The block works in the session: first confirm that the target Bash call was blocked by this hook, for example by seeing the script's reason in the interface or in the model's reply, then check with
ls "$DEMO/old-build"thatstale.txtis still there. A surviving directory alone does not prove the hook worked, since a declined permission approval also keeps it; if you cannot confirm it, record the test as inconclusive. The page says only that the model "can use this to choose a safer alternative"; it does not promise that it will, or say what it would choose. - The command ran anyway: check that
eventisPreToolUse, thatmatcherisBash, that the path incommandis right and that you opened a new session, then go back to the pipe test and confirm the script itself returns 2. The page does not say how each of these mistakes shows up, so rule them out one by one. - A hook failure warning appears in the session: when a script cannot start, times out or exits with an error code, the CLI warns once and afterwards only logs. A warning means this hook run failed and did not block the call; whether a later permission check stops it, the official page does not say. Check the script path, whether
noderuns, and thetimeoutvalue, in that order. - A harmless command was blocked: the script does substring matching, so any command containing
rm -rfis blocked, includingecho "rm -rf is dangerous", which only prints those characters. This site checked it locally and that input gives exit code 2.
Boundaries and what the pages do not say
- Fail-open: script errors, timeouts, crashes and any exit code other than 0 and 2 all mean this hook does not block the call. The official page says plainly that hooks suit alerts and lightweight interception and should not be the sole security barrier; truly high-risk operations should rely on permission approval and manual confirmation. The full example on the configuration page includes a
[[permission.rules]]entry withdecision = "deny"andpattern = "Bash(rm -rf*)", the page says matching deny rules take precedence over ask rules and ask rules over allow rules, and the built-indangerous_command_guardis on by default. Those are separate mechanisms from hooks, and this article did not check how they treat spellings such asrm -fr. - Substring matching is easy to get around: this site checked locally that
rm -fr ./dist,rm -r -f ./distandrm -rf ./dist(two spaces) all give exit code 0, so this hook would not block them. Right after the example, the official page says it only demonstrates the blocking mechanism and is not a production-grade security parser, and that real scenarios are better served by whitelists or a dedicated shell parser that handles quoting, variable expansion and multi-command sequences. - Hook rules exist only in the user-level config and in local plugins. There is no project-level hook file, and the official page says content checked out on a remote target can never inject hook definitions into your session. The official page does not say anything further about local repositories. The page mentions that local plugins can carry hook rules too and does not go further, so this article does not cover them.
- What the pages do not say: the event-specific extra fields of the
PreToolUsepayload (the page lists only the base fields and does not list the event-specific ones in full); whether thematcherregular expression must match the whole string; which shell runscommand, and how~andnoderesolve on Windows; where hook logs are kept; whether thedenyJSON on stdout needs a particular exit code; how blocking results from several hooks are combined; how a block is displayed in the interface; and differences between versions. You need to see the actual behavior in your own environment.
Kimi Code CLI was not installed, signed into or run for this batch, and no account or paid interface was used. The facts here come from the official Kimi Code Hooks page (both the English and Chinese versions) and the configuration files page, fetched on 2026-11-24. The pipe checks ran the official script with Node v24.19.0 on a local machine and prove only the script logic. The in-session block is an expectation taken from the pages, and whether the model then switches to a safer approach is not stated by the official page; neither was verified.
Article sources
Original editorial content; official descriptions and checking suggestions are distinguished.