Documentation
¶
Overview ¶
Package hooks implements the hook engine: shell hooks on 13 lifecycle events with Claude Code-compatible stdin/stdout JSON payloads, exit-code semantics, parallel execution with per-hook timeouts, and config-order aggregation.
Hook commands are trusted user configuration: they run through the platform shell without a sandbox. The security boundary is elsewhere and stays unconditional — a hook allow can never bypass the permission deny-list or transcript redaction, and a hook approval is per-call only.
Index ¶
- Constants
- Variables
- func EnvAdditions(in Input) []string
- func ParseToolInput(raw []byte) json.RawMessage
- func ShellExecutor(ctx context.Context, command, cwd string, stdin []byte, env []string) ([]byte, []byte, int, error)
- type Aggregated
- type Config
- type Decision
- type Event
- type Executor
- type Hook
- type HookResult
- type Input
- type Runner
Constants ¶
const ( // DefaultTimeout bounds one hook command when its config timeout is unset. DefaultTimeout = 30 * time.Second // AbandonGrace is how long the runner waits past a hook's deadline for the // executor to yield before abandoning the goroutine (no opinion either way). AbandonGrace = time.Second // HaltExitCode is the exit code meaning "deny AND halt the turn". It sits // outside the generic-error (1–30), sysexits (64–78) and signal (128+) // ranges so it cannot be produced by accident. HaltExitCode = 49 // SessionEndBudget bounds the whole SessionEnd firing at process exit. SessionEndBudget = 2 * time.Second // DefaultTimeoutSeconds is DefaultTimeout expressed for config files. DefaultTimeoutSeconds = 30 )
Engine constants.
Variables ¶
var AllEvents = []Event{ PreToolUse, PostToolUse, PostToolUseFailure, PermissionRequest, PermissionResult, SessionStart, SessionEnd, TurnStart, TurnEnd, StopFailure, Interrupt, PreCompact, PostCompact, }
AllEvents lists every event in definition order. Exactly one of TurnEnd, StopFailure and Interrupt fires per finished model turn.
Functions ¶
func EnvAdditions ¶
EnvAdditions returns the GOCODE_* environment variables for one firing including CLAUDE_PROJECT_DIR compatibility. Tool-specific variables are only present on tool events whose input carries the matching string field.
func ParseToolInput ¶
func ParseToolInput(raw []byte) json.RawMessage
ParseToolInput converts raw tool-call arguments into the parsed object the payload carries. Anything that is not a JSON object (invalid JSON, arrays, scalars, null) becomes {} — a hook always receives an object it can index.
func ShellExecutor ¶
func ShellExecutor(ctx context.Context, command, cwd string, stdin []byte, env []string) ([]byte, []byte, int, error)
ShellExecutor is the real executor. The command runs through the platform shell — "bash -c" on unix, "cmd /C" on windows — in the payload's cwd, with the payload JSON on stdin and the scrubbed environment plus GOCODE_* additions. Hook commands are trusted user configuration: no sandbox is applied, but credential-shaped environment variables are still scrubbed so a hook child never inherits provider API keys by default.
Types ¶
type Aggregated ¶
type Aggregated struct {
// Decision follows deny > allow > none.
Decision Decision
// Halt is the sticky OR of every hook's halt.
Halt bool
// Reason joins deny reasons (and halting non-deny reasons) with newlines,
// in config order.
Reason string
// StopReason is the last non-empty continue:false stopReason.
StopReason string
// Context joins every hook's context with newlines; the caller appends it
// to the tool result the model sees.
Context string
// UpdatedInput is the original input shallow-merged with every valid
// patch in config order; nil when no patch applied.
UpdatedInput json.RawMessage
// UpdatedOutput is the last hook's whole replacement; nil when unset.
UpdatedOutput *string
// Results carries every hook outcome in config order.
Results []HookResult
// Diagnostics collects abnormal outcomes; the caller decides how to log
// them (the engine has no logger dependency).
Diagnostics []string
}
Aggregated is the combined outcome of one event firing.
func Aggregate ¶
func Aggregate(results []HookResult, originalInput json.RawMessage) Aggregated
Aggregate combines hook results in config order: - decision: deny > allow > none (strongest wins) - halt: sticky OR - reason: newline-joined deny reasons; a halting non-deny hook contributes - context: newline-joined, appended to the tool result by the caller - updated_input: shallow merge of top-level keys onto the original input, applied in order; a patch that is not a JSON object is rejected with a diagnostic - updated_output: whole replacement, last hook to set it wins
type Config ¶
Config maps each event to its hooks in configuration order. Aggregation always follows this order, never completion order.
func NormalizeConfig ¶
NormalizeConfig validates and canonicalizes a raw hook configuration: event names are normalized (case-insensitive, underscores stripped), unknown events and empty commands are rejected, matchers must compile, negative timeouts are rejected, unset timeouts default to 30s, and hooks are deduplicated by command within each event (first occurrence wins). It is idempotent, so config load and runner construction can both call it.
type Decision ¶
type Decision int
Decision is a hook's opinion about the call or lifecycle step.
const ( // DecisionNone means the hook expressed no opinion (success without a // decision, timeout, cancellation, or a non-blocking error exit). DecisionNone Decision = iota // DecisionAllow approves the call. On PreToolUse it short-circuits the // permission prompt for THAT call only; it never bypasses the deny-list. DecisionAllow // DecisionDeny blocks the call (or compaction, on PreCompact). DecisionDeny )
type Event ¶
type Event string
Event is one of the 13 hook lifecycle events.
const ( // PreToolUse runs before a tool call; it may allow, deny, halt, rewrite // the input or add context. PreToolUse Event = "PreToolUse" // PostToolUse runs after a successful tool call; it may rewrite the // output, add context or halt. PostToolUse Event = "PostToolUse" // PostToolUseFailure runs after a failed tool call (Go error or an error // result); it may add context or halt. PostToolUseFailure Event = "PostToolUseFailure" // PermissionRequest is informational: a permission prompt was shown. PermissionRequest Event = "PermissionRequest" // PermissionResult is informational: a prompt resolved (carries decision). PermissionResult Event = "PermissionResult" // SessionStart fires when a session is created or resumed (source field). SessionStart Event = "SessionStart" // SessionEnd fires at process exit (reason field, 2s budget). SessionEnd Event = "SessionEnd" // TurnStart fires before the provider stream of a model turn. TurnStart Event = "TurnStart" // TurnEnd fires when a turn finishes successfully (last_assistant_message). TurnEnd Event = "TurnEnd" // StopFailure fires when a turn ended with a provider error. StopFailure Event = "StopFailure" // Interrupt fires when a turn was cancelled. Interrupt Event = "Interrupt" // PreCompact fires before a compaction summary request; deny BLOCKS // compaction. PreCompact Event = "PreCompact" // PostCompact fires after a compaction summary was persisted. PostCompact Event = "PostCompact" )
func NormalizeEvent ¶
NormalizeEvent resolves an event name case-insensitively with underscores removed, so "pre_tool_use" and "PRETOOLUSE" both resolve to PreToolUse Unknown names report false.
func (Event) IsToolEvent ¶
IsToolEvent reports whether the event carries a tool call (matcher applies).
type Executor ¶
type Executor func(ctx context.Context, command, cwd string, stdin []byte, env []string) (stdout, stderr []byte, exitCode int, err error)
Executor runs one hook command and reports its raw outcome. It is the injection seam: contract tests supply a fake, production uses ShellExecutor. A nil exitCode with non-nil err means the process never started (or was killed by its context); the runner classifies context errors itself.
type Hook ¶
type Hook struct {
Name string `toml:"name" json:"name,omitempty"`
Matcher string `toml:"matcher" json:"matcher,omitempty"`
Command string `toml:"command" json:"command"`
Timeout int `toml:"timeout" json:"timeout,omitempty"`
}
Hook is one configured hook command. Timeout is in seconds; zero selects DefaultTimeout. Matcher is a regex tested against the tool name on tool events (empty matches all) and is ignored on lifecycle events.
type HookResult ¶
type HookResult struct {
Name string
Event Event
Matcher string
Command string
Decision Decision
Halt bool
Reason string
// StopReason carries the folded continue:false stopReason, if any.
StopReason string
Context string
// UpdatedInput is the raw patch object; aggregation shallow-merges it.
UpdatedInput json.RawMessage
// UpdatedOutput is a whole replacement of the tool output; nil = unset.
UpdatedOutput *string
// Diagnostic is non-empty when the hook produced no opinion for an
// abnormal reason (timeout, abandon, cancel, start failure, error exit).
Diagnostic string
}
HookResult is one hook's classified outcome, in configuration order.
type Input ¶
type Input struct {
Event Event `json:"event"`
HookEventName string `json:"hook_event_name"`
SessionID string `json:"session_id,omitempty"`
CWD string `json:"cwd,omitempty"`
ToolName string `json:"tool_name,omitempty"`
ToolInput json.RawMessage `json:"tool_input,omitempty"`
ToolUseID string `json:"tool_use_id,omitempty"`
ToolResponse string `json:"tool_response,omitempty"`
Error string `json:"error,omitempty"`
LastAssistantMessage string `json:"last_assistant_message,omitempty"`
Decision string `json:"decision,omitempty"`
Source string `json:"source,omitempty"`
Reason string `json:"reason,omitempty"`
Trigger string `json:"trigger,omitempty"`
}
Input is the stdin JSON payload. Field names follow Claude Code where an equivalent exists; event is kept alongside hook_event_name. Only set fields appear on the wire. ToolInput is emitted as a PARSED object, never a string; invalid JSON becomes {}.
type Runner ¶
type Runner struct {
// EnvScrub lists extra credential variable names/patterns to drop from
// hook child environments, on top of the built-in scrub.
EnvScrub []string
// DefaultTimeoutOverride and AbandonGraceOverride let tests shrink the
// budgets; zero selects the defaults (30s / 1s).
DefaultTimeoutOverride time.Duration
AbandonGraceOverride time.Duration
// contains filtered or unexported fields
}
Runner executes the configured hooks for an event. The zero value is not usable; construct with NewRunner. A nil *Runner is safe and inert, so callers without hooks pay nothing.
func NewRunner ¶
NewRunner normalizes the configuration and builds a runner. A nil executor selects ShellExecutor. Normalization is idempotent, so an already-validated config passes through unchanged.
func (*Runner) Has ¶
Has reports whether any hook is configured for the event. Nil-safe: a nil runner has no hooks, which keeps the no-hooks path allocation-free.
func (*Runner) Run ¶
Run fires every matching hook for the event IN PARALLEL and aggregates the results in config order. Each hook gets its own timeout (default 30s); past the deadline the runner waits at most the abandon grace (1s) for the executor to yield, then counts the hook as no opinion. Parent cancellation also yields no opinion. Diagnostics ride the returned Aggregated — the engine has no logger dependency.