29. Hooks#
Hooks run your own commands at fixed points in a session: when a turn starts, when a tool is about to run, after an edit, when a session closes. Use them for rules the model should not have to remember and that must be enforced the same way every time.
You never invoke a hook. Rayu does, and the exit code decides what happens next.
Where they live#
Hooks are a [hooks] table in ~/.rayu/config.toml:
[hooks]
turn_start = "~/bin/rayu-turn-busy" # observer
turn_end = "~/bin/rayu-turn-notify" # observer
session_start = "" # observer
session_end = "" # observer
pre_tool = "~/bin/rayu-tool-policy" # gate
post_tool = "" # observer
post_tool_feedback = "~/bin/rayu-vale" # feeds output back to the model
pre_tool_timeout_ms = 5000
post_tool_feedback_timeout_ms = 10000Every command key accepts either a string or an array, so independent scripts can share an event without a dispatcher:
[hooks]
turn_end = ["~/bin/rayu-turn-notify", "~/bin/rayu-event-log"]
pre_tool = ["~/bin/rayu-tool-policy", "~/bin/rayu-audit-policy"]Empty or whitespace-only commands are skipped. Observers are spawned in declaration order but run independently. Gates, transformers and feedback hooks run sequentially in declaration order; the first blocking gate result wins.
There is no per-hook approval dialog, so a hook is a trust boundary: only add one whose script you have read.
The hook contract#
| Rule | Detail |
|---|---|
| Parsing | The command line is split shell-style (quotes and backslashes work) but executed directly, not through a shell. |
~ | A leading ~/ in the program path is expanded. |
| Working directory | The session's working directory when known. |
| stdout | Used by post_tool_feedback and by JSON gate output; ignored elsewhere. |
| stderr | Used by pre_tool exit 2 as the block reason; discarded otherwise. |
| Failure | Observers log and continue; gates fail open. |
Every hook receives:
| Variable | Meaning |
|---|---|
RAYU_HOOK_EVENT | turn_start, turn_end, session_start, session_end, pre_tool, post_tool, post_tool_feedback, pre_tool_transform |
RAYU_HOOK_SESSION_ID | Session the event belongs to |
RAYU_HOOK_CWD | Session working directory |
RAYU_HOOK_PAYLOAD | The whole event as JSON, capped at 16 KB |
RAYU_HOOKS_DISABLED | Always 1; suppresses hooks in nested rayu calls (recursion guard) |
The recursion guard means a hook can safely call rayu without re-triggering
itself.
Events#
turn_start#
Fires after your message is added and before the model generates, on the
interactive streaming loop and the one-shot run path. Extra fields:
RAYU_HOOK_MODEL and RAYU_HOOK_SOURCE (chat or run).
Use it to set a status flag, start a timer, or light up a terminal badge:
#!/usr/bin/env bash
# ~/bin/rayu-turn-busy
tmux set -g status-right "rayu ⏳ ${RAYU_HOOK_SESSION_ID:0:8}"turn_end#
Fires when a turn completes: TUI, desktop, swarm workers, headless sessions, and
one-shot rayu run.
| Variable | Meaning |
|---|---|
RAYU_HOOK_STATUS | ok or error |
RAYU_HOOK_DURATION_MS | Turn duration |
RAYU_HOOK_MODEL | Model used |
RAYU_HOOK_LAST_ASSISTANT_TEXT | Final assistant text, first 4000 chars |
RAYU_HOOK_PROMPT_TOKENS | Provider-reported full prompt size |
RAYU_HOOK_INPUT_TOKENS / RAYU_HOOK_OUTPUT_TOKENS | Raw provider counts |
RAYU_HOOK_CACHE_READ_TOKENS / RAYU_HOOK_CACHE_WRITE_TOKENS | Cache metrics, omitted when the provider does not report them |
RAYU_HOOK_ERROR | Error message on failure |
Token fields are summed from the turn's assistant messages and are not normalized across providers: cached input may be inside the OpenAI input count and reported separately by Anthropic.
#!/usr/bin/env bash
# ~/bin/rayu-turn-notify
if [ "$RAYU_HOOK_STATUS" = ok ]; then icon=✅; else icon=❌; fi
tmux display-message "rayu $icon ${RAYU_HOOK_SESSION_ID:0:12}" 2>/dev/null
notify-send "rayu turn $RAYU_HOOK_STATUS" \
"${RAYU_HOOK_LAST_ASSISTANT_TEXT:0:120}" 2>/dev/null
exit 0session_start / session_end#
session_start fires when a session becomes active, with RAYU_HOOK_SOURCE set
to create (new), attach (existing session object attached) or resume
(restored by id). session_end fires on normal close with
RAYU_HOOK_SOURCE=close.
post_tool#
Fires after every tool call. Extra fields:
| Variable | Meaning |
|---|---|
RAYU_HOOK_TOOL_NAME | Resolved tool name |
RAYU_HOOK_TOOL_CALL_ID | Provider tool call id |
RAYU_HOOK_TOOL_INPUT | Tool input JSON, capped at 16 KB |
RAYU_HOOK_TOUCHED_PATHS | Newline-separated absolute paths named by the input |
RAYU_HOOK_STATUS | ok or error |
RAYU_HOOK_DURATION_MS | Tool execution time |
RAYU_HOOK_OUTPUT_BYTES | Output size on success |
RAYU_HOOK_ERROR | Error message on failure |
RAYU_HOOK_TOUCHED_PATHS is derived from the input (file_path, path,
paths, apply_patch headers), so it lists what a tool was asked to touch.
It does not see files a bash command happened to modify.
post_tool_feedback — send linter output back to the model#
Runs synchronously after every successful tool call and appends its stdout to the tool result the model sees.
- Trimmed stdout is appended under a
[post_tool_feedback]marker, capped at 8 KB per hook. Empty stdout adds nothing. - The exit code is ignored, because linters exit non-zero when they find something. stderr is discarded.
- Timeouts (
post_tool_feedback_timeout_ms, default 10s) and spawn failures add nothing and are logged. - Several hooks run in order and their output is concatenated.
Keep it fast and filter first: it runs on every tool call, including reads.
#!/usr/bin/env bash
# ~/bin/rayu-vale: lint prose the agent just wrote
case "$RAYU_HOOK_TOOL_NAME" in
write|edit|multiedit|apply_patch) ;;
*) exit 0 ;;
esac
while IFS= read -r path; do
case "$path" in
*.md|*.mdx|*.txt|*.rst) [ -f "$path" ] && vale --output=line "$path" ;;
esac
done <<<"$RAYU_HOOK_TOUCHED_PATHS"
exit 0pre_tool — gate every tool call#
Runs synchronously before every tool call. The full tool input JSON arrives on
stdin, and RAYU_HOOK_TOOL_NAME is in the environment.
| Exit code | Result |
|---|---|
0 | Allow the call |
2 | Block. Trimmed stderr, capped at 2000 chars, becomes the tool error the model sees, so it can adapt |
| anything else | Fail open with a logged warning |
Timeouts (pre_tool_timeout_ms, default 5000), a missing binary and spawn errors
also fail open. That is deliberate: a broken policy script should degrade to "no
policy" rather than brick every session. If you need fail-closed behaviour, the
hook is your trust boundary, so make the script itself robust.
JSON output on stdout#
On exit 0 a gate may print one JSON object. Non-JSON stdout is ignored, so plain exit-code scripts keep working.
{
"hookSpecificOutput": {
"permissionDecision": "deny",
"permissionDecisionReason": "rm -rf is not allowed",
"updatedInput": { "command": "ls" },
"additionalContext": "note shown to the model"
},
"systemMessage": "also shown to the model"
}| Field | Effect |
|---|---|
permissionDecision: "deny" | Blocks the call with the given reason. The legacy top-level "decision": "block" plus reason also works. |
permissionDecision: "ask" | Also blocks, with a "requires user approval" reason. Rayu has no interactive approval prompt for hooks. |
updatedInput | Replaces the tool input. With several gates, later gates see the rewritten input; a block discards rewrites. |
additionalContext, systemMessage | Appended under a [pre_tool context] marker. |
Example policy#
#!/usr/bin/env bash
# ~/bin/rayu-tool-policy
# stdin: tool input JSON. Env: RAYU_HOOK_TOOL_NAME, RAYU_HOOK_SESSION_ID, ...
input=$(cat)
case "$RAYU_HOOK_TOOL_NAME" in
bash)
if grep -qE 'rm -rf /([^a-zA-Z]|$)|mkfs|dd if=' <<<"$input"; then
echo "blocked: destructive shell command" >&2
exit 2
fi
;;
write|edit)
if grep -q '"file_path":"/etc/' <<<"$input"; then
echo "blocked: writes to /etc are not allowed" >&2
exit 2
fi
;;
esac
exit 0Remember that Rayu already has a built-in destructive-command gate; a pre_tool
hook is for policy specific to you or your repository. See
Permissions & safety.
pre_tool_transform — rewrite tool input#
Transformers replace a tool's JSON input before it is validated and executed. Each
receives the current complete input on stdin plus RAYU_HOOK_TOOL_NAME,
RAYU_HOOK_SESSION_ID and RAYU_HOOK_CWD, and may print a replacement JSON
object.
[hooks]
pre_tool_transform = ["~/.rayu/plugins/rtk-transform"]
pre_tool_transform_timeout_ms = 500Empty stdout, invalid JSON, a non-zero exit, a spawn error or a timeout leaves the
input unchanged. Transformers compose in configuration order and run before
pre_tool, so policies evaluate the final input. Keep them small and
tool-specific: a transformer that rewrites everything is a bug waiting to happen.
Environment overrides#
Every command has an env override, and the override wins over the config file. An empty value disables a configured hook, which is how you turn one off for a single run.
| Variable | Overrides |
|---|---|
RAYU_HOOK_TURN_START | turn_start |
RAYU_HOOK_TURN_END | turn_end |
RAYU_HOOK_SESSION_START | session_start |
RAYU_HOOK_SESSION_END | session_end |
RAYU_HOOK_PRE_TOOL | pre_tool |
RAYU_HOOK_POST_TOOL | post_tool |
RAYU_HOOK_POST_TOOL_FEEDBACK | post_tool_feedback |
RAYU_HOOK_PRE_TOOL_TRANSFORM | pre_tool_transform |
RAYU_HOOK_PRE_TOOL_TIMEOUT_MS | pre_tool_timeout_ms |
RAYU_HOOK_POST_TOOL_FEEDBACK_TIMEOUT_MS | post_tool_feedback_timeout_ms |
RAYU_HOOK_PRE_TOOL_TRANSFORM_TIMEOUT_MS | pre_tool_transform_timeout_ms |
Command overrides accept a TOML array string:
RAYU_HOOK_TURN_END='["notify-one", "notify-two"]' rayu run "run the tests"Debugging hooks#
- Run the script by hand with the same env and stdin.
RAYU_HOOK_PAYLOADgives you the whole event to replay. - Hooks are re-read on config reload, so you can add or change one without restarting the session.
- Unconfigured hooks cost almost nothing: the hot paths check whether a hook exists before building any payload.
- A gate that never blocks is usually failing open. Check for a missing shebang, a non-executable file, or a timeout on a slow first run.
Next#
Next: Headless & CI →