Function Hooks
Function hooks let you inject custom logic at the key moments of your agent’s lifecycle—before and after tool calls, at session start/end, around subagent scheduling—without modifying any product source code. Audit every tool call, intercept dangerous operations, rewrite arguments, or notify your ops channel: your logic, your rules.What you get
- Four hook types — pick the right tool for each job:
- Python callable: an async function registered in-process. Zero subprocess, zero network round-trip.
- Shell command: one shell command;
$ARGUMENTSexpands to the event payload as JSON and always arrives as data, never as shell code. - HTTP webhook: POST to any URL with SSRF protection (private-IP interception), optional HMAC-SHA256 signing (
X-Webhook-Signature, the GitHub/Stripe convention), and optional fire-and-forget mode for notification events. - LLM-as-hook: describe the condition in plain language; a model decides whether it passes (
quickorthoroughdepth).
- 12 built-in lifecycle events with live fire points + custom event keys —
pre_tool_use,post_tool_use,post_tool_use_failure/_cancelled,session_start,session_end, subagent start/stop/cancel,user_turn,approval_correction. Any custom event key works too. - Declarative, zero-code mounting — declare hooks in a
SKILL.mdfrontmatter block. They go live when you invoke the skill yourself (pick it from the slash palette, or start the message with[use skill-name]) and only for that run. A skill the model loads on its own never registers hooks: third-party hooks always need your explicit consent. - Bloat-proof output — hook output above the token limit spills to disk automatically; only a preview enters the context.
- Run isolation — hook registries are scoped to the session’s async context (ContextVar), and a skill’s hooks are released the moment its run ends: parallel sessions, consecutive runs and other skills never inherit each other’s hooks.
- Failure isolation — one hook crashing or timing out never breaks other hooks or the main flow; opt into fail-closed per hook if you need it.
Declare a hook in SKILL.md
- Recognized event names:
SessionStart,SessionEnd(alsoStop),BeforeToolUse/PreToolUse,AfterToolUse/PostToolUse,PostToolUseFailure. Any other name is skipped with a warning in the log, and so is ahooksblock or an event value that is not shaped like the example above (event name, then a list of entries). scriptbecomes a command hook;urlbecomes an HTTP hook.secretenables HMAC signing;fire_and_forgetmakes the call non-blocking.authandsecrettake a literal, or an environment variable written${NAME}(authbecomes theAuthorizationheader). A skill is third-party text, so a variable whose name looks like a credential (OPENAI_API_KEY,DB_PASSWORD) is refused and the entry is skipped with a warning; name the variableMYRM_HOOK_…to expose it to hooks.toolsfilters which tools the hook sees: one pattern or a list (bash_*,[bash_*, write_file_tool]), matched with fnmatch against the runtime tool name (the bash tool isbash_code_execute_tool). A malformedtoolsvalue skips that hook instead of widening it to every tool.failure_mode: fail_closedblocks the action when the hook fails or is refused (defaultfail_open: skip and log).timeoutis in seconds (default 10, range 1–600). An invalid entry is skipped with a warning and never discards the other hooks of the skill.
Writing command hooks
$ARGUMENTSis data, not code. It expands to the event payload as one JSON string, delivered through theHOOK_PAYLOADenvironment variable, so a hostile tool argument or session id can never be parsed as shell code. Use it bare (printf "%s" $ARGUMENTS) or inside double quotes; inside single quotes it stays literal.HOOK_EVENTcarries the event name.- The complete payload is also on standard input (
cat | jq .tool_name).HOOK_PAYLOADis clipped once it would exceed 96 KiB, because a single environment string cannot be larger on Linux: long string values are shortened and"payload_truncated": trueis added. A hook that must inspect everything (a secret scanner over a large file write) reads stdin. - Commands are vetted as you wrote them, never as the payload they will receive, so a hook gets the same verdict on every event. Ordinary shell syntax (pipes, redirects,
;,$(…),${…}) is fine. - Refused for every hook: destructive or privilege-escalating commands (
sudo,rm -rf /,history -c, writes to~/.ssh/authorized_keysor shell startup files) and obfuscated commands. Also refused for hooks from skills, plugins and user config: commands that need a human decision (eval,curl … | sh,crontabedits). - A refused hook counts as a failed hook — skipped and logged by default, or blocking the action when the hook sets
failure_mode: fail_closed. - No inline interpreter code —
python3 -c …andnode -e …are refused. Put the logic in a script file and call it.
Safety model
- Command hooks run behind the same safety gate as agent shell commands — hook-declared shell commands are analyzed by the same static command analyzer (destructive-command detection, BLOCK/ESCALATE threat levels) used for the agent’s own bash usage; third-party-sourced hooks (skills/plugins/user config) get the stricter path, and standalone mode fails closed for them.
- Rewritten arguments are not approved again — the approval decision covers the arguments the model proposed (or the ones you edited in the approval card) and is made before the
pre_tool_usehook runs. When that hook rewrites them (for example, appending--dry-runto a command), the new arguments still pass through the pre-call guards that read them (loop detection, turn budget, PII parameter check) but do not go through approval again. Register argument-rewriting hooks only from sources you trust; a skill’s hooks go live only when you invoke the skill yourself.
Event reference at a glance
Subagent start and stop
Every subagent run firessubagent_start and ends with a subagent_stop — including runs that fail, run out of budget, hit a model error, or are cancelled — so a start/stop pair is enough to build a per-run record.
subagent_startcarriestask_id,agent_type,task_descriptionandtrace_id.subagent_stopcarriestask_id,agent_type,success,status(for examplecompleted,failed,cancelled,pending_approval),duration_seconds,trace_id, and eitherresultorerror.- Use
trace_idto join a subagent’s records with the rest of the task. - If a cancellation lands while the stop hooks are still running, you may receive a second
subagent_stopwithstatuscancelled; treat the last one for atask_idas final. - A subagent stopped by the hard timeout (three times its configured
timeout_seconds) is reported astimed_outto the parent, but itssubagent_stophook reportscancelled.
Where to go next
- For the overall security model (sandboxing, permission engine, approval flow), see Security Architecture.
- To package and reuse capabilities as portable units, see Agent Plugins.