Skip to content
Source on GitHub (opens in a new tab)
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.

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

The PreToolUse decisions, from most restrictive to least.

const EventCwdChanged = runtime.EventCwdChanged

EventCwdChanged names the CwdChanged hook point.

const EventInstructionsLoaded = runtime.EventInstructionsLoaded

EventInstructionsLoaded names the InstructionsLoaded hook point.

const EventInterrupt = runtime.EventInterrupt

EventInterrupt names the Interrupt hook point.

const EventNotification = runtime.EventNotification

EventNotification names the Notification hook point.

const EventPermissionDenied = runtime.EventPermissionDenied

EventPermissionDenied names the PermissionDenied hook point.

const EventPermissionRequest = runtime.EventPermissionRequest

EventPermissionRequest names the PermissionRequest hook point.

const EventPostCompact = runtime.EventPostCompact

EventPostCompact names the PostCompact hook point.

const EventPostModelSwitch = runtime.EventPostModelSwitch

EventPostModelSwitch names the PostModelSwitch hook point.

const EventPostToolBatch = runtime.EventPostToolBatch

EventPostToolBatch names the PostToolBatch hook point.

const EventPostToolUse = runtime.EventPostToolUse

EventPostToolUse names the PostToolUse hook point.

const EventPostToolUseFailure = runtime.EventPostToolUseFailure

EventPostToolUseFailure names the PostToolUseFailure hook point.

const EventPreCompact = runtime.EventPreCompact

EventPreCompact names the PreCompact hook point.

const EventPreModelSwitch = runtime.EventPreModelSwitch

EventPreModelSwitch names the PreModelSwitch hook point.

const EventPreToolUse = runtime.EventPreToolUse

EventPreToolUse names the PreToolUse hook point.

const EventSessionEnd = runtime.EventSessionEnd

EventSessionEnd names the SessionEnd hook point.

const EventSessionStart = runtime.EventSessionStart

EventSessionStart names the SessionStart hook point.

const EventSkillLoaded = runtime.EventSkillLoaded

EventSkillLoaded names the SkillLoaded hook point.

const EventStop = runtime.EventStop

EventStop names the Stop hook point.

const EventSubagentStart = runtime.EventSubagentStart

EventSubagentStart names the SubagentStart hook point.

const EventSubagentStop = runtime.EventSubagentStop

EventSubagentStop names the SubagentStop hook point.

const EventUserPromptSubmit = runtime.EventUserPromptSubmit

EventUserPromptSubmit names the UserPromptSubmit hook point.

var ErrInvalid = runtime.ErrInvalid

ErrInvalid reports a nil callback or invalid event registration.

var ErrUnsupported = runtime.ErrUnsupported

ErrUnsupported reports an invalid decision or unsupported runtime output.

type Base = runtime.Base

Base describes common invocation identity.

type CompactInput = runtime.CompactInput

CompactInput describes an upcoming compaction.

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.

func (o ContextOutput) WithContext(text string) ContextOutput

WithContext adds model context at this lifecycle point.

type Decision = event.HookDecision

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

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.

func (o DeniedOutput) WithNote(note string) DeniedOutput

WithNote adds a denial note.

type Event = runtime.Event

Event names a hook point.

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.

func Block(reason string) GateOutput

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

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.

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

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

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.

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.

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

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

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

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

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.

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.

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

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

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

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

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.

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:

no-apply deny apply runs only in CI
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.

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

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:

true
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.

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.

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

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

func (h Hook) Event() Event

Event returns the callback’s event point.

func (h Hook) Matches(key string) bool

Matches reports whether the callback selects key.

func (h Hook) Name() string

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

func (h Hook) Validate() error

Validate reports invalid registration without invoking the callback.

type Matcher = runtime.Matcher

Matcher selects invocations using separate wildcard patterns.

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.

type ObservedInput = runtime.ObservedInput

ObservedInput describes an observation notification.

type Option = runtime.Option

Option configures hook registration.

func WithAsync() Option

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

func WithChildren() Option

WithChildren applies the hook inside child sessions too.

func WithName(name string) Option

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

func WithTimeout(d time.Duration) Option

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

type PermissionDecision string

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

const PermissionAllow PermissionDecision = "allow"

PermissionAllow approves an action at the human approval gate.

const PermissionDeny PermissionDecision = "deny"

PermissionDeny refuses an action at the human approval gate.

type PermissionInput = runtime.PermissionInput

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

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.

func AllowSession(id string) PermissionOutput

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

type PreToolUseInput = runtime.PreToolUseInput

PreToolUseInput describes a tool call before policy evaluation.

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.

func Allow() PreToolUseOutput

Allow permits a proposed action subject to ordinary policy ceilings.

func Ask(reason string) PreToolUseOutput

Ask requires a human for the proposed action.

func Defer(reason string) PreToolUseOutput

Defer suspends until a human answers the proposed action.

func Deny(reason string) PreToolUseOutput

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

func Rewrite(input json.RawMessage) PreToolUseOutput

Rewrite substitutes input that is evaluated through policy again.

func (o PreToolUseOutput) WithContext(text string) PreToolUseOutput

WithContext adds model context to this tool decision.

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

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

type PromptInput = runtime.PromptInput

PromptInput describes a submitted user prompt.

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.

func (o PromptOutput) WithContext(text string) PromptOutput

WithContext adds context to a user prompt decision.

type ResultInput = runtime.ResultInput

ResultInput describes a completed tool call.

type SessionInput = runtime.SessionInput

SessionInput describes a session startup or resume.

type StopInput = runtime.StopInput

StopInput describes a candidate run ending.

type SubagentInput = runtime.SubagentInput

SubagentInput describes a child session starting.

type SwitchInput = runtime.SwitchInput

SwitchInput describes a proposed model switch.

type ToolInput = runtime.ToolInput

ToolInput describes a proposed tool call.

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.

func Replace(output string) ToolResultOutput

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

func (o ToolResultOutput) WithContext(text string) ToolResultOutput

WithContext adds model context after a tool result.

func (o ToolResultOutput) WithNote(text string) ToolResultOutput

WithNote adds a classifier note after a tool result.