# hook

> Package hook defines typed, in-process hooks: Go functions zelk runs at fixed points of the loop, the main way a host customizes behaviour without forking zelk.

<!-- Generated from the Go source of github.com/barevoidco/zelk/core/hook (cmd/zelk/internal/reference TestReferenceGoAPI). Don't edit: change the code, then run make reference. -->

```go
import "github.com/barevoidco/zelk/core/hook"
```

Package hook defines typed, in-process hooks: Go functions zelk runs at fixed points of the loop, the main way a host customizes behaviour without forking zelk.

Gate hooks (PreToolUse, UserPromptSubmit, Stop and the others that can change what happens) run as durable effects: each invocation is logged before it runs, its decision is recorded, and replay or resume use the recorded decision without running the hook again. A gate that fails, panics or times out fails closed. Observe-only hooks, and gate hooks registered with WithAsync, run in the background, can't change anything and are best effort: never re-run after a crash.

Results of several hooks of one event combine deterministically, by registration order: the most restrictive decision wins (deny > defer > ask > allow), at most one hook may rewrite an input or replace an output, and extra context is concatenated.

Each event constructor requires its permitted output type. Hosts register definitions; the root owner invokes and joins them through internal runtime methods. Match preserves separate wildcard patterns, including literal pipes.


## Constants

```go
const (
	DecideDeny  = event.HookDeny
	DecideDefer = event.HookDefer
	DecideAsk   = event.HookAsk
	DecideAllow = event.HookAllow
)
```

The PreToolUse decisions, from most restrictive to least.

```go
const EventCwdChanged = runtime.EventCwdChanged
```

EventCwdChanged names the CwdChanged hook point.

```go
const EventInstructionsLoaded = runtime.EventInstructionsLoaded
```

EventInstructionsLoaded names the InstructionsLoaded hook point.

```go
const EventInterrupt = runtime.EventInterrupt
```

EventInterrupt names the Interrupt hook point.

```go
const EventNotification = runtime.EventNotification
```

EventNotification names the Notification hook point.

```go
const EventPermissionDenied = runtime.EventPermissionDenied
```

EventPermissionDenied names the PermissionDenied hook point.

```go
const EventPermissionRequest = runtime.EventPermissionRequest
```

EventPermissionRequest names the PermissionRequest hook point.

```go
const EventPostCompact = runtime.EventPostCompact
```

EventPostCompact names the PostCompact hook point.

```go
const EventPostModelSwitch = runtime.EventPostModelSwitch
```

EventPostModelSwitch names the PostModelSwitch hook point.

```go
const EventPostToolBatch = runtime.EventPostToolBatch
```

EventPostToolBatch names the PostToolBatch hook point.

```go
const EventPostToolUse = runtime.EventPostToolUse
```

EventPostToolUse names the PostToolUse hook point.

```go
const EventPostToolUseFailure = runtime.EventPostToolUseFailure
```

EventPostToolUseFailure names the PostToolUseFailure hook point.

```go
const EventPreCompact = runtime.EventPreCompact
```

EventPreCompact names the PreCompact hook point.

```go
const EventPreModelSwitch = runtime.EventPreModelSwitch
```

EventPreModelSwitch names the PreModelSwitch hook point.

```go
const EventPreToolUse = runtime.EventPreToolUse
```

EventPreToolUse names the PreToolUse hook point.

```go
const EventSessionEnd = runtime.EventSessionEnd
```

EventSessionEnd names the SessionEnd hook point.

```go
const EventSessionStart = runtime.EventSessionStart
```

EventSessionStart names the SessionStart hook point.

```go
const EventSkillLoaded = runtime.EventSkillLoaded
```

EventSkillLoaded names the SkillLoaded hook point.

```go
const EventStop = runtime.EventStop
```

EventStop names the Stop hook point.

```go
const EventSubagentStart = runtime.EventSubagentStart
```

EventSubagentStart names the SubagentStart hook point.

```go
const EventSubagentStop = runtime.EventSubagentStop
```

EventSubagentStop names the SubagentStop hook point.

```go
const EventUserPromptSubmit = runtime.EventUserPromptSubmit
```

EventUserPromptSubmit names the UserPromptSubmit hook point.


## Variables

```go
var ErrInvalid = runtime.ErrInvalid
```

ErrInvalid reports a nil callback or invalid event registration.

```go
var ErrUnsupported = runtime.ErrUnsupported
```

ErrUnsupported reports an invalid decision or unsupported runtime output.


## Base

```go
type Base = runtime.Base
```

Base describes common invocation identity.


## CompactInput

```go
type CompactInput = runtime.CompactInput
```

CompactInput describes an upcoming compaction.


## ContextOutput

```go
type ContextOutput struct {
	Context string
	// Message is for the user, never the model: a warning the host shows
	// where the hook ran.
	Message string
}
```

ContextOutput adds model context at a non-blocking lifecycle point. A SubagentStart hook can't return a Message: it runs while the child is configured, where nothing records it.


### ContextOutput.WithContext

```go
func (o ContextOutput) WithContext(text string) ContextOutput
```

WithContext adds model context at this lifecycle point.


## Decision

```go
type Decision = event.HookDecision
```

Decision is a PreToolUse decision; the zero value leaves policy unchanged.


## DeniedOutput

```go
type DeniedOutput struct {
	Note string
	// Message is for the user, never the model: a warning the host shows
	// where the hook ran.
	Message string
}
```

DeniedOutput adds a model note about a denied action.


### DeniedOutput.WithNote

```go
func (o DeniedOutput) WithNote(note string) DeniedOutput
```

WithNote adds a denial note.


## Event

```go
type Event = runtime.Event
```

Event names a hook point.


## GateOutput

```go
type GateOutput struct {
	Block  bool
	Reason string
	// Message is for the user, never the model: a warning the host shows
	// where the hook ran.
	Message string
}
```

GateOutput blocks a stop, compaction or model switch, or leaves it unchanged.


### Block

```go
func Block(reason string) GateOutput
```

Block prevents a stop, compaction or model switch with the given reason.


## Hook

```go
type Hook runtime.Hook
```

Hook is an immutable event callback definition registered with zelk.WithHooks. Its zero value is invalid; hosts do not invoke registered hooks directly.


### Observe

```go
func Observe(e Event, fn func(context.Context, ObservedInput) error, opts ...Option) Hook
```

Observe registers a best-effort callback for an observation-only event.


### PermissionDenied

```go
func PermissionDenied(m Matcher, fn func(context.Context, PermissionInput) (DeniedOutput, error), opts ...Option) Hook
```

PermissionDenied registers fn at the PermissionDenied event with its permitted output shape.


### PermissionRequest

```go
func PermissionRequest(m Matcher, fn func(context.Context, PermissionInput) (PermissionOutput, error), opts ...Option) Hook
```

PermissionRequest registers fn at the PermissionRequest event with its permitted output shape.


### PostModelSwitch

```go
func PostModelSwitch(fn func(context.Context, SwitchInput) (ContextOutput, error), opts ...Option) Hook
```

PostModelSwitch registers fn at the PostModelSwitch event with its permitted output shape.


### PostToolBatch

```go
func PostToolBatch(fn func(context.Context, Base) (ContextOutput, error), opts ...Option) Hook
```

PostToolBatch registers fn at the PostToolBatch event with its permitted output shape.


### PostToolUse

```go
func PostToolUse(m Matcher, fn func(context.Context, ResultInput) (ToolResultOutput, error), opts ...Option) Hook
```

PostToolUse registers fn at the PostToolUse event with its permitted output shape.


### PostToolUseFailure

```go
func PostToolUseFailure(m Matcher, fn func(context.Context, ResultInput) (ToolResultOutput, error), opts ...Option) Hook
```

PostToolUseFailure registers fn at the PostToolUseFailure event with its permitted output shape.


### PreCompact

```go
func PreCompact(fn func(context.Context, CompactInput) (GateOutput, error), opts ...Option) Hook
```

PreCompact registers fn at the PreCompact event with its permitted output shape.


### PreModelSwitch

```go
func PreModelSwitch(fn func(context.Context, SwitchInput) (GateOutput, error), opts ...Option) Hook
```

PreModelSwitch registers fn at the PreModelSwitch event with its permitted output shape.


### PreToolUse

```go
func PreToolUse(m Matcher, fn func(context.Context, PreToolUseInput) (PreToolUseOutput, error), opts ...Option) Hook
```

PreToolUse registers fn at the PreToolUse event with its permitted output shape.

**Example**

Register the definition with zelk.WithHooks; the execution owner invokes it.

```go
decide := func(_ context.Context, in hook.PreToolUseInput) (hook.PreToolUseOutput, error) {
	if strings.Contains(in.Command(), "terraform apply") {
		return hook.Deny("apply runs only in CI"), nil
	}
	return hook.PreToolUseOutput{}, nil
}
definition := hook.PreToolUse(hook.Match("Bash"), decide, hook.WithName("no-apply"))
result, err := decide(context.Background(), hook.PreToolUseInput{Input: []byte(`{"command":"terraform apply"}`)})
if err != nil {
	panic(err)
}
fmt.Println(definition.Name(), result.Decision, result.Reason)
// Output: no-apply deny apply runs only in CI
```

Output:

```text
no-apply deny apply runs only in CI
```


### SessionStart

```go
func SessionStart(m Matcher, fn func(context.Context, SessionInput) (ContextOutput, error), opts ...Option) Hook
```

SessionStart registers fn at the SessionStart event with its permitted output shape.


### Stop

```go
func Stop(fn func(context.Context, StopInput) (GateOutput, error), opts ...Option) Hook
```

Stop registers fn at the Stop event with its permitted output shape.

**Example**

```go
check := func(_ context.Context, in hook.StopInput) (hook.GateOutput, error) {
	if !strings.Contains(in.Text, "tests pass") {
		return hook.Block("Run the tests and fix any failure before you finish."), nil
	}
	return hook.GateOutput{}, nil
}
definition := hook.Stop(check)
if err := definition.Validate(); err != nil {
	panic(err)
}
result, err := check(context.Background(), hook.StopInput{Text: "Done."})
if err != nil {
	panic(err)
}
fmt.Println(result.Block)
// Output: true
```

Output:

```text
true
```


### SubagentStart

```go
func SubagentStart(m Matcher, fn func(context.Context, SubagentInput) (ContextOutput, error), opts ...Option) Hook
```

SubagentStart registers fn at the SubagentStart event with its permitted output shape.


### SubagentStop

```go
func SubagentStop(m Matcher, fn func(context.Context, StopInput) (GateOutput, error), opts ...Option) Hook
```

SubagentStop registers fn at the SubagentStop event with its permitted output shape.


### UserPromptSubmit

```go
func UserPromptSubmit(fn func(context.Context, PromptInput) (PromptOutput, error), opts ...Option) Hook
```

UserPromptSubmit registers fn at the UserPromptSubmit event with its permitted output shape.


### Hook.Event

```go
func (h Hook) Event() Event
```

Event returns the callback's event point.


### Hook.Matches

```go
func (h Hook) Matches(key string) bool
```

Matches reports whether the callback selects key.


### Hook.Name

```go
func (h Hook) Name() string
```

Name returns the registered name, or an empty string before automatic naming.


### Hook.Validate

```go
func (h Hook) Validate() error
```

Validate reports invalid registration without invoking the callback.


## Matcher

```go
type Matcher = runtime.Matcher
```

Matcher selects invocations using separate wildcard patterns.


### Match

```go
func Match(patterns ...string) Matcher
```

Match selects any of patterns. With no patterns it selects every invocation. A vertical bar is a literal character, not an alternative separator.


## ObservedInput

```go
type ObservedInput = runtime.ObservedInput
```

ObservedInput describes an observation notification.


## Option

```go
type Option = runtime.Option
```

Option configures hook registration.


### WithAsync

```go
func WithAsync() Option
```

WithAsync runs best-effort observation without allowing a gate decision.


### WithChildren

```go
func WithChildren() Option
```

WithChildren applies the hook inside child sessions too.


### WithName

```go
func WithName(name string) Option
```

WithName supplies a stable identity used to resume recorded gate invocations.


### WithTimeout

```go
func WithTimeout(d time.Duration) Option
```

WithTimeout bounds one invocation; a timed-out gate fails closed.


## PermissionDecision

```go
type PermissionDecision string
```

PermissionDecision is an approval hook's allow-or-deny answer.

```go
const PermissionAllow PermissionDecision = "allow"
```

PermissionAllow approves an action at the human approval gate.

```go
const PermissionDeny PermissionDecision = "deny"
```

PermissionDeny refuses an action at the human approval gate.


## PermissionInput

```go
type PermissionInput = runtime.PermissionInput
```

PermissionInput describes a call needing human input or denied by policy.


## PermissionOutput

```go
type PermissionOutput struct {
	Decision   PermissionDecision
	Reason     string
	Suggestion string
	// Message is for the user, never the model: a warning the host shows
	// where the hook ran.
	Message string
}
```

PermissionOutput approves or denies a request, optionally granting an offered rule.


### AllowSession

```go
func AllowSession(id string) PermissionOutput
```

AllowSession approves a permission request and grants its offered rule by ID.


## PreToolUseInput

```go
type PreToolUseInput = runtime.PreToolUseInput
```

PreToolUseInput describes a tool call before policy evaluation.


## PreToolUseOutput

```go
type PreToolUseOutput struct {
	Decision Decision
	Reason   string
	Input    json.RawMessage
	Context  string
	// Message is for the user, never the model: a warning the host shows
	// where the hook ran.
	Message string
}
```

PreToolUseOutput can decide, rewrite a tool input or add model context.


### Allow

```go
func Allow() PreToolUseOutput
```

Allow permits a proposed action subject to ordinary policy ceilings.


### Ask

```go
func Ask(reason string) PreToolUseOutput
```

Ask requires a human for the proposed action.


### Defer

```go
func Defer(reason string) PreToolUseOutput
```

Defer suspends until a human answers the proposed action.


### Deny

```go
func Deny(reason string) PreToolUseOutput
```

Deny refuses a proposed action with a model-visible reason.


### Rewrite

```go
func Rewrite(input json.RawMessage) PreToolUseOutput
```

Rewrite substitutes input that is evaluated through policy again.


### PreToolUseOutput.WithContext

```go
func (o PreToolUseOutput) WithContext(text string) PreToolUseOutput
```

WithContext adds model context to this tool decision.


### PreToolUseOutput.WithInput

```go
func (o PreToolUseOutput) WithInput(input json.RawMessage) PreToolUseOutput
```

WithInput rewrites the tool input; the replacement is evaluated by policy.


## PromptInput

```go
type PromptInput = runtime.PromptInput
```

PromptInput describes a submitted user prompt.


## PromptOutput

```go
type PromptOutput struct {
	Block   bool
	Reason  string
	Context string
	// Message is for the user, never the model: a warning the host shows
	// where the hook ran.
	Message string
}
```

PromptOutput blocks a user prompt or adds context before it is submitted.


### PromptOutput.WithContext

```go
func (o PromptOutput) WithContext(text string) PromptOutput
```

WithContext adds context to a user prompt decision.


## ResultInput

```go
type ResultInput = runtime.ResultInput
```

ResultInput describes a completed tool call.


## SessionInput

```go
type SessionInput = runtime.SessionInput
```

SessionInput describes a session startup or resume.


## StopInput

```go
type StopInput = runtime.StopInput
```

StopInput describes a candidate run ending.


## SubagentInput

```go
type SubagentInput = runtime.SubagentInput
```

SubagentInput describes a child session starting.


## SwitchInput

```go
type SwitchInput = runtime.SwitchInput
```

SwitchInput describes a proposed model switch.


## ToolInput

```go
type ToolInput = runtime.ToolInput
```

ToolInput describes a proposed tool call.


## ToolResultOutput

```go
type ToolResultOutput struct {
	Output  string
	Replace bool
	Context string
	Note    string
	// Message is for the user, never the model: a warning the host shows
	// where the hook ran.
	Message string
}
```

ToolResultOutput can replace a model-visible result and add context or a note.


### Replace

```go
func Replace(output string) ToolResultOutput
```

Replace substitutes a tool result's model-visible text.


### ToolResultOutput.WithContext

```go
func (o ToolResultOutput) WithContext(text string) ToolResultOutput
```

WithContext adds model context after a tool result.


### ToolResultOutput.WithNote

```go
func (o ToolResultOutput) WithNote(text string) ToolResultOutput
```

WithNote adds a classifier note after a tool result.
