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. Read-only after construction.
Methods
Method new()
Create a new HookMatcher.
Usage
HookMatcher$new(event, callback, pattern = NULL, timeout = 30)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)Stop:
function(reason, context)SubagentStop:
function(agent_name, task, result, context)UserPromptSubmit:
function(prompt, context)Notification:
function(message, 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
Examples
\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")
}
}
)
}
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")
}
}
)
} # }