Documentation
¶
Overview ¶
Package hooks implements golder's user-extensible lifecycle hook system: a config-driven way to run shell commands at agent lifecycle points (tool calls, prompt submission, session start/end, etc.) without writing Go or compiling a plugin. It depends only on the standard library plus internal/agentcore (the event types it reports), so it can be composed into the runtime/cli layers without creating an import cycle.
This file defines the configuration types and their validation. A hook is a single shell command; a matcher binds a group of hooks to an event (and, for tool events, a tool-name pattern); a HookSet maps each event type to its matchers. The types carry JSON tags so they can live directly in the layered config.json.
This file implements the Dispatcher: for one event it matches the configured hooks, runs them in order via the Runner, and merges their outputs into a single HookDecision. It owns the fail-open policy (a hook that fails to run is warned about and skipped, never blocking the agent) and the PreToolUse short-circuit (the first block stops further hooks so a blocked call is not also rewritten).
This file implements hook matching: given an event type and (for tool events) a tool name, MatchHooks returns the flat, ordered list of hooks that should run. Matcher semantics follow Claude Code to keep the learning curve low: empty or "*" matches all, an exact tool name matches only that tool, a "|"-separated list matches any listed tool, and anything else is compiled as a Go regexp against the tool name.
This file bridges the agent's event stream to observer-only hooks (US-011/012/ 013, FR-1). Where PreToolUse/UserPromptSubmit/Stop are decision hooks wired at dedicated seams, SessionEnd/PreCompact/Notification only observe: the agent emits lifecycle events, HookNotifier maps each to a HookInput and fires the matching hooks via the Dispatcher, discarding the decision (an observer hook cannot block).
It mirrors plugin.EventNotifier: created once per run, its Handle method is wired as an event-stream OnEvent callback and coexists with the plugin notifier (RunConfig.OnEvent already chains multiple observers). A nil *Dispatcher makes NewHookNotifier return nil, and every method is a no-op on a nil receiver, so callers can wire it unconditionally.
Session id and project dir are fixed for a run, so they are captured at construction rather than read from each event (AgentEndEvent/CompactionEvent do not carry them).
This file defines the process contract between golder and a user hook command: what golder writes to the hook's stdin (HookInput), what golder reads back from its stdout (HookOutput), and the internal merged decision the dispatcher produces (HookDecision). It also defines the exit-code semantics parsing.
The wire contract follows Claude Code: exit 0 = allow, exit 2 = block (with stderr as the reason), any other non-zero = execution failure. On exit 0 a well-formed JSON stdout is parsed as HookOutput; a non-JSON stdout is a no-op.
This file implements Runner.Run: executing a single hook command via the system shell with the event payload on stdin, a per-hook timeout, bounded output capture, and exit-code classification. It is the one place that forks a process, so all isolation guarantees (timeout kill, output cap, error containment) live here.
Index ¶
Constants ¶
const CommandType = "command"
CommandType is the only hook type supported in v1: a shell command. Other types (embedded script engines, WASM) are explicitly out of scope.
const DefaultTimeoutSeconds = 60
DefaultTimeoutSeconds is the per-hook execution timeout when HookConfig.Timeout is nil (FR-11). A slow or hung hook is killed after this many seconds and treated as a failure (fail-open for blocking hooks).
const EventPreToolUse = "PreToolUse"
EventPreToolUse is the one event whose first block short-circuits the rest of the chain. Declared here (rather than importing a shared constants file) so the hooks package stays a leaf; the string must match what callers dispatch.
const MaxOutputBytes = 1 << 20 // 1 MB
MaxOutputBytes caps the bytes captured from a hook's stdout and stderr each (FR-13). Output beyond this is dropped and the truncation is flagged; the captured prefix is still parsed so a hook that prints a small JSON decision followed by noise still works.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Dispatcher ¶
type Dispatcher struct {
// contains filtered or unexported fields
}
Dispatcher runs the hooks configured for an event and merges their results. A nil *Dispatcher is a valid no-op (Dispatch returns an empty decision), so callers can hold a possibly-nil dispatcher without guarding every call.
func NewDispatcher ¶
func NewDispatcher(set HookSet, projectDir string, warnLog io.Writer) *Dispatcher
NewDispatcher builds a dispatcher over the given hook set. It returns nil when the set is empty, so the common no-hooks case costs nothing and callers can treat nil as "hooks disabled" (FR-18). projectDir is where hook commands run; warnLog receives isolation warnings (may be nil).
func (*Dispatcher) Dispatch ¶
func (d *Dispatcher) Dispatch(ctx context.Context, eventType, toolName string, input HookInput) HookDecision
Dispatch runs every hook matching (eventType, toolName) in order and returns the merged decision. On a nil dispatcher or no matched hooks it returns the zero HookDecision. A hook that fails to run is warned about and skipped (fail-open, FR-15). For PreToolUse the first block stops the chain so a blocked call is not subsequently rewritten.
type HookConfig ¶
type HookConfig struct {
Type string `json:"type"` // v1: fixed "command"
Command string `json:"command"` // handed to the system shell
Timeout *int `json:"timeout,omitempty"` // seconds; nil = DefaultTimeoutSeconds
}
HookConfig is a single hook command.
func (HookConfig) TimeoutSeconds ¶
func (h HookConfig) TimeoutSeconds() int
TimeoutSeconds returns the effective timeout for the hook: its own Timeout when set to a positive value, otherwise DefaultTimeoutSeconds. A non-positive override is ignored so a misconfigured 0/negative value cannot disable the timeout guard.
func (HookConfig) Validate ¶
func (h HookConfig) Validate() error
Validate reports whether the hook is well-formed: the type must be "command" (empty is accepted and treated as "command" for convenience) and the command must be non-empty. An invalid hook is rejected at load time and skipped with a warning rather than executed.
type HookDecision ¶
type HookDecision struct {
Block bool
Reason string
AdditionalContext string
UpdatedInput json.RawMessage
}
HookDecision is the dispatcher's merged result after running all matched hooks for one event. Block is set if any hook blocked; Reason accumulates the blocking reasons; AdditionalContext accumulates injected context in order; UpdatedInput holds the last-provided rewrite (last writer wins, §5.4).
type HookInput ¶
type HookInput struct {
EventType string `json:"event_type"`
SessionID string `json:"session_id,omitempty"`
ProjectDir string `json:"project_dir,omitempty"`
ToolName string `json:"tool_name,omitempty"` // Pre/PostToolUse
ToolInput json.RawMessage `json:"tool_input,omitempty"` // Pre/PostToolUse
ToolResponse json.RawMessage `json:"tool_response,omitempty"` // PostToolUse
Prompt string `json:"prompt,omitempty"` // UserPromptSubmit
StopReason string `json:"stop_reason,omitempty"` // Stop/SessionEnd
Source string `json:"source,omitempty"` // SessionStart (startup/resume)
Trigger string `json:"trigger,omitempty"` // PreCompact (manual/auto)
Message string `json:"message,omitempty"` // Notification
}
HookInput is the JSON payload golder writes to a hook command's stdin. It carries only observable, non-secret fields (FR-17) — never API keys or credentials. Per-event fields are omitempty so a payload only contains the fields relevant to its event type.
type HookMatcherConfig ¶
type HookMatcherConfig struct {
Matcher string `json:"matcher,omitempty"`
Hooks []HookConfig `json:"hooks"`
}
HookMatcherConfig binds a group of hooks to a matcher. An empty (or "*") matcher applies to every trigger of the event; otherwise it is matched against the tool name (see matcher.go).
type HookNotifier ¶
type HookNotifier struct {
// contains filtered or unexported fields
}
HookNotifier forwards agent lifecycle events to observer-only hooks. Handle maps AgentEndEvent→SessionEnd and CompactionEvent→PreCompact; Notify emits a Notification event for out-of-band prompts (e.g. a trust confirmation). The merged decision is intentionally discarded — these events have no in-flight action to veto.
func NewHookNotifier ¶
func NewHookNotifier(d *Dispatcher, sessionID, projectDir string) *HookNotifier
NewHookNotifier returns a notifier over d, or nil when d is nil (no hooks) so the caller can skip the OnEvent wiring entirely. sessionID and projectDir populate every emitted HookInput.
func (*HookNotifier) Handle ¶
func (n *HookNotifier) Handle(ev agentcore.AgentEvent)
Handle maps an observed event to its observer hook and fires it. Events with no observer mapping (turn/message/tool events) are ignored. It is a no-op on a nil notifier, so it can be chained onto OnEvent unconditionally.
func (*HookNotifier) Notify ¶
func (n *HookNotifier) Notify(message string)
Notify fires the Notification event with a human-readable message. It is used for out-of-band prompts that are not part of the event stream, such as a trust confirmation for an untrusted-directory bash/write. A no-op on a nil notifier or an empty message.
type HookOutput ¶
type HookOutput struct {
Decision string `json:"decision,omitempty"` // "block" | "approve" | ""
Reason string `json:"reason,omitempty"`
AdditionalContext string `json:"additionalContext,omitempty"`
Continue *bool `json:"continue,omitempty"`
UpdatedInput json.RawMessage `json:"updatedInput,omitempty"` // PreToolUse: rewrite tool args
}
HookOutput is the optional JSON a hook may print to stdout to influence the agent. A non-JSON stdout on exit 0 is treated as an empty HookOutput (no operation). Decision "block" is equivalent to exiting with code 2.
type HookSet ¶
type HookSet map[string][]HookMatcherConfig
HookSet maps an event type (e.g. "PreToolUse") to its matcher list. It is the shape stored in a ConfigLayer and in the resolved Config.
func (HookSet) MatchHooks ¶
func (s HookSet) MatchHooks(eventType, toolName string, warnLog io.Writer) []HookConfig
MatchHooks returns every valid hook under eventType whose matcher matches toolName, preserving config order (layer order + declaration order within a layer). For events that do not carry a tool name (toolName == ""), matchers are ignored and all hooks under the event fire. Invalid hooks (see HookConfig.Validate) are skipped; a matcher whose regexp fails to compile is skipped with a warning on warnLog (when non-nil).
type Runner ¶
Runner executes hook commands. Shell defaults to "sh" with a "-c" flag; it is a field so tests can substitute a shell and future platforms can override it. ProjectDir is the working directory hook commands run in (the project root).
func (*Runner) Run ¶
func (r *Runner) Run(ctx context.Context, h HookConfig, input HookInput) (HookOutput, error)
Run executes one hook, writing input as a single-line JSON document to the command's stdin. It returns the parsed HookOutput and a non-nil error only for an execution *failure* (could not start, timed out, or exited non-zero and non-2). A clean exit 0 or a block (exit 2) both return err == nil; the caller distinguishes a block via HookOutput.blocks(). The GOLDER_* environment variables are injected on top of the current process environment.