# Hooks

> Your own code, run at fixed points in a session. What a hook can decide, why a gate decides before a call exists, and what a timeout does.

A hook is your own code, run by zelk at a fixed point in a session: before a
tool runs, after it, when you send a prompt, when a run is about to stop.
You use one to enforce a policy ("never `terraform apply` outside CI"), to
format a file after an edit, to notify someone when a run ends, or to audit
what the agent did. Hooks are how you change what zelk does without forking
it.

The diagram lays a session out as a track. A socket is a point where a hook
can plug in, and a plug is a registered hook, labelled with its command. The
token is the run: it stops at a gate while the hook runs, and never stops at
an async socket. The scenes play a gate that allows, asks you and denies,
two kinds of timeout, and a crash followed by a replay.

A session’s lifecycle is a track: session starts (`SessionStart`) → prompt submitted (`UserPromptSubmit`) → before the tool (`PreToolUse`) → the tool runs → after the tool (`PostToolUse`) → run stops (`Stop`) → run ends (`SessionEnd`). Each of those points with an event is a socket where a hook plugs in. A **gate** hook stops the token until it has decided; an **async** hook lets it through while the hook runs off to the side.

| Event | Runs as | A hook can |
|---|---|---|
| `SessionStart` | gate, or async if registered so | add context |
| `UserPromptSubmit` | gate, or async if registered so | block the prompt, or add context |
| `PreToolUse` | gate, or async if registered so | allow, deny, ask or defer; rewrite the input; add context |
| `PermissionRequest` | gate, or async if registered so | allow or deny, in a person’s place |
| `PermissionDenied` | gate, or async if registered so | add a note for the model |
| `PostToolUse` | gate, or async if registered so | add context; in Go, replace the result |
| `PostToolUseFailure` | gate, or async if registered so | add context; in Go, replace the result |
| `PostToolBatch` | gate, or async if registered so | add context |
| `Stop` | gate, or async if registered so | block, which sends the run back to work |
| `SubagentStop` | gate, or async if registered so | block, which sends the subagent back to work |
| `SubagentStart` | runs as the child is configured | add context for the child |
| `PreCompact` | gate, or async if registered so | block a compaction zelk chose to make |
| `PostCompact` | async: observes only | observe |
| `PreModelSwitch` | gate, or async if registered so | block the switch |
| `PostModelSwitch` | gate, or async if registered so | add context |
| `InstructionsLoaded` | async: observes only | observe |
| `SkillLoaded` | async: observes only | observe |
| `CwdChanged` | async: observes only | observe |
| `Notification` | async: observes only | observe |
| `SessionEnd` | async: observes only | observe |
| `Interrupt` | async: observes only | observe |

Each scene is the log as it grows, with the model’s own calls left out:

- **A gate allows**. A gate stops the run until it has decided. Allow opens it, and the call goes on to record its intent, though it still meets the permission rules. An async hook is different: the token passes straight through while format runs off to the side, best effort, and the log never hears of it. Plugged in: ./check-path.sh at `PreToolUse`, format at `PostToolUse`.
   1. `command_accepted` user_message: tidy main.go
   2. `effect_started` run_hook check-path · s1:2:0
   3. `hook_decided` check-path: allow
   4. `effect_started` run_tool Edit main.go
   5. `effect_finished` Edit main.go → ok
   6. `run_finished` success
- **A gate asks you**. Ask sends the call out to a person. The call waits as an approval and nothing runs. If you allow it, the gate opens and the intent is recorded; if you deny it, the call ends as a refusal with no intent. A hook that answers defer asks the same way, and lets the session suspend while it waits. Plugged in: ./confirm-push.sh at `PreToolUse`.
   1. `command_accepted` user_message: ship the fix
   2. `effect_started` run_hook confirm-push · s1:2:0
   3. `hook_decided` confirm-push: ask
   4. `effect_started` await_input: approve Bash
   5. `command_accepted` answer: allow
   6. `effect_started` run_tool Bash git push
   7. `effect_finished` Bash git push → ok
   8. `run_finished` success
- **A gate denies**. A gate decides before the call has an intent. Deny closes the gate and the token turns back with a refusal as the call’s result. The log never holds an effect_started for the call, so a crash has nothing to leave open, and the tool is never reached. The notify hook at the end only observes: it can change nothing. Plugged in: ./no-rm.sh at `PreToolUse`, notify at `SessionEnd`.
   1. `command_accepted` user_message: clear the build directory
   2. `effect_started` run_hook no-rm · s1:2:0
   3. `hook_decided` no-rm: deny
   4. `permission_decided` deny: a PreToolUse hook denied it
   5. `run_finished` success
   Not in the log: `no effect_started run_tool Bash rm -rf build`
- **A Go gate times out**. A gate that can’t decide fails closed. A Go hook gets 30 seconds unless it sets hook.WithTimeout. When it times out, the timeout is recorded as the hook’s decision, and the gate denies. The same goes for a Go hook that returns an error, panics, or isn’t registered when the session resumes. Plugged in: approval-check at `PreToolUse`.
   1. `command_accepted` user_message: apply the plan
   2. `effect_started` run_hook approval-check · s1:2:0
   3. `hook_decided` approval-check: timed out
   4. `permission_decided` deny: the PreToolUse hook approval-check timed out, so the call didn’t run
   5. `run_finished` success
   Not in the log: `no effect_started run_tool Bash terraform apply`
- **A hooks.json hook times out**. A hooks.json hook that fails doesn’t block. Its timeout is 60 seconds by default. A timeout, a command that can’t start, or output zelk can’t honor is a non-blocking error: you are shown the failure, and the call goes on. A hook that must not let an action through when it breaks sets "onFailure": "block", which makes a failure deny. Plugged in: ./slow-check.sh at `PreToolUse`.
   1. `command_accepted` user_message: apply the plan
   2. `effect_started` run_hook slow-check · s1:2:0
   3. `hook_decided` slow-check: no decision, it failed
   4. `effect_started` run_tool Bash terraform apply
   5. `effect_finished` Bash terraform apply → ok
   6. `run_finished` success
- **A crash, then replay**. A recorded decision is read back, never run again. The new process folds the log, and a decision in it is final: load-env is not run again. The hook the crash cut off has no decision, so it runs again with the same invocation ID. It may fire twice, so a hook with side effects, such as an audit post, deduplicates by that ID. Plugged in: ./load-env.sh at `SessionStart`, ./audit.sh at `PreToolUse`.
   1. `effect_started` run_hook load-env · s1:1:0
   2. `hook_decided` load-env: allow
   3. `command_accepted` user_message: ship the fix
   4. `effect_started` run_hook audit · s1:4:0
   5. `attempt_ended` run_hook audit · s1:4:0 → lost
   6. `effect_started` run_hook audit · s1:4:0
   7. `hook_decided` audit: allow
   8. `effect_started` run_tool Bash git push
   9. `effect_finished` Bash git push → ok
   10. `run_finished` success

## Gate hooks and async hooks

A hook runs one of two ways.

A **gate** hook is one the run waits for. zelk records its invocation and
its decision in the session's log, and the decision can change what happens
next. Most events are gates.

An **async** hook is one the run doesn't wait for. It runs in the
background, best effort, and can't change anything. It is never recorded as
an intent and never run again after a crash. Events that only observe, such
as `SessionEnd`, always work this way. In Go, `hook.WithAsync()` makes any
other hook async, as the `format` hook in the first scene is. `hooks.json`
has no async flag.

## The events

| When | Events | Runs as |
|---|---|---|
| A session starts, resumes or compacts | `SessionStart` | gate |
| You send a prompt | `UserPromptSubmit` | gate |
| A tool call is about to be decided | `PreToolUse` | gate |
| A call would ask you, or was refused | `PermissionRequest`, `PermissionDenied` | gate |
| A tool call has finished | `PostToolUse`, `PostToolUseFailure`, and `PostToolBatch` once all of a turn's calls have results | gate |
| A run is about to end | `Stop`, or `SubagentStop` in a subagent | gate |
| A subagent starts | `SubagentStart` | run as the child is configured |
| A compaction | `PreCompact` | gate |
| A model switch | `PreModelSwitch`, `PostModelSwitch` | gate |
| Something happened | `InstructionsLoaded`, `SkillLoaded`, `CwdChanged`, `Notification`, `SessionEnd`, `Interrupt`, `PostCompact` | async: observe only |

The `Post` gates run as recorded gates too, so a decision once recorded is
never run again; a crash while one runs reruns it with the same invocation
ID, as for any gate (below). Either way the tool has already run: they can add context to its result, not take
the call back. `hooks.json` also takes `WorktreeCreate` and
`WorktreeRemove`, which the host runs itself in git's place, outside the
loop. [The hooks contract](/internals/hooks/) gives what each event's hook
receives and may return.

## What a gate decides

A `PreToolUse` gate answers with one of four decisions:

- **allow** lets the call go on to the permission rules. It acts like an
  allow rule, so it can't override a deny rule, a protected path or plan
  mode.
- **deny** refuses the call. Its result is a refusal, which the model reads
  on its next call.
- **ask** makes the call human-only: an approval waits, nothing runs, and
  where no one can be asked the call is refused.
- **defer** asks the same way, and lets the session suspend until a person
  answers, perhaps hours later and from another process.

A hook may also rewrite the call's input, which is then decided afresh, and
add context for the model. When several hooks match, the strictest answer
wins: deny, then defer, then ask, then allow. Two hooks that both rewrite
the input fail the gate closed.

The other gates answer more simply. A `UserPromptSubmit` hook can block the
prompt, and a `PreModelSwitch` or `PreCompact` hook the switch or the
compaction. A `Stop` hook that blocks sends the run back to work with its
reason as the next prompt, at most three times in a run: this is how a host
enforces "run the tests before you finish".

## Before the call has an intent

A gate decides before the tool call it guards has an intent in the log. The
loop asks for the hook instead of the call, the driver records the hook's
decision, and only once every gate has decided is the call's intent written,
if it is written at all. So an intent in the log always means its gates let
the call through.

A denied call therefore never starts. Its log has the hook's invocation and
decision and a refusal, and no `effect_started` for the call. A crash can't
leave a denied call open, because there is nothing to reconcile.

## Recorded, and never run again

A decision is recorded as `hook_decided`. Replay and resume read it back and
never run the hook again, so replaying a session doesn't send a second
notification or repeat a second audit.

A crash while a hook runs is different. The decision never reached the log,
so the invocation is open, and the next process runs the hook again. It
gives the hook the same **invocation ID**, which is the ID of the effect, so
a hook with side effects can tell it has fired before and deduplicate. In Go
it is `InvocationID` on the hook's input. A `hooks.json` command reads it as
`invocation_id` in the JSON on its standard input.

Sessions record gate hooks by name, so a Go host that resumes a session
registers the same hooks, named with `hook.WithName`: an invocation of one
it didn't register fails its gate closed. A `hooks.json` hook is named from
a hash of its definition, so editing it does the same to an unfinished
invocation.

## Timeouts and failures

What a failure means depends on where the hook came from.

A **Go gate** fails closed. It has 30 seconds unless it sets
`hook.WithTimeout`. A hook that times out, returns an error, panics, or isn't
registered when the session resumes is recorded as such, and the gate acts
as it would for a refusal: `PreToolUse` denies, and `UserPromptSubmit` and
`PreModelSwitch` block. The other gates ignore the failed hook, so a
compaction is skipped only by an explicit block.

A **`hooks.json` hook** gets 60 seconds unless it sets `timeout`, in seconds.
zelk adds five seconds to that for the callback's own deadline, so the
command runner can kill the whole process group first. A timeout, a command
that can't start, an exit code other than 0 or 2, too much output, or JSON
zelk can't honor is a **non-blocking error**: you are shown `PreToolUse hook
failed: ...`, and the call goes on, still through the permission rules. Exit
code 2 is how a script refuses, with its standard error as the reason. A
missing script exits 127, which is a failure and not a refusal.

A hook that must not let an action through when it breaks sets
`"onFailure": "block"`, and then a failure does what exit 2 does. It has no
effect on `Stop` and `SubagentStop`, where a continuation can't repair a
hook that won't run.

## Where hooks are configured

In the zelk command, hooks are commands (or URLs to post to) in
`~/.config/zelk/hooks.json` and, once you trust the exact file, a project's
`.zelk/hooks.json`. A command reads the event as JSON on its standard input,
runs outside the sandbox with your environment, and applies in subagents too.
The [Hooks guide](/cli/hooks/) covers the format, matchers, exit codes and
trust.

In Go, you register hooks with
[`zelk.WithHooks`](/reference/go/zelk/#withhooks). Each event has a typed
constructor in the [`hook` package](/reference/go/hook/), and `WithName`,
`WithTimeout`, `WithAsync` and `WithChildren` (to run in subagents too) set
how it runs:

```go
agent, err := zelk.New(ctx, p,
	zelk.WithModel(m),
	zelk.WithPermissionMode(permission.ModeDefault),
	zelk.WithHooks(
		hook.PreToolUse(hook.Match("Bash"),
			func(ctx 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
			}, hook.WithName("no-apply")),
	))
```

## Hooks and permissions

A `PreToolUse` gate is the first step of every call's
[permission decision](/concepts/permissions/#the-decision), ahead of the
rules and the mode. What it answers carries on from there:

- A **deny** is final, in every mode, `bypass` included.
- An **allow** counts as an allow rule, at the step where those apply. It
  doesn't override a deny rule, plan mode or a protected path.
- An **ask** or **defer** reaches the step that sends a call to a person.
  In `auto` it never goes to [the reviewer](/concepts/reviewer/): a person
  decides, or the call is refused where none can be asked.

In `auto`, an allow from a hook means the reviewer isn't asked, as with an
allow rule, except for a write to a built-in protected path, which the
reviewer still judges.

Two other hooks sit beside this step. A `PermissionRequest` hook may answer
for the person when a call would ask: allow, deny, or nothing, which leaves
the normal flow. It runs in headless sessions too, since a hook may route
the question to a chat. A `PermissionDenied` hook adds a note for the model
to a refusal, such as when it may try again.

## Where to go deeper

- The [Hooks guide](/cli/hooks/) shows `hooks.json`: matchers, exit codes,
  HTTP hooks and how a project's hooks are trusted.
- [The hooks contract](/internals/hooks/) specifies every event's input and
  output, and how decisions combine.
- [Permissions](/concepts/permissions/) shows where hooks sit in each
  decision, and [Extending zelk](/concepts/extending/) where a hook sits
  beside tools, MCP servers and subagents.
- [Durability and recovery](/concepts/durability/) explains why a recorded
  decision is never run again, and
  [the durability contract](/internals/durability/#h1) gives the hook
  protocol.
