Defines when a hook callback should be triggered. Hooks can be filtered by event type and optionally by tool name pattern.
Security Note: Hook matcher configuration is read-only from the public API after construction so callbacks and matching rules cannot be swapped out accidentally at runtime.
Active bindings
eventThe hook event type (see HookEvent). Read-only after construction.
patternOptional regex pattern for tool name filtering. Read-only after construction.
callbackThe function to call when the hook fires. Read-only after construction.
timeoutMaximum execution time for the callback in seconds. Zero runs in the caller's process; a positive value uses a clean subprocess. Read-only after construction.
Methods
HookMatcher$new()
Create a new HookMatcher.
Usage
HookMatcher$new(event, callback, pattern = NULL, timeout = 0)Arguments
eventThe event type (must be one of HookEvent)
callbackFunction to call. Signature depends on event type:
PreToolUse:
function(tool_name, tool_input, context)PostToolUse:
function(tool_name, tool_result, tool_error, context)PostToolUseFailure:
function(tool_name, tool_result, tool_error, context)Stop:
function(reason, context)SubagentStart:
function(agent_name, task, context)SubagentStop:
function(agent_name, task, result, context)UserPromptSubmit:
function(prompt, context)Notification:
function(message, context)PermissionRequest:
function(tool_name, tool_input, permission_result, context)ConfigChange:
function(key, old_value, new_value, context)PreCompact:
function(turns_to_compact, turns_to_keep, context)SessionStart:
function(context)SessionEnd:
function(reason, context)
patternOptional regex pattern to filter by tool name. Only applies to PreToolUse and PostToolUse events.
timeoutMaximum callback execution time in seconds. The default,
0, runs the callback in the caller's process. Positive values run the callback in a cleancallr::r()subprocess, where caller-process state and side effects are not available.
Examples
# Block dangerous bash commands
HookMatcher$new(
event = "PreToolUse",
pattern = "^(run_bash|bash)$",
callback = function(tool_name, tool_input, context) {
if (grepl("rm -rf", tool_input$command)) {
HookResultPreToolUse(permission = "deny", reason = "Dangerous!")
} else {
HookResultPreToolUse(permission = "allow")
}
}
)Examples
## ------------------------------------------------
## Method `HookMatcher$new()`
## ------------------------------------------------
if (FALSE) { # \dontrun{
# Block dangerous bash commands
HookMatcher$new(
event = "PreToolUse",
pattern = "^(run_bash|bash)$",
callback = function(tool_name, tool_input, context) {
if (grepl("rm -rf", tool_input$command)) {
HookResultPreToolUse(permission = "deny", reason = "Dangerous!")
} else {
HookResultPreToolUse(permission = "allow")
}
}
)
} # }