claude-hooks-configuration
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseClaude 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
钩子事件
| Hook | Trigger | Default Timeout |
|---|---|---|
| When Claude Code session begins | 600s (command) |
| When session ends or | 600s (command) |
| When main agent stops responding | 600s (command) |
| When a subagent (Task tool) finishes | 600s (command) |
| Before a tool executes | 600s (command) |
| After a tool completes | 600s (command) |
| After a tool execution fails | 600s (command) |
| When Claude requests permission for a tool | 600s (command) |
| New git worktree created via EnterWorktree | 600s (command) |
| Worktree removed after session exits | 600s (command) |
| Teammate in agent team goes idle | 600s (command) |
| Task in shared task list marked complete | 600s (command) |
| Claude Code settings change at runtime | 600s (command) |
Default timeouts: = 600s, = 30s, = 60s. Always set explicit timeouts — it documents intent.
commandpromptagent| 钩子 | 触发时机 | 默认超时时间 |
|---|---|---|
| 当Claude Code会话开始时 | 600秒(command类型) |
| 当会话结束或执行 | 600秒(command类型) |
| 当主Agent停止响应时 | 600秒(command类型) |
| 当子Agent(任务工具)完成时 | 600秒(command类型) |
| 工具执行前 | 600秒(command类型) |
| 工具完成后 | 600秒(command类型) |
| 工具执行失败后 | 600秒(command类型) |
| 当Claude请求工具权限时 | 600秒(command类型) |
| 通过EnterWorktree创建新的git工作树时 | 600秒(command类型) |
| 会话退出后删除工作树时 | 600秒(command类型) |
| Agent团队中的成员进入空闲状态时 | 600秒(command类型) |
| 共享任务列表中的任务标记为完成时 | 600秒(command类型) |
| 运行时修改Claude Code设置时 | 600秒(command类型) |
默认超时时间:=600秒,=30秒,=60秒。建议始终显式设置超时时间,以明确配置意图。
commandpromptagentHook Types
钩子类型
| Type | How It Works | Default Timeout | Use When |
|---|---|---|---|
| Runs a shell command, reads stdin, returns exit code/JSON | 600s | Deterministic rules |
| Sends hook data to an HTTPS endpoint | 30s | Remote/centralized policy |
| Single-turn LLM call, returns | 30s | Judgment on hook input data |
| Multi-turn subagent with tool access, returns | 60s | Verification needing file/tool access |
| 类型 | 工作机制 | 默认超时时间 | 适用场景 |
|---|---|---|---|
| 执行shell命令,读取标准输入,返回退出码/JSON | 600秒 | 确定性规则场景 |
| 将钩子数据发送至HTTPS端点 | 30秒 | 远程/集中式策略场景 |
| 单轮LLM调用,返回 | 30秒 | 对钩子输入数据进行判断的场景 |
| 具备工具访问权限的多轮子Agent,返回 | 60秒 | 需要访问文件/工具进行验证的场景 |
Async and Once
异步与单次执行
- on command hooks: fire-and-forget, does not block the operation
async: true - on any hook handler: runs only once per session, subsequent triggers skipped
once: true
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 cancelledRoot cause: Hook execution exceeds the configured timeout. With the 2.1.50 default of 10 minutes, this is now less common — but explicitly setting in your hook config is still recommended.
"timeout"Solutions (in order of preference):
- Background subshell - Run slow operations in background, exit immediately
- Explicit timeout - Add field to hook configuration
timeout
SessionEnd hook [bash ~/.claude/session-logger.sh] failed: Hook cancelled根本原因:钩子执行时间超过配置的超时时间。自2.1.50版本起默认超时为10分钟,这类情况已有所减少,但仍建议在钩子配置中显式设置。
"timeout"解决方案(按优先级排序):
- 后台子shell - 将耗时操作放在后台运行,立即退出
- 显式设置超时 - 在钩子配置中添加字段
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 Type | Recommended Timeout | Use Case |
|---|---|---|
| SessionStart | 120–300s | Tests, linters, dependency checks |
| SessionEnd | 60–120s | Logging, cleanup, state saving |
| Stop / SubagentStop | 30–60s | Git status checks, quick validations |
| PreToolUse | 10–30s | Quick validations |
| PostToolUse | 30–120s | Logging, notifications |
| PermissionRequest | 5–15s | Keep fast for good UX |
| 钩子类型 | 推荐超时时间 | 适用场景 |
|---|---|---|
| SessionStart | 120–300秒 | 测试、代码检查、依赖校验 |
| SessionEnd | 60–120秒 | 日志记录、清理操作、状态保存 |
| Stop / SubagentStop | 30–60秒 | Git状态检查、快速验证 |
| PreToolUse | 10–30秒 | 快速验证 |
| PostToolUse | 30–120秒 | 日志记录、通知 |
| PermissionRequest | 5–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": <秒数>
undefinedundefinedScript Optimization Patterns
脚本优化模式
| Optimization | Pattern |
|---|---|
| Background subshell | |
| Fast test modes | |
| Skip heavy operations | Conditional execution |
| Parallel execution | Use |
| 优化方式 | 实现模式 |
|---|---|
| 后台子shell | |
| 快速测试模式 | |
| 跳过耗时操作 | 条件执行 |
| 并行执行 | 使用 |
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.tomltoml
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.tomltoml
command_timeout = 1000 # 1秒(默认是500毫秒)针对缓慢的Node版本检测:
toml
[nodejs]
disabled = false
detect_files = ["package.json"] # 跳过.nvmrc以加快检测速度
[command]
command_timeout = 2000 # 如果仍超时则继续增加Agentic Optimizations
Agent相关优化命令
| Context | Command |
|---|---|
| View hooks config | |
| Test hook script | |
| Find slow operations | |
| Check starship config | |
| 场景 | 命令 |
|---|---|
| 查看钩子配置 | |
| 测试钩子脚本 | |
| 查找耗时操作 | |
| 检查Starship配置 | |
Quick Reference
快速参考
| Setting | Location | Default |
|---|---|---|
| Hook timeout | | 10 minutes (600s) since 2.1.50 |
| Starship timeout | | 500ms |
| Node detection | | Auto |
| 设置项 | 位置 | 默认值 |
|---|---|---|
| 钩子超时 | | 自2.1.50版本起为10分钟(600秒) |
| Starship超时 | | 500毫秒 |
| Node检测 | | 自动检测 |
Error Handling
错误处理
| Error | Cause | Fix |
|---|---|---|
| Hook cancelled | Timeout exceeded | Add explicit |
| Hook failed | Script error | Check exit code, add error handling |
| Command not found | Missing script | Verify script path and permissions |
| Permission denied | Script not executable | |
| 错误信息 | 原因 | 解决方法 |
|---|---|---|
| Hook cancelled | 执行时间超过超时时间 | 添加显式 |
| Hook failed | 脚本错误 | 检查退出码,添加错误处理逻辑 |
| Command not found | 脚本不存在 | 验证脚本路径和权限 |
| Permission denied | 脚本无执行权限 | |
Best Practices
最佳实践
- Use background subshell - Wrap slow operations in and
( ) &>/dev/null &exit 0 - Set explicit timeouts - Add field for hooks requiring synchronous execution
timeout - Test hook timing - Use to measure execution
time bash ~/.claude/script.sh - Redirect all output - Use to prevent blocking on stdout/stderr
&>/dev/null - Apply menu - Use Claude Code's hook menu to reload settings after changes
/hooks
- 使用后台子shell - 将耗时操作包裹在中,并执行
( ) &>/dev/null &exit 0 - 设置显式超时 - 为需要同步执行的钩子添加字段
timeout - 测试钩子执行时间 - 使用测量执行时长
time bash ~/.claude/script.sh - 重定向所有输出 - 使用避免因标准输出/错误导致阻塞
&>/dev/null - 使用菜单 - 修改设置后,使用Claude Code的钩子菜单重新加载配置
/hooks