18 18
19<div style={{maxWidth: "500px", margin: "0 auto"}}>19<div style={{maxWidth: "500px", margin: "0 auto"}}>
20 <Frame>20 <Frame>
21 <img src="https://mintcdn.com/claude-code/lBsitdsGyD9caWJQ/images/hooks-lifecycle.svg?fit=max&auto=format&n=lBsitdsGyD9caWJQ&q=85&s=be3486ef2cf2563eb213b6cbbce93982" alt="Hook lifecycle diagram showing the sequence of hooks from SessionStart through the agentic loop (PreToolUse, PermissionRequest, PostToolUse, SubagentStart/Stop, TaskCompleted) to PostCompact and SessionEnd, with Elicitation and ElicitationResult nested inside MCP tool execution and WorktreeCreate, WorktreeRemove, Notification, ConfigChange, and InstructionsLoaded as standalone async events" width="520" height="1100" data-path="images/hooks-lifecycle.svg" />21 <img src="https://mintcdn.com/claude-code/WLZtXlltXc8aIoIM/images/hooks-lifecycle.svg?fit=max&auto=format&n=WLZtXlltXc8aIoIM&q=85&s=6a0bf67eeb570a96e36b564721fa2a93" alt="Hook lifecycle diagram showing the sequence of hooks from SessionStart through the agentic loop (PreToolUse, PermissionRequest, PostToolUse, SubagentStart/Stop, TaskCreated, TaskCompleted) to Stop or StopFailure, TeammateIdle, PreCompact, PostCompact, and SessionEnd, with Elicitation and ElicitationResult nested inside MCP tool execution, PermissionDenied as a side branch from PermissionRequest for auto-mode denials, and WorktreeCreate, WorktreeRemove, Notification, ConfigChange, InstructionsLoaded, CwdChanged, and FileChanged as standalone async events" width="520" height="1155" data-path="images/hooks-lifecycle.svg" />
22 </Frame>22 </Frame>
23</div>23</div>
24 24
25The table below summarizes when each event fires. The [Hook events](#hook-events) section documents the full input schema and decision control options for each one.25The table below summarizes when each event fires. The [Hook events](#hook-events) section documents the full input schema and decision control options for each one.
26 26
27| Event | When it fires |27| Event | When it fires |
28| :------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------- |28| :------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- |
29| `SessionStart` | When a session begins or resumes |29| `SessionStart` | When a session begins or resumes |
30| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |30| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |
31| `PreToolUse` | Before a tool call executes. Can block it |31| `PreToolUse` | Before a tool call executes. Can block it |
32| `PermissionRequest` | When a permission dialog appears |32| `PermissionRequest` | When a permission dialog appears |
33| `PermissionDenied` | When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call |
33| `PostToolUse` | After a tool call succeeds |34| `PostToolUse` | After a tool call succeeds |
34| `PostToolUseFailure` | After a tool call fails |35| `PostToolUseFailure` | After a tool call fails |
35| `Notification` | When Claude Code sends a notification |36| `Notification` | When Claude Code sends a notification |
36| `SubagentStart` | When a subagent is spawned |37| `SubagentStart` | When a subagent is spawned |
37| `SubagentStop` | When a subagent finishes |38| `SubagentStop` | When a subagent finishes |
39| `TaskCreated` | When a task is being created via `TaskCreate` |
40| `TaskCompleted` | When a task is being marked as completed |
38| `Stop` | When Claude finishes responding |41| `Stop` | When Claude finishes responding |
42| `StopFailure` | When the turn ends due to an API error. Output and exit code are ignored |
39| `TeammateIdle` | When an [agent team](/en/agent-teams) teammate is about to go idle |43| `TeammateIdle` | When an [agent team](/en/agent-teams) teammate is about to go idle |
40| `TaskCompleted` | When a task is being marked as completed |
41| `InstructionsLoaded` | When a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. Fires at session start and when files are lazily loaded during a session |44| `InstructionsLoaded` | When a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. Fires at session start and when files are lazily loaded during a session |
42| `ConfigChange` | When a configuration file changes during a session |45| `ConfigChange` | When a configuration file changes during a session |
46| `CwdChanged` | When the working directory changes, for example when Claude executes a `cd` command. Useful for reactive environment management with tools like direnv |
47| `FileChanged` | When a watched file changes on disk. The `matcher` field specifies which filenames to watch |
43| `WorktreeCreate` | When a worktree is being created via `--worktree` or `isolation: "worktree"`. Replaces default git behavior |48| `WorktreeCreate` | When a worktree is being created via `--worktree` or `isolation: "worktree"`. Replaces default git behavior |
44| `WorktreeRemove` | When a worktree is being removed, either at session exit or when a subagent finishes |49| `WorktreeRemove` | When a worktree is being removed, either at session exit or when a subagent finishes |
45| `PreCompact` | Before context compaction |50| `PreCompact` | Before context compaction |
50 55
51### How a hook resolves56### How a hook resolves
52 57
53To see how these pieces fit together, consider this `PreToolUse` hook that blocks destructive shell commands. The hook runs `block-rm.sh` before every Bash tool call:58To see how these pieces fit together, consider this `PreToolUse` hook that blocks destructive shell commands. The `matcher` narrows to Bash tool calls and the `if` condition narrows further to commands starting with `rm`, so `block-rm.sh` only spawns when both filters match:
54 59
55```json theme={null}60```json theme={null}
56{61{
61 "hooks": [66 "hooks": [
62 {67 {
63 "type": "command",68 "type": "command",
64 "command": ".claude/hooks/block-rm.sh"69 "if": "Bash(rm *)",
70 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-rm.sh"
65 }71 }
66 ]72 ]
67 }73 }
93Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here's what happens:99Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here's what happens:
94 100
95<Frame>101<Frame>
96 <img src="https://mintcdn.com/claude-code/c5r9_6tjPMzFdDDT/images/hook-resolution.svg?fit=max&auto=format&n=c5r9_6tjPMzFdDDT&q=85&s=ad667ee6d86ab2276aa48a4e73e220df" alt="Hook resolution flow: PreToolUse event fires, matcher checks for Bash match, hook handler runs, result returns to Claude Code" width="780" height="290" data-path="images/hook-resolution.svg" />102 <img src="https://mintcdn.com/claude-code/-tYw1BD_DEqfyyOZ/images/hook-resolution.svg?fit=max&auto=format&n=-tYw1BD_DEqfyyOZ&q=85&s=c73ebc1eeda2037570427d7af1e0a891" alt="Hook resolution flow: PreToolUse event fires, matcher checks for Bash match, if condition checks for Bash(rm *) match, hook handler runs, result returns to Claude Code" width="930" height="290" data-path="images/hook-resolution.svg" />
97</Frame>103</Frame>
98 104
99<Steps>105<Steps>
106 </Step>112 </Step>
107 113
108 <Step title="Matcher checks">114 <Step title="Matcher checks">
109 The matcher `"Bash"` matches the tool name, so `block-rm.sh` runs. If you omit the matcher or use `"*"`, the hook runs on every occurrence of the event. Hooks only skip when a matcher is defined and doesn't match.115 The matcher `"Bash"` matches the tool name, so this hook group activates. If you omit the matcher or use `"*"`, the group activates on every occurrence of the event.
116 </Step>
117
118 <Step title="If condition checks">
119 The `if` condition `"Bash(rm *)"` matches because the command starts with `rm`, so this handler spawns. If the command had been `npm test`, the `if` check would fail and `block-rm.sh` would never run, avoiding the process spawn overhead. The `if` field is optional; without it, every handler in the matched group runs.
110 </Step>120 </Step>
111 121
112 <Step title="Hook handler runs">122 <Step title="Hook handler runs">
113 The script extracts `"rm -rf /tmp/build"` from the input and finds `rm -rf`, so it prints a decision to stdout:123 The script inspects the full command and finds `rm -rf`, so it prints a decision to stdout:
114 124
115 ```json theme={null}125 ```json theme={null}
116 {126 {
122 }132 }
123 ```133 ```
124 134
125 If the command had been safe (like `npm test`), the script would hit `exit 0` instead, which tells Claude Code to allow the tool call with no further action.135 If the command had been a safer `rm` variant like `rm file.txt`, the script would hit `exit 0` instead, which tells Claude Code to allow the tool call with no further action.
126 </Step>136 </Step>
127 137
128 <Step title="Claude Code acts on the result">138 <Step title="Claude Code acts on the result">
166The `matcher` field is a regex string that filters when hooks fire. Use `"*"`, `""`, or omit `matcher` entirely to match all occurrences. Each event type matches on a different field:176The `matcher` field is a regex string that filters when hooks fire. Use `"*"`, `""`, or omit `matcher` entirely to match all occurrences. Each event type matches on a different field:
167 177
168| Event | What the matcher filters | Example matcher values |178| Event | What the matcher filters | Example matcher values |
169| :-------------------------------------------------------------------------------------------------------------------- | :------------------------ | :--------------------------------------------------------------------------------- |179| :------------------------------------------------------------------------------------------------------------- | :-------------------------------------- | :------------------------------------------------------------------------------------------------------------------------ |
170| `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |180| `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |
171| `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` |181| `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` |
172| `SessionEnd` | why the session ended | `clear`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other` |182| `SessionEnd` | why the session ended | `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other` |
173| `Notification` | notification type | `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog` |183| `Notification` | notification type | `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog` |
174| `SubagentStart` | agent type | `Bash`, `Explore`, `Plan`, or custom agent names |184| `SubagentStart` | agent type | `Bash`, `Explore`, `Plan`, or custom agent names |
175| `PreCompact`, `PostCompact` | what triggered compaction | `manual`, `auto` |185| `PreCompact`, `PostCompact` | what triggered compaction | `manual`, `auto` |
176| `SubagentStop` | agent type | same values as `SubagentStart` |186| `SubagentStop` | agent type | same values as `SubagentStart` |
177| `ConfigChange` | configuration source | `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills` |187| `ConfigChange` | configuration source | `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills` |
178| `UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `InstructionsLoaded` | no matcher support | always fires on every occurrence |188| `CwdChanged` | no matcher support | always fires on every directory change |
189| `FileChanged` | filename (basename of the changed file) | `.envrc`, `.env`, any filename you want to watch |
190| `StopFailure` | error type | `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, `unknown` |
191| `InstructionsLoaded` | load reason | `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact` |
192| `Elicitation` | MCP server name | your configured MCP server names |
193| `ElicitationResult` | MCP server name | same values as `Elicitation` |
194| `UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove` | no matcher support | always fires on every occurrence |
179 195
180The matcher is a regex, so `Edit|Write` matches either tool and `Notebook.*` matches any tool starting with Notebook. The matcher runs against a field from the [JSON input](#hook-input-and-output) that Claude Code sends to your hook on stdin. For tool events, that field is `tool_name`. Each [hook event](#hook-events) section lists the full set of matcher values and the input schema for that event.196The matcher is a regex, so `Edit|Write` matches either tool and `Notebook.*` matches any tool starting with Notebook. The matcher runs against a field from the [JSON input](#hook-input-and-output) that Claude Code sends to your hook on stdin. For tool events, that field is `tool_name`. Each [hook event](#hook-events) section lists the full set of matcher values and the input schema for that event.
181 197
199}215}
200```216```
201 217
202`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, and `InstructionsLoaded` don't support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored.218`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, and `CwdChanged` don't support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored.
219
220For tool events, you can filter more narrowly by setting the [`if` field](#common-fields) on individual hook handlers. `if` uses [permission rule syntax](/en/permissions) to match against the tool name and arguments together, so `"Bash(git *)"` runs only for `git` commands and `"Edit(*.ts)"` runs only for TypeScript files.
203 221
204#### Match MCP tools222#### Match MCP tools
205 223
206[MCP](/en/mcp) server tools appear as regular tools in tool events (`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`), so you can match them the same way you match any other tool name.224[MCP](/en/mcp) server tools appear as regular tools in tool events (`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied`), so you can match them the same way you match any other tool name.
207 225
208MCP tools follow the naming pattern `mcp__<server>__<tool>`, for example:226MCP tools follow the naming pattern `mcp__<server>__<tool>`, for example:
209 227
259These fields apply to all hook types:277These fields apply to all hook types:
260 278
261| Field | Required | Description |279| Field | Required | Description |
262| :-------------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------- |280| :-------------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
263| `type` | yes | `"command"`, `"http"`, `"prompt"`, or `"agent"` |281| `type` | yes | `"command"`, `"http"`, `"prompt"`, or `"agent"` |
282| `if` | no | Permission rule syntax to filter when this hook runs, such as `"Bash(git *)"` or `"Edit(*.ts)"`. The hook only spawns if the tool call matches the pattern. Only evaluated on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. On other events, a hook with `if` set never runs. Uses the same syntax as [permission rules](/en/permissions) |
264| `timeout` | no | Seconds before canceling. Defaults: 600 for command, 30 for prompt, 60 for agent |283| `timeout` | no | Seconds before canceling. Defaults: 600 for command, 30 for prompt, 60 for agent |
265| `statusMessage` | no | Custom spinner message displayed while the hook runs |284| `statusMessage` | no | Custom spinner message displayed while the hook runs |
266| `once` | no | If `true`, runs only once per session then is removed. Skills only, not agents. See [Hooks in skills and agents](#hooks-in-skills-and-agents) |285| `once` | no | If `true`, runs only once per session then is removed. Skills only, not agents. See [Hooks in skills and agents](#hooks-in-skills-and-agents) |
270In addition to the [common fields](#common-fields), command hooks accept these fields:289In addition to the [common fields](#common-fields), command hooks accept these fields:
271 290
272| Field | Required | Description |291| Field | Required | Description |
273| :-------- | :------- | :------------------------------------------------------------------------------------------------------------------ |292| :-------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
274| `command` | yes | Shell command to execute |293| `command` | yes | Shell command to execute |
275| `async` | no | If `true`, runs in the background without blocking. See [Run hooks in the background](#run-hooks-in-the-background) |294| `async` | no | If `true`, runs in the background without blocking. See [Run hooks in the background](#run-hooks-in-the-background) |
295| `shell` | no | Shell to use for this hook. Accepts `"bash"` (default) or `"powershell"`. Setting `"powershell"` runs the command via PowerShell on Windows. Does not require `CLAUDE_CODE_USE_POWERSHELL_TOOL` since hooks spawn PowerShell directly |
276 296
277#### HTTP hook fields297#### HTTP hook fields
278 298
440 460
441### Common input fields461### Common input fields
442 462
443All hook events receive these fields as JSON, in addition to event-specific fields documented in each [hook event](#hook-events) section. For command hooks, this JSON arrives via stdin. For HTTP hooks, it arrives as the POST request body.463Hook events receive these fields as JSON, in addition to event-specific fields documented in each [hook event](#hook-events) section. For command hooks, this JSON arrives via stdin. For HTTP hooks, it arrives as the POST request body.
444 464
445| Field | Description |465| Field | Description |
446| :---------------- | :----------------------------------------------------------------------------------------------------------------------------------------- |466| :---------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
447| `session_id` | Current session identifier |467| `session_id` | Current session identifier |
448| `transcript_path` | Path to conversation JSON |468| `transcript_path` | Path to conversation JSON |
449| `cwd` | Current working directory when the hook is invoked |469| `cwd` | Current working directory when the hook is invoked |
450| `permission_mode` | Current [permission mode](/en/permissions#permission-modes): `"default"`, `"plan"`, `"acceptEdits"`, `"dontAsk"`, or `"bypassPermissions"` |470| `permission_mode` | Current [permission mode](/en/permissions#permission-modes): `"default"`, `"plan"`, `"acceptEdits"`, `"auto"`, `"dontAsk"`, or `"bypassPermissions"`. Not all events receive this field: see each event's JSON example below to check |
451| `hook_event_name` | Name of the event that fired |471| `hook_event_name` | Name of the event that fired |
452 472
453When running with `--agent` or inside a subagent, two additional fields are included:473When running with `--agent` or inside a subagent, two additional fields are included:
505Exit code 2 is the way a hook signals "stop, don't do this." The effect depends on the event, because some events represent actions that can be blocked (like a tool call that hasn't happened yet) and others represent things that already happened or can't be prevented.525Exit code 2 is the way a hook signals "stop, don't do this." The effect depends on the event, because some events represent actions that can be blocked (like a tool call that hasn't happened yet) and others represent things that already happened or can't be prevented.
506 526
507| Hook event | Can block? | What happens on exit 2 |527| Hook event | Can block? | What happens on exit 2 |
508| :------------------- | :--------- | :---------------------------------------------------------------------------- |528| :------------------- | :--------- | :----------------------------------------------------------------------------------------------------------------------------------- |
509| `PreToolUse` | Yes | Blocks the tool call |529| `PreToolUse` | Yes | Blocks the tool call |
510| `PermissionRequest` | Yes | Denies the permission |530| `PermissionRequest` | Yes | Denies the permission |
511| `UserPromptSubmit` | Yes | Blocks prompt processing and erases the prompt |531| `UserPromptSubmit` | Yes | Blocks prompt processing and erases the prompt |
512| `Stop` | Yes | Prevents Claude from stopping, continues the conversation |532| `Stop` | Yes | Prevents Claude from stopping, continues the conversation |
513| `SubagentStop` | Yes | Prevents the subagent from stopping |533| `SubagentStop` | Yes | Prevents the subagent from stopping |
514| `TeammateIdle` | Yes | Prevents the teammate from going idle (teammate continues working) |534| `TeammateIdle` | Yes | Prevents the teammate from going idle (teammate continues working) |
535| `TaskCreated` | Yes | Rolls back the task creation |
515| `TaskCompleted` | Yes | Prevents the task from being marked as completed |536| `TaskCompleted` | Yes | Prevents the task from being marked as completed |
516| `ConfigChange` | Yes | Blocks the configuration change from taking effect (except `policy_settings`) |537| `ConfigChange` | Yes | Blocks the configuration change from taking effect (except `policy_settings`) |
538| `StopFailure` | No | Output and exit code are ignored |
517| `PostToolUse` | No | Shows stderr to Claude (tool already ran) |539| `PostToolUse` | No | Shows stderr to Claude (tool already ran) |
518| `PostToolUseFailure` | No | Shows stderr to Claude (tool already failed) |540| `PostToolUseFailure` | No | Shows stderr to Claude (tool already failed) |
541| `PermissionDenied` | No | Exit code and stderr are ignored (denial already occurred). Use JSON `hookSpecificOutput.retry: true` to tell the model it may retry |
519| `Notification` | No | Shows stderr to user only |542| `Notification` | No | Shows stderr to user only |
520| `SubagentStart` | No | Shows stderr to user only |543| `SubagentStart` | No | Shows stderr to user only |
521| `SessionStart` | No | Shows stderr to user only |544| `SessionStart` | No | Shows stderr to user only |
522| `SessionEnd` | No | Shows stderr to user only |545| `SessionEnd` | No | Shows stderr to user only |
546| `CwdChanged` | No | Shows stderr to user only |
547| `FileChanged` | No | Shows stderr to user only |
523| `PreCompact` | No | Shows stderr to user only |548| `PreCompact` | No | Shows stderr to user only |
524| `PostCompact` | No | Shows stderr to user only |549| `PostCompact` | No | Shows stderr to user only |
525| `Elicitation` | Yes | Denies the elicitation |550| `Elicitation` | Yes | Denies the elicitation |
550 575
551Your hook's stdout must contain only the JSON object. If your shell profile prints text on startup, it can interfere with JSON parsing. See [JSON validation failed](/en/hooks-guide#json-validation-failed) in the troubleshooting guide.576Your hook's stdout must contain only the JSON object. If your shell profile prints text on startup, it can interfere with JSON parsing. See [JSON validation failed](/en/hooks-guide#json-validation-failed) in the troubleshooting guide.
552 577
578Hook output injected into context (`additionalContext`, `systemMessage`, or plain stdout) is capped at 10,000 characters. Output that exceeds this limit is saved to a file and replaced with a preview and file path, the same way large tool results are handled.
579
553The JSON object supports three kinds of fields:580The JSON object supports three kinds of fields:
554 581
555* **Universal fields** like `continue` work across all events. These are listed in the table below.582* **Universal fields** like `continue` work across all events. These are listed in the table below.
574Not every event supports blocking or controlling behavior through JSON. The events that do each use a different set of fields to express that decision. Use this table as a quick reference before writing a hook:601Not every event supports blocking or controlling behavior through JSON. The events that do each use a different set of fields to express that decision. Use this table as a quick reference before writing a hook:
575 602
576| Events | Decision pattern | Key fields |603| Events | Decision pattern | Key fields |
577| :------------------------------------------------------------------------------------ | :----------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |604| :-------------------------------------------------------------------------------------------------------------------------- | :----------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
578| UserPromptSubmit, PostToolUse, PostToolUseFailure, Stop, SubagentStop, ConfigChange | Top-level `decision` | `decision: "block"`, `reason` |605| UserPromptSubmit, PostToolUse, PostToolUseFailure, Stop, SubagentStop, ConfigChange | Top-level `decision` | `decision: "block"`, `reason` |
579| TeammateIdle, TaskCompleted | Exit code or `continue: false` | Exit code 2 blocks the action with stderr feedback. JSON `{"continue": false, "stopReason": "..."}` also stops the teammate entirely, matching `Stop` hook behavior |606| TeammateIdle, TaskCreated, TaskCompleted | Exit code or `continue: false` | Exit code 2 blocks the action with stderr feedback. JSON `{"continue": false, "stopReason": "..."}` also stops the teammate entirely, matching `Stop` hook behavior |
580| PreToolUse | `hookSpecificOutput` | `permissionDecision` (allow/deny/ask), `permissionDecisionReason` |607| PreToolUse | `hookSpecificOutput` | `permissionDecision` (allow/deny/ask/defer), `permissionDecisionReason` |
581| PermissionRequest | `hookSpecificOutput` | `decision.behavior` (allow/deny) |608| PermissionRequest | `hookSpecificOutput` | `decision.behavior` (allow/deny) |
582| WorktreeCreate | stdout path | Hook prints absolute path to created worktree. Non-zero exit fails creation |609| PermissionDenied | `hookSpecificOutput` | `retry: true` tells the model it may retry the denied tool call |
610| WorktreeCreate | path return | Command hook prints path on stdout; HTTP hook returns `hookSpecificOutput.worktreePath`. Hook failure or missing path fails creation |
583| Elicitation | `hookSpecificOutput` | `action` (accept/decline/cancel), `content` (form field values for accept) |611| Elicitation | `hookSpecificOutput` | `action` (accept/decline/cancel), `content` (form field values for accept) |
584| ElicitationResult | `hookSpecificOutput` | `action` (accept/decline/cancel), `content` (form field values override) |612| ElicitationResult | `hookSpecificOutput` | `action` (accept/decline/cancel), `content` (form field values override) |
585| WorktreeRemove, Notification, SessionEnd, PreCompact, PostCompact, InstructionsLoaded | None | No decision control. Used for side effects like logging or cleanup |613| WorktreeRemove, Notification, SessionEnd, PreCompact, PostCompact, InstructionsLoaded, StopFailure, CwdChanged, FileChanged | None | No decision control. Used for side effects like logging or cleanup |
586 614
587Here are examples of each pattern in action:615Here are examples of each pattern in action:
588 616
661 "session_id": "abc123",689 "session_id": "abc123",
662 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",690 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
663 "cwd": "/Users/...",691 "cwd": "/Users/...",
664 "permission_mode": "default",
665 "hook_event_name": "SessionStart",692 "hook_event_name": "SessionStart",
666 "source": "startup",693 "source": "startup",
667 "model": "claude-sonnet-4-6"694 "model": "claude-sonnet-4-6"
725Any variables written to this file will be available in all subsequent Bash commands that Claude Code executes during the session.752Any variables written to this file will be available in all subsequent Bash commands that Claude Code executes during the session.
726 753
727<Note>754<Note>
728 `CLAUDE_ENV_FILE` is available for SessionStart hooks. Other hook types do not have access to this variable.755 `CLAUDE_ENV_FILE` is available for SessionStart, [CwdChanged](#cwdchanged), and [FileChanged](#filechanged) hooks. Other hook types do not have access to this variable.
729</Note>756</Note>
730 757
731### InstructionsLoaded758### InstructionsLoaded
732 759
733Fires when a `CLAUDE.md` or `.claude/rules/*.md` file is loaded into context. This event fires at session start for eagerly-loaded files and again later when files are lazily loaded, for example when Claude accesses a subdirectory that contains a nested `CLAUDE.md` or when conditional rules with `paths:` frontmatter match. The hook does not support blocking or decision control. It runs asynchronously for observability purposes.760Fires when a `CLAUDE.md` or `.claude/rules/*.md` file is loaded into context. This event fires at session start for eagerly-loaded files and again later when files are lazily loaded, for example when Claude accesses a subdirectory that contains a nested `CLAUDE.md` or when conditional rules with `paths:` frontmatter match. The hook does not support blocking or decision control. It runs asynchronously for observability purposes.
734 761
735InstructionsLoaded does not support matchers and fires on every load occurrence.762The matcher runs against `load_reason`. For example, use `"matcher": "session_start"` to fire only for files loaded at session start, or `"matcher": "path_glob_match|nested_traversal"` to fire only for lazy loads.
736 763
737#### InstructionsLoaded input764#### InstructionsLoaded input
738 765
752 "session_id": "abc123",779 "session_id": "abc123",
753 "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",780 "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
754 "cwd": "/Users/my-project",781 "cwd": "/Users/my-project",
755 "permission_mode": "default",
756 "hook_event_name": "InstructionsLoaded",782 "hook_event_name": "InstructionsLoaded",
757 "file_path": "/Users/my-project/CLAUDE.md",783 "file_path": "/Users/my-project/CLAUDE.md",
758 "memory_type": "Project",784 "memory_type": "Project",
822 848
823### PreToolUse849### PreToolUse
824 850
825Runs after Claude creates tool parameters and before processing the tool call. Matches on tool name: `Bash`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `Agent`, `WebFetch`, `WebSearch`, and any [MCP tool names](#match-mcp-tools).851Runs after Claude creates tool parameters and before processing the tool call. Matches on tool name: `Bash`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `Agent`, `WebFetch`, `WebSearch`, `AskUserQuestion`, `ExitPlanMode`, and any [MCP tool names](#match-mcp-tools).
826 852
827Use [PreToolUse decision control](#pretooluse-decision-control) to allow, deny, or ask for permission to use the tool.853Use [PreToolUse decision control](#pretooluse-decision-control) to allow, deny, ask, or defer the tool call.
828 854
829#### PreToolUse input855#### PreToolUse input
830 856
923| `subagent_type` | string | `"Explore"` | Type of specialized agent to use |949| `subagent_type` | string | `"Explore"` | Type of specialized agent to use |
924| `model` | string | `"sonnet"` | Optional model alias to override the default |950| `model` | string | `"sonnet"` | Optional model alias to override the default |
925 951
952##### AskUserQuestion
953
954Asks the user one to four multiple-choice questions.
955
956| Field | Type | Example | Description |
957| :---------- | :----- | :----------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
958| `questions` | array | `[{"question": "Which framework?", "header": "Framework", "options": [{"label": "React"}], "multiSelect": false}]` | Questions to present, each with a `question` string, short `header`, `options` array, and optional `multiSelect` flag |
959| `answers` | object | `{"Which framework?": "React"}` | Optional. Maps question text to the selected option label. Multi-select answers join labels with commas. Claude does not set this field; supply it via `updatedInput` to answer programmatically |
960
926#### PreToolUse decision control961#### PreToolUse decision control
927 962
928`PreToolUse` hooks can control whether a tool call proceeds. Unlike other hooks that use a top-level `decision` field, PreToolUse returns its decision inside a `hookSpecificOutput` object. This gives it richer control: three outcomes (allow, deny, or ask) plus the ability to modify tool input before execution.963`PreToolUse` hooks can control whether a tool call proceeds. Unlike other hooks that use a top-level `decision` field, PreToolUse returns its decision inside a `hookSpecificOutput` object. This gives it richer control: four outcomes (allow, deny, ask, or defer) plus the ability to modify tool input before execution.
929 964
930| Field | Description |965| Field | Description |
931| :------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |966| :------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
932| `permissionDecision` | `"allow"` skips the permission prompt. `"deny"` prevents the tool call. `"ask"` prompts the user to confirm. [Deny and ask rules](/en/permissions#manage-permissions) still apply when a hook returns `"allow"` |967| `permissionDecision` | `"allow"` skips the permission prompt. `"deny"` prevents the tool call. `"ask"` prompts the user to confirm. `"defer"` exits gracefully so the tool can be resumed later. [Deny and ask rules](/en/permissions#manage-permissions) still apply when a hook returns `"allow"` |
933| `permissionDecisionReason` | For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude |968| `permissionDecisionReason` | For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude. For `"defer"`, ignored |
934| `updatedInput` | Modifies the tool's input parameters before execution. Combine with `"allow"` to auto-approve, or `"ask"` to show the modified input to the user |969| `updatedInput` | Modifies the tool's input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones. Combine with `"allow"` to auto-approve, or `"ask"` to show the modified input to the user. For `"defer"`, ignored |
935| `additionalContext` | String added to Claude's context before the tool executes |970| `additionalContext` | String added to Claude's context before the tool executes. For `"defer"`, ignored |
971
972When multiple PreToolUse hooks return different decisions, precedence is `deny` > `defer` > `ask` > `allow`.
936 973
937When a hook returns `"ask"`, the permission prompt displayed to the user includes a label identifying where the hook came from: for example, `[User]`, `[Project]`, `[Plugin]`, or `[Local]`. This helps users understand which configuration source is requesting confirmation.974When a hook returns `"ask"`, the permission prompt displayed to the user includes a label identifying where the hook came from: for example, `[User]`, `[Project]`, `[Plugin]`, or `[Local]`. This helps users understand which configuration source is requesting confirmation.
938 975
950}987}
951```988```
952 989
990`AskUserQuestion` and `ExitPlanMode` require user interaction and normally block in [non-interactive mode](/en/headless) with the `-p` flag. Returning `permissionDecision: "allow"` together with `updatedInput` satisfies that requirement: the hook reads the tool's input from stdin, collects the answer through your own UI, and returns it in `updatedInput` so the tool runs without prompting. Returning `"allow"` alone is not sufficient for these tools. For `AskUserQuestion`, echo back the original `questions` array and add an [`answers`](#askuserquestion) object mapping each question's text to the chosen answer.
991
953<Note>992<Note>
954 PreToolUse previously used top-level `decision` and `reason` fields, but these are deprecated for this event. Use `hookSpecificOutput.permissionDecision` and `hookSpecificOutput.permissionDecisionReason` instead. The deprecated values `"approve"` and `"block"` map to `"allow"` and `"deny"` respectively. Other events like PostToolUse and Stop continue to use top-level `decision` and `reason` as their current format.993 PreToolUse previously used top-level `decision` and `reason` fields, but these are deprecated for this event. Use `hookSpecificOutput.permissionDecision` and `hookSpecificOutput.permissionDecisionReason` instead. The deprecated values `"approve"` and `"block"` map to `"allow"` and `"deny"` respectively. Other events like PostToolUse and Stop continue to use top-level `decision` and `reason` as their current format.
955</Note>994</Note>
956 995
996#### Defer a tool call for later
997
998`"defer"` is for integrations that run `claude -p` as a subprocess and read its JSON output, such as an Agent SDK app or a custom UI built on top of Claude Code. It lets that calling process pause Claude at a tool call, collect input through its own interface, and resume where it left off. Claude Code honors this value only in [non-interactive mode](/en/headless) with the `-p` flag. In interactive sessions it logs a warning and ignores the hook result.
999
1000<Note>
1001 The `defer` value requires Claude Code v2.1.89 or later. Earlier versions do not recognize it and the tool proceeds through the normal permission flow.
1002</Note>
1003
1004The `AskUserQuestion` tool is the typical case: Claude wants to ask the user something, but there is no terminal to answer in. The round trip works like this:
1005
10061. Claude calls `AskUserQuestion`. The `PreToolUse` hook fires.
10072. The hook returns `permissionDecision: "defer"`. The tool does not execute. The process exits with `stop_reason: "tool_deferred"` and the pending tool call preserved in the transcript.
10083. The calling process reads `deferred_tool_use` from the SDK result, surfaces the question in its own UI, and waits for an answer.
10094. The calling process runs `claude -p --resume <session-id>`. The same tool call fires `PreToolUse` again.
10105. The hook returns `permissionDecision: "allow"` with the answer in `updatedInput`. The tool executes and Claude continues.
1011
1012The `deferred_tool_use` field carries the tool's `id`, `name`, and `input`. The `input` is the parameters Claude generated for the tool call, captured before execution:
1013
1014```json theme={null}
1015{
1016 "type": "result",
1017 "subtype": "success",
1018 "stop_reason": "tool_deferred",
1019 "session_id": "abc123",
1020 "deferred_tool_use": {
1021 "id": "toolu_01abc",
1022 "name": "AskUserQuestion",
1023 "input": { "questions": [{ "question": "Which framework?", "header": "Framework", "options": [{"label": "React"}, {"label": "Vue"}], "multiSelect": false }] }
1024 }
1025}
1026```
1027
1028There is no timeout or retry limit. The session remains on disk until you resume it. If the answer is not ready when you resume, the hook can return `"defer"` again and the process exits the same way. The calling process controls when to break the loop by eventually returning `"allow"` or `"deny"` from the hook.
1029
1030`"defer"` only works when Claude makes a single tool call in the turn. If Claude makes several tool calls at once, `"defer"` is ignored with a warning and the tool proceeds through the normal permission flow. The constraint exists because resume can only re-run one tool: there is no way to defer one call from a batch without leaving the others unresolved.
1031
1032If the deferred tool is no longer available when you resume, the process exits with `stop_reason: "tool_deferred_unavailable"` and `is_error: true` before the hook fires. This happens when an MCP server that provided the tool is not connected for the resumed session. The `deferred_tool_use` payload is still included so you can identify which tool went missing.
1033
1034<Warning>
1035 `--resume` does not restore the permission mode from the prior session. Pass the same `--permission-mode` flag on resume that was active when the tool was deferred. Claude Code logs a warning if the modes differ.
1036</Warning>
1037
957### PermissionRequest1038### PermissionRequest
958 1039
959Runs when the user is shown a permission dialog.1040Runs when the user is shown a permission dialog.
995| Field | Description |1076| Field | Description |
996| :------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |1077| :------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
997| `behavior` | `"allow"` grants the permission, `"deny"` denies it |1078| `behavior` | `"allow"` grants the permission, `"deny"` denies it |
998| `updatedInput` | For `"allow"` only: modifies the tool's input parameters before execution |1079| `updatedInput` | For `"allow"` only: modifies the tool's input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones |
999| `updatedPermissions` | For `"allow"` only: array of [permission update entries](#permission-update-entries) to apply, such as adding an allow rule or changing the session permission mode |1080| `updatedPermissions` | For `"allow"` only: array of [permission update entries](#permission-update-entries) to apply, such as adding an allow rule or changing the session permission mode |
1000| `message` | For `"deny"` only: tells Claude why the permission was denied |1081| `message` | For `"deny"` only: tells Claude why the permission was denied |
1001| `interrupt` | For `"deny"` only: if `true`, stops Claude |1082| `interrupt` | For `"deny"` only: if `true`, stops Claude |
1140}1221}
1141```1222```
1142 1223
1224### PermissionDenied
1225
1226Runs when the [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) classifier denies a tool call. This hook only fires in auto mode: it does not run when you manually deny a permission dialog, when a `PreToolUse` hook blocks a call, or when a `deny` rule matches. Use it to log classifier denials, adjust configuration, or tell the model it may retry the tool call.
1227
1228Matches on tool name, same values as PreToolUse.
1229
1230#### PermissionDenied input
1231
1232In addition to the [common input fields](#common-input-fields), PermissionDenied hooks receive `tool_name`, `tool_input`, `tool_use_id`, and `reason`.
1233
1234```json theme={null}
1235{
1236 "session_id": "abc123",
1237 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1238 "cwd": "/Users/...",
1239 "permission_mode": "auto",
1240 "hook_event_name": "PermissionDenied",
1241 "tool_name": "Bash",
1242 "tool_input": {
1243 "command": "rm -rf /tmp/build",
1244 "description": "Clean build directory"
1245 },
1246 "tool_use_id": "toolu_01ABC123...",
1247 "reason": "Auto mode denied: command targets a path outside the project"
1248}
1249```
1250
1251| Field | Description |
1252| :------- | :------------------------------------------------------------ |
1253| `reason` | The classifier's explanation for why the tool call was denied |
1254
1255#### PermissionDenied decision control
1256
1257PermissionDenied hooks can tell the model it may retry the denied tool call. Return a JSON object with `hookSpecificOutput.retry` set to `true`:
1258
1259```json theme={null}
1260{
1261 "hookSpecificOutput": {
1262 "hookEventName": "PermissionDenied",
1263 "retry": true
1264 }
1265}
1266```
1267
1268When `retry` is `true`, Claude Code adds a message to the conversation telling the model it may retry the tool call. The denial itself is not reversed. If your hook does not return JSON, or returns `retry: false`, the denial stands and the model receives the original rejection message.
1269
1143### Notification1270### Notification
1144 1271
1145Runs when Claude Code sends notifications. Matches on notification type: `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`. Omit the matcher to run hooks for all notification types.1272Runs when Claude Code sends notifications. Matches on notification type: `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`. Omit the matcher to run hooks for all notification types.
1182 "session_id": "abc123",1309 "session_id": "abc123",
1183 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1310 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1184 "cwd": "/Users/...",1311 "cwd": "/Users/...",
1185 "permission_mode": "default",
1186 "hook_event_name": "Notification",1312 "hook_event_name": "Notification",
1187 "message": "Claude needs your permission to use Bash",1313 "message": "Claude needs your permission to use Bash",
1188 "title": "Permission needed",1314 "title": "Permission needed",
1209 "session_id": "abc123",1335 "session_id": "abc123",
1210 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1336 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1211 "cwd": "/Users/...",1337 "cwd": "/Users/...",
1212 "permission_mode": "default",
1213 "hook_event_name": "SubagentStart",1338 "hook_event_name": "SubagentStart",
1214 "agent_id": "agent-abc123",1339 "agent_id": "agent-abc123",
1215 "agent_type": "Explore"1340 "agent_type": "Explore"
1256 1381
1257SubagentStop hooks use the same decision control format as [Stop hooks](#stop-decision-control).1382SubagentStop hooks use the same decision control format as [Stop hooks](#stop-decision-control).
1258 1383
1259### Stop1384### TaskCreated
1260
1261Runs when the main Claude Code agent has finished responding. Does not run if
1262the stoppage occurred due to a user interrupt.
1263
1264#### Stop input
1265
1266In addition to the [common input fields](#common-input-fields), Stop hooks receive `stop_hook_active` and `last_assistant_message`. The `stop_hook_active` field is `true` when Claude Code is already continuing as a result of a stop hook. Check this value or process the transcript to prevent Claude Code from running indefinitely. The `last_assistant_message` field contains the text content of Claude's final response, so hooks can access it without parsing the transcript file.
1267 1385
1268```json theme={null}1386Runs when a task is being created via the `TaskCreate` tool. Use this to enforce naming conventions, require task descriptions, or prevent certain tasks from being created.
1269{
1270 "session_id": "abc123",
1271 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1272 "cwd": "/Users/...",
1273 "permission_mode": "default",
1274 "hook_event_name": "Stop",
1275 "stop_hook_active": true,
1276 "last_assistant_message": "I've completed the refactoring. Here's a summary..."
1277}
1278```
1279 1387
1280#### Stop decision control1388When a `TaskCreated` hook exits with code 2, the task is not created and the stderr message is fed back to the model as feedback. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TaskCreated hooks do not support matchers and fire on every occurrence.
1281 1389
1282`Stop` and `SubagentStop` hooks can control whether Claude continues. In addition to the [JSON output fields](#json-output) available to all hooks, your hook script can return these event-specific fields:1390#### TaskCreated input
1283 1391
1284| Field | Description |1392In addition to the [common input fields](#common-input-fields), TaskCreated hooks receive `task_id`, `task_subject`, and optionally `task_description`, `teammate_name`, and `team_name`.
1285| :--------- | :------------------------------------------------------------------------- |
1286| `decision` | `"block"` prevents Claude from stopping. Omit to allow Claude to stop |
1287| `reason` | Required when `decision` is `"block"`. Tells Claude why it should continue |
1288
1289```json theme={null}
1290{
1291 "decision": "block",
1292 "reason": "Must be provided when Claude is blocked from stopping"
1293}
1294```
1295
1296### TeammateIdle
1297
1298Runs when an [agent team](/en/agent-teams) teammate is about to go idle after finishing its turn. Use this to enforce quality gates before a teammate stops working, such as requiring passing lint checks or verifying that output files exist.
1299
1300When a `TeammateIdle` hook exits with code 2, the teammate receives the stderr message as feedback and continues working instead of going idle. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TeammateIdle hooks do not support matchers and fire on every occurrence.
1301
1302#### TeammateIdle input
1303
1304In addition to the [common input fields](#common-input-fields), TeammateIdle hooks receive `teammate_name` and `team_name`.
1305 1393
1306```json theme={null}1394```json theme={null}
1307{1395{
1309 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1397 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1310 "cwd": "/Users/...",1398 "cwd": "/Users/...",
1311 "permission_mode": "default",1399 "permission_mode": "default",
1312 "hook_event_name": "TeammateIdle",1400 "hook_event_name": "TaskCreated",
1313 "teammate_name": "researcher",1401 "task_id": "task-001",
1402 "task_subject": "Implement user authentication",
1403 "task_description": "Add login and signup endpoints",
1404 "teammate_name": "implementer",
1314 "team_name": "my-project"1405 "team_name": "my-project"
1315}1406}
1316```1407```
1317 1408
1318| Field | Description |1409| Field | Description |
1319| :-------------- | :-------------------------------------------- |1410| :----------------- | :---------------------------------------------------- |
1320| `teammate_name` | Name of the teammate that is about to go idle |1411| `task_id` | Identifier of the task being created |
1321| `team_name` | Name of the team |1412| `task_subject` | Title of the task |
1413| `task_description` | Detailed description of the task. May be absent |
1414| `teammate_name` | Name of the teammate creating the task. May be absent |
1415| `team_name` | Name of the team. May be absent |
1322 1416
1323#### TeammateIdle decision control1417#### TaskCreated decision control
1324 1418
1325TeammateIdle hooks support two ways to control teammate behavior:1419TaskCreated hooks support two ways to control task creation:
1326 1420
1327* **Exit code 2**: the teammate receives the stderr message as feedback and continues working instead of going idle.1421* **Exit code 2**: the task is not created and the stderr message is fed back to the model as feedback.
1328* **JSON `{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.1422* **JSON `{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.
1329 1423
1330This example checks that a build artifact exists before allowing a teammate to go idle:1424This example blocks tasks whose subjects don't follow the required format:
1331 1425
1332```bash theme={null}1426```bash theme={null}
1333#!/bin/bash1427#!/bin/bash
1428INPUT=$(cat)
1429TASK_SUBJECT=$(echo "$INPUT" | jq -r '.task_subject')
1334 1430
1335if [ ! -f "./dist/output.js" ]; then1431if [[ ! "$TASK_SUBJECT" =~ ^\[TICKET-[0-9]+\] ]]; then
1336 echo "Build artifact missing. Run the build before stopping." >&21432 echo "Task subject must start with a ticket number, e.g. '[TICKET-123] Add feature'" >&2
1337 exit 21433 exit 2
1338fi1434fi
1339 1435
1396exit 01492exit 0
1397```1493```
1398 1494
1495### Stop
1496
1497Runs when the main Claude Code agent has finished responding. Does not run if
1498the stoppage occurred due to a user interrupt. API errors fire
1499[StopFailure](#stopfailure) instead.
1500
1501#### Stop input
1502
1503In addition to the [common input fields](#common-input-fields), Stop hooks receive `stop_hook_active` and `last_assistant_message`. The `stop_hook_active` field is `true` when Claude Code is already continuing as a result of a stop hook. Check this value or process the transcript to prevent Claude Code from running indefinitely. The `last_assistant_message` field contains the text content of Claude's final response, so hooks can access it without parsing the transcript file.
1504
1505```json theme={null}
1506{
1507 "session_id": "abc123",
1508 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1509 "cwd": "/Users/...",
1510 "permission_mode": "default",
1511 "hook_event_name": "Stop",
1512 "stop_hook_active": true,
1513 "last_assistant_message": "I've completed the refactoring. Here's a summary..."
1514}
1515```
1516
1517#### Stop decision control
1518
1519`Stop` and `SubagentStop` hooks can control whether Claude continues. In addition to the [JSON output fields](#json-output) available to all hooks, your hook script can return these event-specific fields:
1520
1521| Field | Description |
1522| :--------- | :------------------------------------------------------------------------- |
1523| `decision` | `"block"` prevents Claude from stopping. Omit to allow Claude to stop |
1524| `reason` | Required when `decision` is `"block"`. Tells Claude why it should continue |
1525
1526```json theme={null}
1527{
1528 "decision": "block",
1529 "reason": "Must be provided when Claude is blocked from stopping"
1530}
1531```
1532
1533### StopFailure
1534
1535Runs instead of [Stop](#stop) when the turn ends due to an API error. Output and exit code are ignored. Use this to log failures, send alerts, or take recovery actions when Claude cannot complete a response due to rate limits, authentication problems, or other API errors.
1536
1537#### StopFailure input
1538
1539In addition to the [common input fields](#common-input-fields), StopFailure hooks receive `error`, optional `error_details`, and optional `last_assistant_message`. The `error` field identifies the error type and is used for matcher filtering.
1540
1541| Field | Description |
1542| :----------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1543| `error` | Error type: `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, or `unknown` |
1544| `error_details` | Additional details about the error, when available |
1545| `last_assistant_message` | The rendered error text shown in the conversation. Unlike `Stop` and `SubagentStop`, where this field holds Claude's conversational output, for `StopFailure` it contains the API error string itself, such as `"API Error: Rate limit reached"` |
1546
1547```json theme={null}
1548{
1549 "session_id": "abc123",
1550 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1551 "cwd": "/Users/...",
1552 "hook_event_name": "StopFailure",
1553 "error": "rate_limit",
1554 "error_details": "429 Too Many Requests",
1555 "last_assistant_message": "API Error: Rate limit reached"
1556}
1557```
1558
1559StopFailure hooks have no decision control. They run for notification and logging purposes only.
1560
1561### TeammateIdle
1562
1563Runs when an [agent team](/en/agent-teams) teammate is about to go idle after finishing its turn. Use this to enforce quality gates before a teammate stops working, such as requiring passing lint checks or verifying that output files exist.
1564
1565When a `TeammateIdle` hook exits with code 2, the teammate receives the stderr message as feedback and continues working instead of going idle. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TeammateIdle hooks do not support matchers and fire on every occurrence.
1566
1567#### TeammateIdle input
1568
1569In addition to the [common input fields](#common-input-fields), TeammateIdle hooks receive `teammate_name` and `team_name`.
1570
1571```json theme={null}
1572{
1573 "session_id": "abc123",
1574 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1575 "cwd": "/Users/...",
1576 "permission_mode": "default",
1577 "hook_event_name": "TeammateIdle",
1578 "teammate_name": "researcher",
1579 "team_name": "my-project"
1580}
1581```
1582
1583| Field | Description |
1584| :-------------- | :-------------------------------------------- |
1585| `teammate_name` | Name of the teammate that is about to go idle |
1586| `team_name` | Name of the team |
1587
1588#### TeammateIdle decision control
1589
1590TeammateIdle hooks support two ways to control teammate behavior:
1591
1592* **Exit code 2**: the teammate receives the stderr message as feedback and continues working instead of going idle.
1593* **JSON `{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.
1594
1595This example checks that a build artifact exists before allowing a teammate to go idle:
1596
1597```bash theme={null}
1598#!/bin/bash
1599
1600if [ ! -f "./dist/output.js" ]; then
1601 echo "Build artifact missing. Run the build before stopping." >&2
1602 exit 2
1603fi
1604
1605exit 0
1606```
1607
1399### ConfigChange1608### ConfigChange
1400 1609
1401Runs when a configuration file changes during a session. Use this to audit settings changes, enforce security policies, or block unauthorized modifications to configuration files.1610Runs when a configuration file changes during a session. Use this to audit settings changes, enforce security policies, or block unauthorized modifications to configuration files.
1440 "session_id": "abc123",1649 "session_id": "abc123",
1441 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1650 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1442 "cwd": "/Users/...",1651 "cwd": "/Users/...",
1443 "permission_mode": "default",
1444 "hook_event_name": "ConfigChange",1652 "hook_event_name": "ConfigChange",
1445 "source": "project_settings",1653 "source": "project_settings",
1446 "file_path": "/Users/.../my-project/.claude/settings.json"1654 "file_path": "/Users/.../my-project/.claude/settings.json"
1465 1673
1466`policy_settings` changes cannot be blocked. Hooks still fire for `policy_settings` sources, so you can use them for audit logging, but any blocking decision is ignored. This ensures enterprise-managed settings always take effect.1674`policy_settings` changes cannot be blocked. Hooks still fire for `policy_settings` sources, so you can use them for audit logging, but any blocking decision is ignored. This ensures enterprise-managed settings always take effect.
1467 1675
1676### CwdChanged
1677
1678Runs when the working directory changes during a session, for example when Claude executes a `cd` command. Use this to react to directory changes: reload environment variables, activate project-specific toolchains, or run setup scripts automatically. Pairs with [FileChanged](#filechanged) for tools like [direnv](https://direnv.net/) that manage per-directory environment.
1679
1680CwdChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in [SessionStart hooks](#persist-environment-variables). Only `type: "command"` hooks are supported.
1681
1682CwdChanged does not support matchers and fires on every directory change.
1683
1684#### CwdChanged input
1685
1686In addition to the [common input fields](#common-input-fields), CwdChanged hooks receive `old_cwd` and `new_cwd`.
1687
1688```json theme={null}
1689{
1690 "session_id": "abc123",
1691 "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
1692 "cwd": "/Users/my-project/src",
1693 "hook_event_name": "CwdChanged",
1694 "old_cwd": "/Users/my-project",
1695 "new_cwd": "/Users/my-project/src"
1696}
1697```
1698
1699#### CwdChanged output
1700
1701In addition to the [JSON output fields](#json-output) available to all hooks, CwdChanged hooks can return `watchPaths` to dynamically set which file paths [FileChanged](#filechanged) watches:
1702
1703| Field | Description |
1704| :----------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1705| `watchPaths` | Array of absolute paths. Replaces the current dynamic watch list (paths from your `matcher` configuration are always watched). Returning an empty array clears the dynamic list, which is typical when entering a new directory |
1706
1707CwdChanged hooks have no decision control. They cannot block the directory change.
1708
1709### FileChanged
1710
1711Runs when a watched file changes on disk. The `matcher` field in your hook configuration controls which filenames to watch: it is a pipe-separated list of basenames (filenames without directory paths, for example `".envrc|.env"`). The same `matcher` value is also used to filter which hooks run when a file changes, matching against the basename of the changed file. Useful for reloading environment variables when project configuration files are modified.
1712
1713FileChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in [SessionStart hooks](#persist-environment-variables). Only `type: "command"` hooks are supported.
1714
1715#### FileChanged input
1716
1717In addition to the [common input fields](#common-input-fields), FileChanged hooks receive `file_path` and `event`.
1718
1719| Field | Description |
1720| :---------- | :---------------------------------------------------------------------------------------------- |
1721| `file_path` | Absolute path to the file that changed |
1722| `event` | What happened: `"change"` (file modified), `"add"` (file created), or `"unlink"` (file deleted) |
1723
1724```json theme={null}
1725{
1726 "session_id": "abc123",
1727 "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",
1728 "cwd": "/Users/my-project",
1729 "hook_event_name": "FileChanged",
1730 "file_path": "/Users/my-project/.envrc",
1731 "event": "change"
1732}
1733```
1734
1735#### FileChanged output
1736
1737In addition to the [JSON output fields](#json-output) available to all hooks, FileChanged hooks can return `watchPaths` to dynamically update which file paths are watched:
1738
1739| Field | Description |
1740| :----------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1741| `watchPaths` | Array of absolute paths. Replaces the current dynamic watch list (paths from your `matcher` configuration are always watched). Use this when your hook script discovers additional files to watch based on the changed file |
1742
1743FileChanged hooks have no decision control. They cannot block the file change from occurring.
1744
1468### WorktreeCreate1745### WorktreeCreate
1469 1746
1470When you run `claude --worktree` or a [subagent uses `isolation: "worktree"`](/en/sub-agents#choose-the-subagent-scope), Claude Code creates an isolated working copy using `git worktree`. If you configure a WorktreeCreate hook, it replaces the default git behavior, letting you use a different version control system like SVN, Perforce, or Mercurial.1747When you run `claude --worktree` or a [subagent uses `isolation: "worktree"`](/en/sub-agents#choose-the-subagent-scope), Claude Code creates an isolated working copy using `git worktree`. If you configure a WorktreeCreate hook, it replaces the default git behavior, letting you use a different version control system like SVN, Perforce, or Mercurial.
1471 1748
1472The hook must print the absolute path to the created worktree directory on stdout. Claude Code uses this path as the working directory for the isolated session.1749Because the hook replaces the default behavior entirely, [`.worktreeinclude`](/en/common-workflows#copy-gitignored-files-to-worktrees) is not processed. If you need to copy local configuration files like `.env` into the new worktree, do it inside your hook script.
1750
1751The hook must return the absolute path to the created worktree directory. Claude Code uses this path as the working directory for the isolated session. Command hooks print it on stdout; HTTP hooks return it via `hookSpecificOutput.worktreePath`.
1473 1752
1474This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:1753This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
1475 1754
1508 1787
1509#### WorktreeCreate output1788#### WorktreeCreate output
1510 1789
1511The hook must print the absolute path to the created worktree directory on stdout. If the hook fails or produces no output, worktree creation fails with an error.1790WorktreeCreate hooks do not use the standard allow/block decision model. Instead, the hook's success or failure determines the outcome. The hook must return the absolute path to the created worktree directory:
1791
1792* **Command hooks** (`type: "command"`): print the path on stdout.
1793* **HTTP hooks** (`type: "http"`): return `{ "hookSpecificOutput": { "hookEventName": "WorktreeCreate", "worktreePath": "/absolute/path" } }` in the response body.
1512 1794
1513WorktreeCreate hooks do not use the standard allow/block decision model. Instead, the hook's success or failure determines the outcome. Only `type: "command"` hooks are supported.1795If the hook fails or produces no path, worktree creation fails with an error.
1514 1796
1515### WorktreeRemove1797### WorktreeRemove
1516 1798
1517The cleanup counterpart to [WorktreeCreate](#worktreecreate). This hook fires when a worktree is being removed, either when you exit a `--worktree` session and choose to remove it, or when a subagent with `isolation: "worktree"` finishes. For git-based worktrees, Claude handles cleanup automatically with `git worktree remove`. If you configured a WorktreeCreate hook for a non-git version control system, pair it with a WorktreeRemove hook to handle cleanup. Without one, the worktree directory is left on disk.1799The cleanup counterpart to [WorktreeCreate](#worktreecreate). This hook fires when a worktree is being removed, either when you exit a `--worktree` session and choose to remove it, or when a subagent with `isolation: "worktree"` finishes. For git-based worktrees, Claude handles cleanup automatically with `git worktree remove`. If you configured a WorktreeCreate hook for a non-git version control system, pair it with a WorktreeRemove hook to handle cleanup. Without one, the worktree directory is left on disk.
1518 1800
1519Claude Code passes the path that WorktreeCreate printed on stdout as `worktree_path` in the hook input. This example reads that path and removes the directory:1801Claude Code passes the path returned by WorktreeCreate as `worktree_path` in the hook input. This example reads that path and removes the directory:
1520 1802
1521```json theme={null}1803```json theme={null}
1522{1804{
1549}1831}
1550```1832```
1551 1833
1552WorktreeRemove hooks have no decision control. They cannot block worktree removal but can perform cleanup tasks like removing version control state or archiving changes. Hook failures are logged in debug mode only. Only `type: "command"` hooks are supported.1834WorktreeRemove hooks have no decision control. They cannot block worktree removal but can perform cleanup tasks like removing version control state or archiving changes. Hook failures are logged in debug mode only.
1553 1835
1554### PreCompact1836### PreCompact
1555 1837
1571 "session_id": "abc123",1853 "session_id": "abc123",
1572 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1854 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1573 "cwd": "/Users/...",1855 "cwd": "/Users/...",
1574 "permission_mode": "default",
1575 "hook_event_name": "PreCompact",1856 "hook_event_name": "PreCompact",
1576 "trigger": "manual",1857 "trigger": "manual",
1577 "custom_instructions": ""1858 "custom_instructions": ""
1598 "session_id": "abc123",1879 "session_id": "abc123",
1599 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1880 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1600 "cwd": "/Users/...",1881 "cwd": "/Users/...",
1601 "permission_mode": "default",
1602 "hook_event_name": "PostCompact",1882 "hook_event_name": "PostCompact",
1603 "trigger": "manual",1883 "trigger": "manual",
1604 "compact_summary": "Summary of the compacted conversation..."1884 "compact_summary": "Summary of the compacted conversation..."
1617| Reason | Description |1897| Reason | Description |
1618| :---------------------------- | :----------------------------------------- |1898| :---------------------------- | :----------------------------------------- |
1619| `clear` | Session cleared with `/clear` command |1899| `clear` | Session cleared with `/clear` command |
1900| `resume` | Session switched via interactive `/resume` |
1620| `logout` | User logged out |1901| `logout` | User logged out |
1621| `prompt_input_exit` | User exited while prompt input was visible |1902| `prompt_input_exit` | User exited while prompt input was visible |
1622| `bypass_permissions_disabled` | Bypass permissions mode was disabled |1903| `bypass_permissions_disabled` | Bypass permissions mode was disabled |
1631 "session_id": "abc123",1912 "session_id": "abc123",
1632 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1913 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
1633 "cwd": "/Users/...",1914 "cwd": "/Users/...",
1634 "permission_mode": "default",
1635 "hook_event_name": "SessionEnd",1915 "hook_event_name": "SessionEnd",
1636 "reason": "other"1916 "reason": "other"
1637}1917}
1639 1919
1640SessionEnd hooks have no decision control. They cannot block session termination but can perform cleanup tasks.1920SessionEnd hooks have no decision control. They cannot block session termination but can perform cleanup tasks.
1641 1921
1642SessionEnd hooks have a default timeout of 1.5 seconds. This applies to both session exit and `/clear`. If your hooks need more time, set the `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` environment variable to a higher value in milliseconds. Any per-hook `timeout` setting is also capped by this value.1922SessionEnd hooks have a default timeout of 1.5 seconds. This applies to session exit, `/clear`, and switching sessions via interactive `/resume`. If your hooks need more time, set the `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` environment variable to a higher value in milliseconds. Any per-hook `timeout` setting is also capped by this value.
1643 1923
1644```bash theme={null}1924```bash theme={null}
1645CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS=5000 claude1925CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS=5000 claude
1774* `Stop`2054* `Stop`
1775* `SubagentStop`2055* `SubagentStop`
1776* `TaskCompleted`2056* `TaskCompleted`
2057* `TaskCreated`
1777* `UserPromptSubmit`2058* `UserPromptSubmit`
1778 2059
1779Events that only support `type: "command"` hooks:2060Events that support `command` and `http` hooks but not `prompt` or `agent`:
1780 2061
1781* `ConfigChange`2062* `ConfigChange`
2063* `CwdChanged`
1782* `Elicitation`2064* `Elicitation`
1783* `ElicitationResult`2065* `ElicitationResult`
2066* `FileChanged`
1784* `InstructionsLoaded`2067* `InstructionsLoaded`
1785* `Notification`2068* `Notification`
2069* `PermissionDenied`
1786* `PostCompact`2070* `PostCompact`
1787* `PreCompact`2071* `PreCompact`
1788* `SessionEnd`2072* `SessionEnd`
1789* `SessionStart`2073* `StopFailure`
1790* `SubagentStart`2074* `SubagentStart`
1791* `TeammateIdle`2075* `TeammateIdle`
1792* `WorktreeCreate`2076* `WorktreeCreate`
1793* `WorktreeRemove`2077* `WorktreeRemove`
1794 2078
2079`SessionStart` supports only `command` hooks.
2080
1795### How prompt-based hooks work2081### How prompt-based hooks work
1796 2082
1797Instead of executing a Bash command, prompt-based hooks:2083Instead of executing a Bash command, prompt-based hooks:
2035* **Use absolute paths**: specify full paths for scripts, using `"$CLAUDE_PROJECT_DIR"` for the project root2321* **Use absolute paths**: specify full paths for scripts, using `"$CLAUDE_PROJECT_DIR"` for the project root
2036* **Skip sensitive files**: avoid `.env`, `.git/`, keys, etc.2322* **Skip sensitive files**: avoid `.env`, `.git/`, keys, etc.
2037 2323
2324## Windows PowerShell tool
2325
2326On Windows, you can run individual hooks in PowerShell by setting `"shell": "powershell"` on a command hook. Hooks spawn PowerShell directly, so this works regardless of whether `CLAUDE_CODE_USE_POWERSHELL_TOOL` is set. Claude Code auto-detects `pwsh.exe` (PowerShell 7+) with a fallback to `powershell.exe` (5.1).
2327
2328```json theme={null}
2329{
2330 "hooks": {
2331 "PostToolUse": [
2332 {
2333 "matcher": "Write",
2334 "hooks": [
2335 {
2336 "type": "command",
2337 "shell": "powershell",
2338 "command": "Write-Host 'File written'"
2339 }
2340 ]
2341 }
2342 ]
2343 }
2344}
2345```
2346
2038## Debug hooks2347## Debug hooks
2039 2348
2040Run `claude --debug` to see hook execution details, including which hooks matched, their exit codes, and output. Toggle verbose mode with `Ctrl+O` to see hook progress in the transcript.2349Run `claude --debug` to see hook execution details, including which hooks matched, their exit codes, and output.
2041 2350
2042```text theme={null}2351```text theme={null}
2043[DEBUG] Executing hooks for PostToolUse:Write2352[DEBUG] Executing hooks for PostToolUse:Write
2044[DEBUG] Getting matching hook commands for PostToolUse with query: Write
2045[DEBUG] Found 1 hook matchers in settings
2046[DEBUG] Matched 1 hooks for query "Write"
2047[DEBUG] Found 1 hook commands to execute2353[DEBUG] Found 1 hook commands to execute
2048[DEBUG] Executing hook command: <Your command> with timeout 600000ms2354[DEBUG] Executing hook command: <Your command> with timeout 600000ms
2049[DEBUG] Hook command completed with status 0: <Your stdout>2355[DEBUG] Hook command completed with status 0: <Your stdout>
2050```2356```
2051 2357
2358For more granular hook matching details, set `CLAUDE_CODE_DEBUG_LOG_LEVEL=verbose` to see additional log lines such as hook matcher counts and query matching.
2359
2052For troubleshooting common issues like hooks not firing, infinite Stop hook loops, or configuration errors, see [Limitations and troubleshooting](/en/hooks-guide#limitations-and-troubleshooting) in the guide.2360For troubleshooting common issues like hooks not firing, infinite Stop hook loops, or configuration errors, see [Limitations and troubleshooting](/en/hooks-guide#limitations-and-troubleshooting) in the guide.