Skip to main content

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; $ARGUMENTS expands 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 (quick or thorough depth).
  • 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.md frontmatter 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 (also Stop), BeforeToolUse / PreToolUse, AfterToolUse / PostToolUse, PostToolUseFailure. Any other name is skipped with a warning in the log, and so is a hooks block or an event value that is not shaped like the example above (event name, then a list of entries).
  • script becomes a command hook; url becomes an HTTP hook. secret enables HMAC signing; fire_and_forget makes the call non-blocking.
  • auth and secret take a literal, or an environment variable written ${NAME} (auth becomes the Authorization header). 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 variable MYRM_HOOK_… to expose it to hooks.
  • tools filters 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 is bash_code_execute_tool). A malformed tools value skips that hook instead of widening it to every tool.
  • failure_mode: fail_closed blocks the action when the hook fails or is refused (default fail_open: skip and log). timeout is 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

  • $ARGUMENTS is data, not code. It expands to the event payload as one JSON string, delivered through the HOOK_PAYLOAD environment 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_EVENT carries the event name.
  • The complete payload is also on standard input (cat | jq .tool_name). HOOK_PAYLOAD is 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": true is 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_keys or 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, crontab edits).
  • 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 … and node -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_use hook runs. When that hook rewrites them (for example, appending --dry-run to 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 fires subagent_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_start carries task_id, agent_type, task_description and trace_id.
  • subagent_stop carries task_id, agent_type, success, status (for example completed, failed, cancelled, pending_approval), duration_seconds, trace_id, and either result or error.
  • Use trace_id to 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_stop with status cancelled; treat the last one for a task_id as final.
  • A subagent stopped by the hard timeout (three times its configured timeout_seconds) is reported as timed_out to the parent, but its subagent_stop hook reports cancelled.

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.