claude-hooks-configuration

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Claude Code Hooks Configuration

Claude Code钩子配置

Core Expertise

核心功能

Configure Claude Code lifecycle hooks (all 17 events including SessionStart, Stop, PreToolUse, PostToolUse, PostToolUseFailure, PermissionRequest, WorktreeCreate, TeammateIdle, TaskCompleted, ConfigChange, and more) with proper timeout settings to prevent "Hook cancelled" errors during session management.
配置Claude Code生命周期钩子(包含SessionStart、Stop、PreToolUse、PostToolUse、PostToolUseFailure、PermissionRequest、WorktreeCreate、TeammateIdle、TaskCompleted、ConfigChange等全部17种事件)并设置合理的超时时间,以避免会话管理过程中出现“钩子已取消”错误。

Hook Events

钩子事件

HookTriggerDefault Timeout
SessionStart
When Claude Code session begins600s (command)
SessionEnd
When session ends or
/clear
runs
600s (command)
Stop
When main agent stops responding600s (command)
SubagentStop
When a subagent (Task tool) finishes600s (command)
PreToolUse
Before a tool executes600s (command)
PostToolUse
After a tool completes600s (command)
PostToolUseFailure
After a tool execution fails600s (command)
PermissionRequest
When Claude requests permission for a tool600s (command)
WorktreeCreate
New git worktree created via EnterWorktree600s (command)
WorktreeRemove
Worktree removed after session exits600s (command)
TeammateIdle
Teammate in agent team goes idle600s (command)
TaskCompleted
Task in shared task list marked complete600s (command)
ConfigChange
Claude Code settings change at runtime600s (command)
Default timeouts:
command
= 600s,
prompt
= 30s,
agent
= 60s. Always set explicit timeouts — it documents intent.
钩子触发时机默认超时时间
SessionStart
当Claude Code会话开始时600秒(command类型)
SessionEnd
当会话结束或执行
/clear
600秒(command类型)
Stop
主Agent停止响应时600秒(command类型)
SubagentStop
子Agent(任务工具)完成时600秒(command类型)
PreToolUse
工具执行前600秒(command类型)
PostToolUse
工具完成后600秒(command类型)
PostToolUseFailure
工具执行失败后600秒(command类型)
PermissionRequest
当Claude请求工具权限时600秒(command类型)
WorktreeCreate
通过EnterWorktree创建新的git工作树时600秒(command类型)
WorktreeRemove
会话退出后删除工作树时600秒(command类型)
TeammateIdle
Agent团队中的成员进入空闲状态时600秒(command类型)
TaskCompleted
共享任务列表中的任务标记为完成时600秒(command类型)
ConfigChange
运行时修改Claude Code设置时600秒(command类型)
默认超时时间:
command
=600秒,
prompt
=30秒,
agent
=60秒。建议始终显式设置超时时间,以明确配置意图。

Hook Types

钩子类型

TypeHow It WorksDefault TimeoutUse When
command
Runs a shell command, reads stdin, returns exit code/JSON600sDeterministic rules
http
Sends hook data to an HTTPS endpoint30sRemote/centralized policy
prompt
Single-turn LLM call, returns
{ok: true/false}
30sJudgment on hook input data
agent
Multi-turn subagent with tool access, returns
{ok: true/false}
60sVerification needing file/tool access
类型工作机制默认超时时间适用场景
command
执行shell命令,读取标准输入,返回退出码/JSON600秒确定性规则场景
http
将钩子数据发送至HTTPS端点30秒远程/集中式策略场景
prompt
单轮LLM调用,返回
{ok: true/false}
30秒对钩子输入数据进行判断的场景
agent
具备工具访问权限的多轮子Agent,返回
{ok: true/false}
60秒需要访问文件/工具进行验证的场景

Async and Once

异步与单次执行

  • async: true
    on command hooks: fire-and-forget, does not block the operation
  • once: true
    on any hook handler: runs only once per session, subsequent triggers skipped
For full event reference, schemas, and examples, see .claude/rules/hooks-reference.md.
  • async: true
    用于命令型钩子:触发后即忽略执行结果,不会阻塞后续操作
  • once: true
    用于任意钩子处理程序:每个会话仅运行一次,后续触发会被跳过
完整的事件参考、模式和示例,请查看.claude/rules/hooks-reference.md

Common Issue: Hook Cancelled Error

常见问题:钩子已取消错误

SessionEnd hook [bash ~/.claude/session-logger.sh] failed: Hook cancelled
Root cause: Hook execution exceeds the configured timeout. With the 2.1.50 default of 10 minutes, this is now less common — but explicitly setting
"timeout"
in your hook config is still recommended.
Solutions (in order of preference):
  1. Background subshell - Run slow operations in background, exit immediately
  2. Explicit timeout - Add
    timeout
    field to hook configuration
SessionEnd hook [bash ~/.claude/session-logger.sh] failed: Hook cancelled
根本原因:钩子执行时间超过配置的超时时间。自2.1.50版本起默认超时为10分钟,这类情况已有所减少,但仍建议在钩子配置中显式设置
"timeout"
解决方案(按优先级排序)
  1. 后台子shell - 将耗时操作放在后台运行,立即退出
  2. 显式设置超时 - 在钩子配置中添加
    timeout
    字段

Hook Configuration

钩子配置

Location

配置位置

Hooks are configured in
.claude/settings.json
:
  • User-level:
    ~/.claude/settings.json
  • Project-level:
    <project>/.claude/settings.json
钩子配置在
.claude/settings.json
中:
  • 用户级
    ~/.claude/settings.json
  • 项目级
    <project>/.claude/settings.json

Structure with Timeout

含超时设置的配置结构

json
{
  "hooks": {
    "SessionEnd": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "~/.claude/session-logger.sh",
            "timeout": 120
          }
        ]
      }
    ],
    "SessionStart": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "~/.claude/session-setup.sh",
            "timeout": 180
          }
        ]
      }
    ],
    "Stop": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "~/.claude/stop-hook-git-check.sh",
            "timeout": 30
          }
        ]
      }
    ]
  }
}
json
{
  "hooks": {
    "SessionEnd": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "~/.claude/session-logger.sh",
            "timeout": 120
          }
        ]
      }
    ],
    "SessionStart": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "~/.claude/session-setup.sh",
            "timeout": 180
          }
        ]
      }
    ],
    "Stop": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "~/.claude/stop-hook-git-check.sh",
            "timeout": 30
          }
        ]
      }
    ]
  }
}

Timeout Guidelines

超时设置指南

Hook TypeRecommended TimeoutUse Case
SessionStart120–300sTests, linters, dependency checks
SessionEnd60–120sLogging, cleanup, state saving
Stop / SubagentStop30–60sGit status checks, quick validations
PreToolUse10–30sQuick validations
PostToolUse30–120sLogging, notifications
PermissionRequest5–15sKeep fast for good UX
钩子类型推荐超时时间适用场景
SessionStart120–300秒测试、代码检查、依赖校验
SessionEnd60–120秒日志记录、清理操作、状态保存
Stop / SubagentStop30–60秒Git状态检查、快速验证
PreToolUse10–30秒快速验证
PostToolUse30–120秒日志记录、通知
PermissionRequest5–15秒保持快速以提升用户体验

Fixing Timeout Issues

解决超时问题

Recommended: Background Subshell Pattern

推荐方案:后台子shell模式

The most portable and robust solution is to run slow operations in a background subshell and exit immediately:
bash
#!/bin/bash
最具可移植性和稳健性的解决方案是将耗时操作放在后台子shell中运行,并立即退出:
bash
#!/bin/bash

~/.claude/session-logger.sh

~/.claude/session-logger.sh

Exits instantly, work continues in background

立即退出,后续操作在后台执行

(

All slow operations go here

echo "$(date): Session ended" >> ~/.claude/session.log curl -s -X POST "https://api.example.com/log" -d "session_end=$(date)"

Any other slow work...

) &>/dev/null &
exit 0

**Why this works:**
- `( )` creates a subshell for the commands
- `&` runs the subshell in background
- `&>/dev/null` prevents stdout/stderr from blocking
- `exit 0` returns success immediately

**Comparison of approaches:**

| Approach | Portability | Speed | Notes |
|----------|-------------|-------|-------|
| `( ) &` | bash, zsh, sh | Instant | Recommended |
| `disown` | Bash-only | Instant | Not POSIX |
| `nohup` | POSIX | Slight overhead | Overkill for hooks |
(

所有耗时操作放在此处

echo "$(date): Session ended" >> ~/.claude/session.log curl -s -X POST "https://api.example.com/log" -d "session_end=$(date)"

其他耗时操作...

) &>/dev/null &
exit 0

**为什么此方案有效**:
- `( )` 为命令创建子shell
- `&` 将子shell放在后台运行
- `&>/dev/null` 避免标准输出/错误阻塞
- `exit 0` 立即返回成功

**方案对比**:

| 方案 | 可移植性 | 速度 | 说明 |
|----------|-------------|-------|-------|
| `( ) &` | bash、zsh、sh均支持 | 即时生效 | 推荐使用 |
| `disown` | 仅支持Bash | 即时生效 | 非POSIX标准 |
| `nohup` | 符合POSIX标准 | 轻微性能开销 | 对于钩子场景过于冗余 |

Alternative: Increase Timeout

替代方案:增加超时时间

If you need synchronous execution, add explicit timeout to settings:
bash
cat ~/.claude/settings.json | jq '.hooks'
如果需要同步执行,可在设置中添加显式超时:
bash
cat ~/.claude/settings.json | jq '.hooks'

Edit to add "timeout": <seconds> to each hook

编辑配置为每个钩子添加"timeout": <秒数>

undefined
undefined

Script Optimization Patterns

脚本优化模式

OptimizationPattern
Background subshell
( commands ) &>/dev/null &
Fast test modes
--bail=1
,
-x
,
--dots
Skip heavy operationsConditional execution
Parallel executionUse
&
and
wait
优化方式实现模式
后台子shell
( commands ) &>/dev/null &
快速测试模式
--bail=1
,
-x
,
--dots
跳过耗时操作条件执行
并行执行使用
&
wait

Related: Starship Timeout

相关问题:Starship超时

If you see:
[WARN] - (starship::utils): Executing command "...node" timed out.
This is a separate starship issue. Fix by adding to
~/.config/starship.toml
:
toml
command_timeout = 1000  # 1 second (default is 500ms)
For slow node version detection:
toml
[nodejs]
disabled = false
detect_files = ["package.json"]  # Skip .nvmrc to speed up detection

[command]
command_timeout = 2000  # Increase if still timing out
如果出现以下提示:
[WARN] - (starship::utils): Executing command "...node" timed out.
这是Starship的独立问题。可通过在
~/.config/starship.toml
中添加以下配置解决:
toml
command_timeout = 1000  # 1秒(默认是500毫秒)
针对缓慢的Node版本检测:
toml
[nodejs]
disabled = false
detect_files = ["package.json"]  # 跳过.nvmrc以加快检测速度

[command]
command_timeout = 2000  # 如果仍超时则继续增加

Agentic Optimizations

Agent相关优化命令

ContextCommand
View hooks config
cat ~/.claude/settings.json | jq '.hooks'
Test hook script
time bash ~/.claude/session-logger.sh
Find slow operations
bash -x ~/.claude/session-logger.sh 2>&1 | head -50
Check starship config
starship config
场景命令
查看钩子配置
cat ~/.claude/settings.json | jq '.hooks'
测试钩子脚本
time bash ~/.claude/session-logger.sh
查找耗时操作
bash -x ~/.claude/session-logger.sh 2>&1 | head -50
检查Starship配置
starship config

Quick Reference

快速参考

SettingLocationDefault
Hook timeout
.claude/settings.json
→ hook →
timeout
10 minutes (600s) since 2.1.50
Starship timeout
~/.config/starship.toml
command_timeout
500ms
Node detection
~/.config/starship.toml
[nodejs]
Auto
设置项位置默认值
钩子超时
.claude/settings.json
→ 钩子 →
timeout
自2.1.50版本起为10分钟(600秒)
Starship超时
~/.config/starship.toml
command_timeout
500毫秒
Node检测
~/.config/starship.toml
[nodejs]
自动检测

Error Handling

错误处理

ErrorCauseFix
Hook cancelledTimeout exceededAdd explicit
"timeout"
(e.g.
"timeout": 120
)
Hook failedScript errorCheck exit code, add error handling
Command not foundMissing scriptVerify script path and permissions
Permission deniedScript not executable
chmod +x ~/.claude/script.sh
错误信息原因解决方法
Hook cancelled执行时间超过超时时间添加显式
"timeout"
配置(例如
"timeout": 120
Hook failed脚本错误检查退出码,添加错误处理逻辑
Command not found脚本不存在验证脚本路径和权限
Permission denied脚本无执行权限
chmod +x ~/.claude/script.sh

Best Practices

最佳实践

  1. Use background subshell - Wrap slow operations in
    ( ) &>/dev/null &
    and
    exit 0
  2. Set explicit timeouts - Add
    timeout
    field for hooks requiring synchronous execution
  3. Test hook timing - Use
    time bash ~/.claude/script.sh
    to measure execution
  4. Redirect all output - Use
    &>/dev/null
    to prevent blocking on stdout/stderr
  5. Apply
    /hooks
    menu
    - Use Claude Code's hook menu to reload settings after changes
  1. 使用后台子shell - 将耗时操作包裹在
    ( ) &>/dev/null &
    中,并执行
    exit 0
  2. 设置显式超时 - 为需要同步执行的钩子添加
    timeout
    字段
  3. 测试钩子执行时间 - 使用
    time bash ~/.claude/script.sh
    测量执行时长
  4. 重定向所有输出 - 使用
    &>/dev/null
    避免因标准输出/错误导致阻塞
  5. 使用
    /hooks
    菜单
    - 修改设置后,使用Claude Code的钩子菜单重新加载配置