Follow Discord
Sweep 24 Nov 2026 · 22:58Z Build v2.1.332 549 read Stable v2.1.326 Latest v2.1.332 Next v2.1.332 Feeds RSS JSON llms.txt llms-full.txt Unofficial
One capture · claude-code

One read of Claude Code CLIclaude-code-20261125T060701Z

8 pages moved out of 221 read.

Pages moved 8 significant first
Pages read 221 in this capture
Captured 06:07 UTC
Corpus hash 63aa80a62b59 corpus-hash

What this read moved

1-8 of 8

hooks Changed · +87 / -7 lines

### PreSkillShellCommand #### Commands that reach a PreSkillShellCommand hook #### PreSkillShellCommand input #### PreSkillShellCommand decision control

This page is larger than the 256 KiB this site keeps, so one side of the diff below stops where the stored text does.

from line 20
2020* per turn: `UserPromptSubmit`, `Stop`, and `StopFailure`
2121* on every tool call inside the agentic loop: `PreToolUse` and `PostToolUse`, except [`EndConversation`](https://code.claude.com/docs/en/tools-reference#endconversation-tool-behavior) calls, which skip both
2222 
23![Hook lifecycle diagram showing optional Setup feeding into SessionStart, then a per-turn loop containing UserPromptSubmit, UserPromptExpansion for slash commands, the nested agentic loop (PreToolUse, PermissionRequest, PostToolUse, PostToolUseFailure, PostToolBatch, SubagentStart/Stop, TaskCreated, TaskCompleted), and Stop or StopFailure, followed by 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, WorktreeCreate, WorktreeRemove, Notification, ConfigChange, InstructionsLoaded, CwdChanged, FileChanged, and DirectoryAdded as standalone async events, PreModelSwitch as a standalone sequential event that runs before a requested model switch, PostModelSwitch as a standalone async event that runs after the session's model changes, and MessageDisplay as a display-only event that runs while assistant message text streams](https://mintcdn.com/claude-code/x7pO8l4XcvAXCoVc/images/hooks-lifecycle.svg?fit=max\&auto=format\&n=x7pO8l4XcvAXCoVc\&q=85\&s=81b9256c1bbe8832553485f5d9e9c746)
23![Hook lifecycle diagram showing optional Setup feeding into SessionStart, then a per-turn loop containing UserPromptSubmit, UserPromptExpansion for slash commands, the nested agentic loop (PreToolUse, PermissionRequest, PostToolUse, PostToolUseFailure, PostToolBatch, SubagentStart/Stop, TaskCreated, TaskCompleted), and Stop or StopFailure, followed by 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, WorktreeCreate, WorktreeRemove, Notification, ConfigChange, InstructionsLoaded, CwdChanged, FileChanged, and DirectoryAdded as standalone async events, PreSkillShellCommand as a standalone blocking event that runs before a shell command in a loading skill, PreModelSwitch as a standalone sequential event that runs before a requested model switch, PostModelSwitch as a standalone async event that runs after the session's model changes, and MessageDisplay as a display-only event that runs while assistant message text streams](https://mintcdn.com/claude-code/IWhl7FXSx6ARoVoo/images/hooks-lifecycle.svg?fit=max\&auto=format\&n=IWhl7FXSx6ARoVoo\&q=85\&s=a8adf56a3d13b8a8ba9c446bbd7171f8)
2424 
2525The 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.
2626 
from line 30
3030| `Setup` | When you start Claude Code with `--init-only`, or with `--init` or `--maintenance` in `-p` mode. For one-time preparation in CI or scripts |
3131| `UserPromptSubmit` | When a prompt is submitted, before Claude processes it. Also fires on [turns Claude Code starts on its own](https://code.claude.com/docs/en/hooks.md#userpromptsubmit) |
3232| `UserPromptExpansion` | When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion |
33| `PreSkillShellCommand` | Before a skill's [injected shell command](https://code.claude.com/docs/en/skills.md#inject-dynamic-context) runs. Can block the command |
3334| `PreToolUse` | Before a tool call executes. Can block it |
3435| `PermissionRequest` | When a tool call needs a permission decision |
3536| `PermissionDenied` | When auto mode denies a tool call, including denials without a classifier verdict. Use JSON `hookSpecificOutput.retry: true` to tell the model it may retry the denied tool call. Claude Code ignores `retry` when the classifier produced no verdict |
from line 305
304305| `StopFailure` | error type | `rate_limit`, `authentication_failed`, `oauth_org_not_allowed`, `account_on_hold`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, `cloud_credential_error`, `unknown` |
305306| `InstructionsLoaded` | load reason | `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact` |
306307| `UserPromptExpansion` | command name | your skill or command names |
308| `PreSkillShellCommand` | tool that runs the command | `Bash`, `PowerShell` |
307309| `Elicitation` | MCP server name | your configured MCP server names |
308310| `ElicitationResult` | MCP server name | same values as `Elicitation` |
309311| `UserPromptSubmit`, `PostToolBatch`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `MessageDisplay` | no matcher support | always fires on every occurrence |
from line 419
417419| Field | Required | Description |
418420| :- | :- | :- |
419421| `type` | yes | `"command"`, `"http"`, `"mcp_tool"`, `"prompt"`, or `"agent"` |
420| `if` | no | [Permission rule syntax](https://code.claude.com/docs/en/permissions.md#permission-rule-syntax) to filter when this hook runs, such as `"Bash(git *)"` or `"Edit(*.ts)"`. The hook command only runs if the tool call matches the pattern. See the [Bash matching table](#bash-if-matching) for how Bash patterns evaluate against subcommands, `$()`, and backticks. Only evaluated on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. On other events, a hook with `if` set never runs |
422| `if` | no | [Permission rule syntax](https://code.claude.com/docs/en/permissions.md#permission-rule-syntax) to filter when this hook runs, such as `"Bash(git *)"` or `"Edit(*.ts)"`. The hook command only runs if the tool call matches the pattern. See the [Bash matching table](#bash-if-matching) for how Bash patterns evaluate against subcommands, `$()`, and backticks. Only evaluated on `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied`, and `PreSkillShellCommand`. On other events, a hook with `if` set doesn't run |
421423| `timeout` | no | Seconds before canceling. Claude Code doesn't enforce it on a command hook you run with [`async: true`](#run-hooks-in-the-background). Defaults: 600 for `command`, `http`, and `mcp_tool`; 30 for `prompt`; 60 for `agent`. Claude Code lowers the `command`, `http`, and `mcp_tool` default to 30 on [`UserPromptSubmit`](#userpromptsubmit), [`PreModelSwitch`](#premodelswitch), and [`PostModelSwitch`](#postmodelswitch), and to 10 on [`MessageDisplay`](#messagedisplay). [`SessionEnd`](#sessionend) hooks share a 1.5-second budget; if your settings set a longer per-hook `timeout`, Claude Code raises the budget to match, up to 60 seconds |
422424| `statusMessage` | no | Custom spinner message displayed while the hook runs |
423425| `once` | no | If `true`, Claude Code removes the hook after its first successful run. A run that fails, blocks with exit code 2, or times out leaves the hook in place, so it runs again on the next matching event. Only honored for hooks declared in [skill frontmatter](#hooks-in-skills-and-agents); ignored in settings files and agent frontmatter |
from line 941
939941 
940942> [!NOTE]
941943>
942> On Windows without Git Bash, a shell-form `PreToolUse` or `PermissionRequest` command hook that fails with `onFailure` unset can instead [block the tool call](#failed-hooks-on-windows-without-git-bash).
944> On Windows without Git Bash, a shell-form `PreToolUse`, `PermissionRequest`, or `PreSkillShellCommand` command hook that fails with `onFailure` unset can instead [block the action](#failed-hooks-on-windows-without-git-bash).
943945 
944This `PreToolUse` hook in `.claude/settings.json` runs a project script before each Bash command, and blocks the command if the script fails:
946This `PreToolUse` hook in `.claude/settings.json` runs a project script before each Bash tool call, and blocks the command if the script fails:
945947 
946948```json theme={null}
947949{
from line 996
994996 
995997#### Failed hooks on Windows without Git Bash
996998 
997If the error for a blocked tool call includes this text, a `PreToolUse` or `PermissionRequest` command hook failed or timed out and blocked the call:
999If the error for a blocked tool call or [injected command](#preskillshellcommand) includes this text, a command hook on `PreToolUse`, `PermissionRequest`, or `PreSkillShellCommand` failed or timed out and blocked it:
9981000 
9991001```text theme={null}
10001002blocking because Git Bash wasn't found, so only exit code 0 or 2 counts as this hook's verdict.
from line 1035
10331035| `PermissionRequest` | No | Not read as a decision. Deny through the [`decision` object](#permissionrequest-decision-control) instead |
10341036| `UserPromptSubmit` | Yes | Blocks the prompt. See [What a blocked prompt leaves behind](#what-a-blocked-prompt-leaves-behind) |
10351037| `UserPromptExpansion` | Yes | Blocks the expansion |
1038| `PreSkillShellCommand` | Yes | Blocks the command, and the skill loads without its output |
10361039| `Stop` | Yes | Prevents Claude from stopping, continues the conversation |
10371040| `SubagentStop` | Yes | Prevents the subagent from stopping |
10381041| `TeammateIdle` | Yes | Prevents the teammate from going idle, so it continues working |
from line 1212
12091212| TaskCreated | Exit code or top-level `decision` | Exit code 2 or `decision: "block"` [cancels the task](#taskcreated-decision-control) and returns the message to Claude. `continue: false` is ignored |
12101213| PreToolUse | `hookSpecificOutput` | `permissionDecision` (allow/deny/ask/defer), `permissionDecisionReason` |
12111214| PreModelSwitch | `hookSpecificOutput` or top-level `decision` | `permissionDecision` (allow/deny/ask), `permissionDecisionReason`. `decision: "block"` also [cancels the switch](#premodelswitch-decision-control) |
1215| PreSkillShellCommand | `hookSpecificOutput` or top-level `decision` | `permissionDecision`, `permissionDecisionReason`. The hook [can only block](#preskillshellcommand-decision-control) |
12121216| PermissionRequest | `hookSpecificOutput` | `decision.behavior` (allow/deny) |
12131217| PermissionDenied | `hookSpecificOutput` | `retry: true` tells the model it may retry the denied tool call; Claude Code ignores it for [no-verdict denials](#permissiondenied-decision-control) |
12141218| WorktreeCreate | path return | Command hook prints path on stdout; HTTP hook returns `hookSpecificOutput.worktreePath`. Hook failure or missing path fails creation |
from line 1652
16481652}
16491653```
16501654 
1655### PreSkillShellCommand
1656 
1657Runs before an [injected command](https://code.claude.com/docs/en/skills.md#inject-dynamic-context), a shell command that runs while a skill or a command such as `/security-review` loads. [PreToolUse](#pretooluse) hooks don't fire for injected commands. To log or block them with a script you already run on PreToolUse, add the script to this event too. In a skill's file, injected commands appear as `` !`<command>` `` or in a ` ```! ` block.
1658 
1659Requires Claude Code v2.1.332 or later, including in the desktop app and VS Code extension. Update before you add the hook, because earlier versions run injected commands without calling it. If you add it to a settings file first, an earlier version such as v2.1.331 opens each interactive terminal session with a [warning dialog](https://code.claude.com/docs/en/settings.md#fix-a-broken-settings-file): `Unknown hook event "PreSkillShellCommand" was ignored`. To enforce a minimum version, see [`requiredMinimumVersion`](https://code.claude.com/docs/en/settings-reference#requiredminimumversion).
1660 
1661For a hook that has to block commands, set the matcher, type, location, and failure handling this way:
1662 
1663* **Matcher**: use `Bash|PowerShell` to cover [both tools that run injected commands](https://code.claude.com/docs/en/skills.md#how-injected-commands-run).
1664* **Type**: use a `command`, `http`, or `mcp_tool` hook that isn't [async](#run-hooks-in-the-background), because an async hook can't block. If you configure a `prompt` or `agent` hook on this event, Claude Code can't run it and blocks each command the hook matches.
1665* **Location**: define the hook in a [settings file](#hook-locations), such as managed settings, or in a plugin. A skill's injected commands run without the hooks in its own frontmatter on its first load in a session and on loads inside a subagent. A [forked skill](https://code.claude.com/docs/en/skills.md#run-skills-in-a-subagent)'s injected commands run without the hooks in its own frontmatter or in its subagent's definition.
1666* **Failures**: set [`onFailure: "block"`](#block-the-action-when-a-hook-fails) so the command doesn't run when the hook fails or times out.
1667 
1668You can reuse the blocking script from [How a hook resolves](#how-a-hook-resolves).
1669 
1670On macOS and Linux, this entry in `.claude/settings.json` runs the script in [exec form](#exec-form-and-shell-form):
1671 
1672```json theme={null}
1673{
1674 "hooks": {
1675 "PreSkillShellCommand": [
1676 {
1677 "matcher": "Bash|PowerShell",
1678 "hooks": [
1679 { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.sh", "args": [], "onFailure": "block" }
1680 ]
1681 }
1682 ]
1683 }
1684}
1685```
1686 
1687On Windows, replace `command` and `args` in this entry with the ones in the Windows tab of [How a hook resolves](#how-a-hook-resolves).
1688 
1689To test this example on macOS or Linux, create `.claude/skills/hook-test/SKILL.md` with the single line `` !`echo 'rm -rf'` ``. This [read-only command](https://code.claude.com/docs/en/permissions.md#read-only-commands) needs no approval and deletes nothing. Start a session in your terminal and type `/hook-test`. You see `Not run in /hook-test: echo 'rm -rf' (blocked by hook: Destructive command blocked by hook)`.
1690 
1691#### Commands that reach a PreSkillShellCommand hook
1692 
1693Your script runs after the [permission check on injected commands](https://code.claude.com/docs/en/skills.md#permission-checks-on-injected-commands), so it gets the commands that passed. It also runs in `bypassPermissions` mode.
1694 
1695In auto mode, a command that would otherwise need approval doesn't run while the skill loads. Claude can run it afterward as a tool call, which fires `PreToolUse` and not this event, so keep your script on both events.
1696 
1697#### PreSkillShellCommand input
1698 
1699In addition to the [common input fields](#common-input-fields), which include `permission_mode`, PreSkillShellCommand hooks receive the fields in this table:
1700 
1701| Field | Description |
1702| :- | :- |
1703| `tool_name` | The tool that runs the command, `Bash` or `PowerShell` |
1704| `tool_input.command` | The shell command as it would run |
1705| `tool_use_id` | ID of this command, which names no tool call in the transcript |
1706| `command_name` | Name of the skill or command that is loading, such as `pr-summary`, or `my-plugin:deploy` for a plugin's skill |
1707| `command_source` | Where the skill or command comes from, such as `userSettings`, `projectSettings`, `policySettings`, `plugin`, or `builtin` |
1708| `invoked_by` | `"user"` when you typed the skill's name or an Agent SDK app sent it, or `"claude"` when Claude or a [session-scoped scheduled task](https://code.claude.com/docs/en/scheduled-tasks.md) invoked the skill. `"other"` for anything else, such as a subagent that [preloads the skill](https://code.claude.com/docs/en/sub-agents.md#preload-skills-into-subagents). |
1709 
1710#### PreSkillShellCommand decision control
1711 
1712To block an injected command, have your script exit 2 or return `permissionDecision: "deny"`, and the skill loads without running that command. You can block a command from this hook, but you can't approve or change one.
1713 
1714For a JSON response, use the [PreToolUse format](#pretooluse-decision-control). To use one script on both events, leave `hookEventName` as `PreToolUse`. For a script you run only on this event, you can set `hookEventName` to `PreSkillShellCommand`.
1715 
1716| Hook outcome | What happens |
1717| :- | :- |
1718| Exit 0 with no decision, or `permissionDecision: "allow"` | The command runs unless another hook blocks it |
1719| Exit 2, `permissionDecision: "deny"`, or top-level `decision: "block"` | The command doesn't run. The skill still loads, and Claude reads `[not run: blocked by hook: <reason>]` in place of the command's output. |
1720| `permissionDecision: "ask"` or `"defer"`, or any `updatedInput` | Claude Code blocks the command the same way as `"deny"` |
1721| `continue: false` | Invoking the skill fails with `Operation stopped by hook: <stopReason>`. None of its injected commands runs, because Claude Code collects your hooks' answers before it runs the first one. |
1722| A `command`, `http`, or `mcp_tool` hook fails, for example by exiting 1 with no JSON output, or times out | The command runs unless the hook is [one whose failure blocks the action](#block-the-action-when-a-hook-fails). In a [Code Mode](https://code.claude.com/docs/en/code-mode.md#tool-call-refused-by-a-hook) session where Claude has already run code, a timeout blocks the command by default. |
1723 
1724When you type a skill's name in your terminal, a `Not run in /<name>` line reports a blocked command. A `Ran anyway in /<name>` line reports a command that ran after its hook failed or timed out.
1725 
1726To give a reason for a block, write it to stderr when you exit 2. In JSON, put it in `permissionDecisionReason`, or in `reason` beside a top-level `decision`. While [Remote Control](https://code.claude.com/docs/en/remote-control.md) is connected, the hook still blocks, and neither you nor Claude sees the reason. Find it in the [debug log](#debug-hooks).
1727 
16511728### MessageDisplay
16521729 
16531730Runs while an assistant message streams to the screen. Claude Code displays the message in increments: each time a batch of newly completed lines is ready to render, the hook runs once with those lines and Claude Code renders the hook's replacement text in their place. A long message produces several calls; a short message may produce only one.
from line 1862
17851862 
17861863> [!WARNING]
17871864>
1788> PreToolUse runs only when Claude calls a tool. By default, files you [reference with `@` in your prompt](https://code.claude.com/docs/en/common-workflows#reference-files-and-directories) are added without any tool call. Claude Code inserts their contents while building the prompt, so no PreToolUse hook fires for them, including hooks matching `Read`. PreToolUse also doesn't fire for [`EndConversation`](https://code.claude.com/docs/en/tools-reference#endconversation-tool-behavior).
1865> PreToolUse runs when Claude calls a tool. It doesn't fire for [injected commands](https://code.claude.com/docs/en/skills.md#inject-dynamic-context), the shell commands that pass a [permission check](https://code.claude.com/docs/en/skills.md#permission-checks-on-injected-commands) and run while a skill loads. To log or block those, add a [PreSkillShellCommand](#preskillshellcommand) hook.
17891866>
1867> By default, files you [reference with `@` in your prompt](https://code.claude.com/docs/en/common-workflows#reference-files-and-directories) are added without any tool call. Claude Code inserts their contents while building the prompt, so no PreToolUse hook fires for them, including hooks matching `Read`. PreToolUse also doesn't fire for [`EndConversation`](https://code.claude.com/docs/en/tools-reference#endconversation-tool-behavior).
1868>
17901869> You can block specific paths from `@` references, or turn the insertion off:
17911870>
17921871> * **Block specific paths**: add a [`Read` deny rule](https://code.claude.com/docs/en/permissions#read-and-edit) for them
from line 3640
35613640| `prompt_cache_warm` | boolean | Whether the current model's prompt cache is likely still warm, meaning the switch forfeits it |
35623641| `cache_ttl` | string | [Prompt cache lifetime](https://code.claude.com/docs/en/prompt-caching.md#cache-lifetime) of the main conversation at the time of this switch: `"5m"` or `"1h"` |
35633642| `estimated_cache_write_usd` | number | Estimated cost in US dollars of writing `context_tokens` to the prompt cache on `to_model` at the `cache_ttl` rate, excluding the next response. The server may not need to re-cache the whole context, so treat it as an estimate |
3564| `pricing` | string | How Claude Code priced `estimated_cache_write_usd`: `"configured"` at your organization's own rates when it has configured them, `"catalog"` at list price, or `"default"` when `to_model` has no known price and Claude Code assumed a default rate |
3565 
3566This example shows the input for `/model opus` in a session running Sonnet 5:
3567 
3568```json theme={null}
3569{
3570 "session_id": "abc123",
3571 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
3572 "cwd": "/Users/...",
3573 "hook_event_name": "PreModelSwitch",
3574 "from_model": "claude-sonnet-5",
3575 "to_model": "claude-opus-5",
3576 "requested_model": "opus",
3577 "source": "command",
3578 "context_tokens": 182340,
3579 "prompt_cache_warm": true,
3580 "cache_ttl": "5m",
3581 "estimated_cache_write_usd": 1.1396,
3582 "pricing": "catalog"
3583}
3584```
3585 
3586#### PreModelSwitch decision control
3587 
3588`PreModelSwitch` hooks can cancel the switch, ask the user to confirm it, or let it proceed. Exit code 2 or a top-level `decision: "block"` cancels the switch.
3589 
3590For finer control, return `permissionDecision` and `permissionDecisionReason` in a `hookSpecificOutput` object, as on [PreToolUse](#pretooluse-decision-control). `PreModelSwitch` accepts `"allow"`, `"deny"`, and `"ask"`. It doesn't accept `"defer"`, `updatedInput`, or `additionalContext`. The table below describes both fields:
3591 
3592| Field | Description |
3593| :- | :- |
3594| `permissionDecision` | `"allow"` proceeds and skips the [confirmation Claude Code shows while the prompt cache is warm](https://code.claude.com/docs/en/prompt-caching.md#switching-models). `"deny"` cancels the switch. `"ask"` prompts the user to confirm it |
3595| `permissionDecisionReason` | For `"deny"`, shown to the user as the reason the switch was blocked, or returned as the error for a `set_model` request. For `"ask"`, shown in the confirmation prompt. Ignored for `"allow"` |
3596 
3597Only `/model` in an interactive session can show the `"ask"` prompt. On every other surface, including non-interactive mode with the `-p` flag, `/config`, and `set_model` requests, Claude Code treats `"ask"` as a refusal.
3598 
3599This example asks the user to confirm and quotes the token count from `context_tokens`:
3600 
3601```json theme={null}
3602{
3603 "hookSpecificOutput": {
3604 "hookEventName": "PreModelSwitch",
3605 "permissionDecision": "ask",
3606 "permissionDecisionReason": "Switching now re-sends about 180k tokens to the new model. Continue?"
3607 }
3608}
3609```
3610 
3611When multiple PreModelSwitch hooks return different decisions, precedence is `deny` > `ask` > `allow`.
3612 
3613Claude Code shows the user any `systemMessage` your hook returns regardless of the decision, so a cost-report hook can return `{"systemMessage": "..."}` and exit 0.
3614 
3615#### PreModelSwitch timeouts and other exit codes
3616 
3617A PreModelSwitch hook that doesn't respond before its timeout blocks the switch. The default timeout for this event is 30 seconds.
3618 
3619An exit code other than 0 or 2 without valid JSON output is a [non-blocking error](#other-exit-codes), so the switch goes ahead, except for hooks [whose failure blocks it](#block-the-action-when-a-hook-fails).
3620 
3621### PostModelSwitch
3622 
3623Runs after the session's model changes. Use it to give Claude model-specific guidance without editing every CLAUDE.md, for example an organization-wide instruction that applies on certain models.
3624 
3625PostModelSwitch requires Claude Code v2.1.251 or later. It can't block, because the model has already changed. Claude Code runs PostModelSwitch hooks after any of these changes:
3626 
3627* A switch you or a client requested
3628* An [automatic model fallback](https://code.claude.com/docs/en/model-config.md#automatic-model-fallback), which changes the session's model
3629* A setting such as [`opusplan`](https://code.claude.com/docs/en/model-config#opusplan-model-setting) entering or leaving plan mode
3630* Claude Code restoring the model when you resume a session
3631 
3632Claude Code doesn't run PostModelSwitch hooks when a model from a [fallback model chain](https://code.claude.com/docs/en/model-config.md#fallback-model-chains) serves a turn, because that substitution lasts one turn and leaves the session's model unchanged.
3633 
3634The matcher follows the same rules as [PreModelSwitch](#premodelswitch): Claude Code compares it against the canonical name of the model the session switched to.
3635 
3636This example adds guidance whenever the session's model changes to any Opus model:
3637 
3638```json theme={null}
3639{
3640 "hooks": {
3641 "PostModelSwitch": [
3642 {
3643 "matcher": ".*opus.*",
3644 "hooks": [
3645 {
3646 "type": "command",
3647 "command": "echo 'On Opus, delegate implementation work to subagents and keep this conversation for planning and review.'"
3648 }
3649 ]
3650 }
3651 ]
3652 }
3653}
3654```
3655 
3656To confirm the hook works, switch to an Opus model from a session running a different model, for example run `/model opus` from a Sonnet session, then ask Claude what guidance it has about the current model.
3657 
3658#### PostModelSwitch input
3659 
3660PostModelSwitch hooks receive the same fields as [PreModelSwitch](#premodelswitch-input), with `hook_event_name` set to `"PostModelSwitch"` and two more `source` values: `"auto"` for an automatic fallback or other change Claude Code made on its own, and `"resume"` for the model restored when you resume a session.
3661 
3662`requested_model` is `null` when `source` is `"auto"`. When `source` is `"resume"`, it is the saved model setting Claude Code restored.
3663 
3664#### PostModelSwitch decision control
3665 
3666Claude Code takes your hook's [plain-text stdout](#exit-code-0) on exit 0, or `additionalContext` from JSON output, and delivers it to Claude with the next request after the switch. In addition to the [JSON output fields](#json-output) available to all hooks, you can return:
3667 
3668| Field | Description |
3669| :- | :- |
3670| `additionalContext` | String added to Claude's context with the next request. See [Add context for Claude](#add-context-for-claude) |
3671 
3672If the hook hasn't finished within five seconds after you send the next prompt, Claude Code sends that request without the output and attaches it to the following request instead. If the model changes several times before the next request, Claude Code delivers only the output for the last switch's target model.
3673 
3674### SessionEnd
3675 
3676Runs when a Claude Code session ends. Useful for cleanup tasks, logging session
3677statistics, or saving session state. Supports matchers to filter by exit reason.
3678 
3679The `reason` field in the hook input indicates why the session ended:
3680 
3681| Reason | Description |
3682| :- | :- |
3683| `clear` | Session cleared with `/clear` command |
3684| `resume` | Session switched via interactive `/resume` |
3685| `logout` | User logged out |
3686| `prompt_input_exit` | User exited while prompt input was visible |
3687| `other` | Other exit reasons |
3688| `bypass_permissions_disabled` | Removed in v2.1.234; Claude Code doesn't send it. Drop it from your `SessionEnd` matchers |
3689 
3690#### SessionEnd input
3691 
3692In addition to the [common input fields](#common-input-fields), SessionEnd hooks receive a `reason` field indicating why the session ended. See the [reason table](#sessionend) above for all values.
3693 
3694```json theme={null}
3695{
3696 "session_id": "abc123",
3697 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
3698 "cwd": "/Users/...",
3699 "hook_event_name": "SessionEnd",
3700 "reason": "other"
3701}
3702```
3703 
3704SessionEnd hooks have no decision control. They can't block session termination but can perform cleanup tasks. Claude Code discards their [JSON output fields](#json-output), such as `systemMessage`.
3705 
3706SessionEnd hooks have a default timeout of 1.5 seconds. It applies when you exit, run `/clear`, or switch sessions with interactive `/resume`. You can give a hook more time in two ways:
3707 
3708* **Per-hook `timeout`**: set `timeout` in that hook's configuration. The overall budget rises automatically to match the highest per-hook `timeout` in your settings files, up to 60 seconds. If you raise the budget this way, a hook without its own `timeout` still keeps the default. Timeouts set on plugin-provided hooks don't raise the budget.
3709* **`CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS`**: set this environment variable in milliseconds to override the budget explicitly. The value you set also becomes the ti
3643| `pricing` | string | How Claude Code priced `estimated_cache_write_usd`: `"configured"` at your organization's own ra

hooks-guide Changed · +5 / -1 lines

from line 471
471471| `Setup` | When you start Claude Code with `--init-only`, or with `--init` or `--maintenance` in `-p` mode. For one-time preparation in CI or scripts |
472472| `UserPromptSubmit` | When a prompt is submitted, before Claude processes it. Also fires on [turns Claude Code starts on its own](https://code.claude.com/docs/en/hooks.md#userpromptsubmit) |
473473| `UserPromptExpansion` | When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion |
474| `PreSkillShellCommand` | Before a skill's [injected shell command](https://code.claude.com/docs/en/skills.md#inject-dynamic-context) runs. Can block the command |
474475| `PreToolUse` | Before a tool call executes. Can block it |
475476| `PermissionRequest` | When a tool call needs a permission decision |
476477| `PermissionDenied` | When auto mode denies a tool call, including denials without a classifier verdict. Use JSON `hookSpecificOutput.retry: true` to tell the model it may retry the denied tool call. Claude Code ignores `retry` when the classifier produced no verdict |
from line 691
690691| `ElicitationResult` | MCP server name | same values as `Elicitation` |
691692| `FileChanged` | literal filenames to watch (see [FileChanged](https://code.claude.com/docs/en/hooks.md#filechanged)) | `.envrc\|.env` |
692693| `UserPromptExpansion` | command name | your skill or command names |
694| `PreSkillShellCommand` | tool that runs the command | `Bash`, `PowerShell` |
693695| `UserPromptSubmit`, `PostToolBatch`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `CwdChanged`, `MessageDisplay` | no matcher support | always fires on every occurrence |
694696 
695697The tabs below show a few more matchers on different event types.
from line 803
801803 
802804The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported.
803805 
804`if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. Adding it to any other event prevents the hook from running.
806> [!NOTE]
807>
808> `if` only works on `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied`, and `PreSkillShellCommand`. If you add it on any other event, the hook doesn't run.
805809 
806810### Configure hook location
807811 

costs Changed · +1 / -1 lines

from line 292
292292 
293293> [tab] settings.json
294294>
295> Add this to your [settings.json](https://code.claude.com/docs/en/settings.md#where-settings-live) to run the hook before every Bash command:
295> Add this to your [settings.json](https://code.claude.com/docs/en/settings.md#where-settings-live) to run the hook before every Bash tool call:
296296>
297297> ```json theme={null}
298298> {

debug-your-config Changed · +1 / -1 lines

from line 58
5858Run `/hooks` to list every hook registered for the current session, grouped by event. If a hook you defined doesn't appear, Claude Code didn't load it. Check for these causes:
5959 
6060* The hook is defined in a standalone file. Hooks go under the `"hooks"` key in a [settings file](https://code.claude.com/docs/en/settings.md#settings-files).
61* The `matcher` value is an array instead of a single string. Claude Code lists the entry as an invalid setting when you start an interactive session and in `claude doctor`. If the array is under `PreToolUse` or `PermissionRequest`, none of that file's other hooks load either.
61* The `matcher` value is an array instead of a single string. Claude Code lists the entry as an invalid setting when you start an interactive session and in `claude doctor`. If the array is under `PreToolUse`, `PermissionRequest`, or `PreSkillShellCommand`, none of that file's other hooks load either.
6262* The hook is in a skill's frontmatter, and neither you nor Claude has invoked the skill yet in this session. Invoke it or ask Claude to, then run `/hooks` again. If the hook still doesn't appear, check for other causes, such as [frontmatter that didn't parse](https://code.claude.com/docs/en/skills.md#skill-not-triggering) or one of the [limits on skill hooks](https://code.claude.com/docs/en/hooks.md#limits-on-skill-hooks).
6363 
6464If the hook appears but doesn't fire, the matcher is the usual cause. Check it for these mistakes:

errors Changed · +1 / -0 lines

This page is larger than the 256 KiB this site keeps, so one side of the diff below stops where the stored text does.

from line 305
305305| `Shell command failed for pattern "..."`, from `/security-review` or any skill that injects dynamic context | [Command-line errors](#security-review-fails-without-origin-head) |
306306| `Shell command permission check failed for pattern "..."`, from a skill that injects dynamic context | [Command-line errors](#security-review-fails-without-origin-head) |
307307| ``Couldn't run `<command>` for <name>. A file named HEAD or .git in this folder or one above it may not be yours``, from a skill that injects dynamic context | [Permission checks on injected commands](https://code.claude.com/docs/en/skills.md#permission-checks-on-injected-commands) |
308| `Not run in /<name>` / `Ran anyway in /<name>` / `[not run: blocked by hook`, from `/security-review` or a skill that injects dynamic context | [PreSkillShellCommand decision control](https://code.claude.com/docs/en/hooks.md#preskillshellcommand-decision-control) |
308309| ``Skill <name> requires bash (`shell: bash` in frontmatter) but Git Bash was not found`` | [Command-line errors](#security-review-fails-without-origin-head) |
309310| `No shell command in <name> was run, because the <tool> tool does not accept one of them` | [Command-line errors](#no-shell-command-was-run) |
310311| `This skill, command or hook and the arguments filled into it add up to more than 4,000,000 characters` | [Command-line errors](#skill-command-or-hook-over-the-4000000-character-limit) |
from line 2375
23742375```text theme={null}
23752376The cloud environments service returned an empty response (HTTP 200 with no body). This is usually temporary — try again in a moment.
23762377The cloud environments service returned a response in an unexpected format (HTTP 200 with a non-JSON body). This is usually temporary — try again in a moment.
2377The cloud environments service returned a response in an unexpected format (HTTP 200 without a usable environments list). This is usually temporary — try again in a moment.
2378```
2379 
2380**What to do:**
2381 
2382* Retry the action. Claude Code requests the list again each time
2383* If the message keeps appearing, check [status.claude.com](https://status.claude.com) for active incidents
2384 
2385Before v2.1.236, Claude Cod
2378The cloud environments service returned a response in an unexpected format (HTTP 200 without a usable environments list). This is u

settings-example Changed · +1 / -1 lines

from line 179
179179> "Read(./secrets/**)"
180180> ]
181181> },
182> // Before every Bash command, run a script in the repo that can block it
182> // Before every Bash tool call, run a script in the repo that can block it
183183> "hooks": {
184184> "PreToolUse": [
185185> {

skills Changed · +2 / -0 lines

from line 817
817817 
818818In auto mode, a command that would otherwise need your approval doesn't abort the invocation. The skill loads with an instruction telling Claude to run the command first, and Claude's own call then goes through [auto mode's usual checks](https://code.claude.com/docs/en/permission-modes.md#how-the-classifier-evaluates-actions). The invocation still aborts in a [forked skill](#run-skills-in-a-subagent) that sets `agent`, and in a session where Claude doesn't have the [shell tool that runs injected commands](#how-injected-commands-run).
819819 
820`PreToolUse` hooks don't fire for injected commands that run as the skill loads. To log or block the ones that pass the permission check, use a [`PreSkillShellCommand` hook](https://code.claude.com/docs/en/hooks#preskillshellcommand).
821 
820822### Run skills in a subagent
821823 
822824Add `context: fork` to your frontmatter when you want a skill to run in isolation. Claude Code starts a new subagent of the type set in the `agent` field and gives it the skill content as its prompt. The subagent doesn't see your conversation history, so the skill's instructions have to stand on their own.

sub-agents Changed · +1 / -1 lines

from line 710
710710 
711711For more dynamic control over tool usage, use `PreToolUse` hooks to validate operations before they execute. This is useful when you need to allow some operations of a tool while blocking others.
712712 
713This example creates a subagent that only allows read-only database queries. The `PreToolUse` hook runs the script specified in `command` before each Bash command executes:
713This example creates a subagent that only allows read-only database queries. The `PreToolUse` hook runs the script specified in `command` before each Bash tool call executes:
714714 
715715```yaml theme={null}
716716---
Feedback