Hooks
Guides

Hooks

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:

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 = 10000

Every command key accepts either a string or an array, so independent scripts can share an event without a dispatcher:

toml
[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#

RuleDetail
ParsingThe 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 directoryThe session's working directory when known.
stdoutUsed by post_tool_feedback and by JSON gate output; ignored elsewhere.
stderrUsed by pre_tool exit 2 as the block reason; discarded otherwise.
FailureObservers log and continue; gates fail open.

Every hook receives:

VariableMeaning
RAYU_HOOK_EVENTturn_start, turn_end, session_start, session_end, pre_tool, post_tool, post_tool_feedback, pre_tool_transform
RAYU_HOOK_SESSION_IDSession the event belongs to
RAYU_HOOK_CWDSession working directory
RAYU_HOOK_PAYLOADThe whole event as JSON, capped at 16 KB
RAYU_HOOKS_DISABLEDAlways 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:

bash
#!/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.

VariableMeaning
RAYU_HOOK_STATUSok or error
RAYU_HOOK_DURATION_MSTurn duration
RAYU_HOOK_MODELModel used
RAYU_HOOK_LAST_ASSISTANT_TEXTFinal assistant text, first 4000 chars
RAYU_HOOK_PROMPT_TOKENSProvider-reported full prompt size
RAYU_HOOK_INPUT_TOKENS / RAYU_HOOK_OUTPUT_TOKENSRaw provider counts
RAYU_HOOK_CACHE_READ_TOKENS / RAYU_HOOK_CACHE_WRITE_TOKENSCache metrics, omitted when the provider does not report them
RAYU_HOOK_ERRORError 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.

bash
#!/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 0

session_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:

VariableMeaning
RAYU_HOOK_TOOL_NAMEResolved tool name
RAYU_HOOK_TOOL_CALL_IDProvider tool call id
RAYU_HOOK_TOOL_INPUTTool input JSON, capped at 16 KB
RAYU_HOOK_TOUCHED_PATHSNewline-separated absolute paths named by the input
RAYU_HOOK_STATUSok or error
RAYU_HOOK_DURATION_MSTool execution time
RAYU_HOOK_OUTPUT_BYTESOutput size on success
RAYU_HOOK_ERRORError 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.

bash
#!/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 0

pre_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 codeResult
0Allow the call
2Block. Trimmed stderr, capped at 2000 chars, becomes the tool error the model sees, so it can adapt
anything elseFail 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.

json
{
  "hookSpecificOutput": {
    "permissionDecision": "deny",
    "permissionDecisionReason": "rm -rf is not allowed",
    "updatedInput": { "command": "ls" },
    "additionalContext": "note shown to the model"
  },
  "systemMessage": "also shown to the model"
}
FieldEffect
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.
updatedInputReplaces the tool input. With several gates, later gates see the rewritten input; a block discards rewrites.
additionalContext, systemMessageAppended under a [pre_tool context] marker.

Example policy#

bash
#!/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 0

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

toml
[hooks]
pre_tool_transform = ["~/.rayu/plugins/rtk-transform"]
pre_tool_transform_timeout_ms = 500

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

VariableOverrides
RAYU_HOOK_TURN_STARTturn_start
RAYU_HOOK_TURN_ENDturn_end
RAYU_HOOK_SESSION_STARTsession_start
RAYU_HOOK_SESSION_ENDsession_end
RAYU_HOOK_PRE_TOOLpre_tool
RAYU_HOOK_POST_TOOLpost_tool
RAYU_HOOK_POST_TOOL_FEEDBACKpost_tool_feedback
RAYU_HOOK_PRE_TOOL_TRANSFORMpre_tool_transform
RAYU_HOOK_PRE_TOOL_TIMEOUT_MSpre_tool_timeout_ms
RAYU_HOOK_POST_TOOL_FEEDBACK_TIMEOUT_MSpost_tool_feedback_timeout_ms
RAYU_HOOK_PRE_TOOL_TRANSFORM_TIMEOUT_MSpre_tool_transform_timeout_ms

Command overrides accept a TOML array string:

bash
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_PAYLOAD gives 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 →