Defines when a hook callback should be triggered. Hooks can be filtered by event type and optionally by tool name pattern.
Public fields
eventThe hook event type (see HookEvent)
patternOptional regex pattern for tool name filtering
callbackThe function to call when the hook fires
timeoutMaximum execution time for the callback in seconds
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)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")
}
}
)
} # }