Claude Code 生命周期 Hooks 使用指南

概述

Hooks 是用户自定义的脚本/命令,在 Claude Code 的特定生命周期节点自动执行。支持 4 种类型、4 个生命周期事件。


Hook 的 4 种类型

类型 type 字段 说明
Shell 命令 "command" 执行 shell 命令,stdout 作为输出
HTTP 请求 "http" 向指定 URL 发送 POST 请求(含 hook input JSON)
LLM 提示 "prompt" 用 LLM 评估 prompt,返回结构化结果
Agent 验证 "agent" 用 agent 执行验证任务(如检查测试是否通过)

4 个生命周期事件

Setup

在 Claude Code 启动时运行一次,用于项目初始化。

json 复制代码
{
  "hooks": {
    "Setup": [
      {
        "matcher": "",
        "hooks": [
          { "type": "command", "command": "npm install", "timeout": 60 }
        ]
      }
    ]
  }
}

触发时机: 进程启动后、REPL 渲染前 Hook Input 字段:

字段 类型 说明
hook_event_name "Setup" ---
trigger `"init" "maintenance"`
session_id string 当前会话 ID
cwd string 工作目录
transcript_path string 会话日志路径

stdout 处理: ❌ 不注入模型


SessionStart

每次会话开始时 执行。新启动、/resume/clear 后都会触发。stdout 内容作为 system message 注入模型上下文。

json 复制代码
{
  "hooks": {
    "SessionStart": [
      {
        "matcher": "",
        "hooks": [
          { "type": "command", "command": "cat .claude/session-context.md", "timeout": 10 }
        ]
      }
    ]
  }
}

触发时机:

source 场景
startup 进程首次启动
resume --resume/resume 恢复会话
clear /clear
compact 上下文压缩后

Hook Input 字段:

字段 类型 说明
hook_event_name "SessionStart" ---
source `"startup" "resume"
agent_type string (optional) agent 类型
model string (optional) 当前模型

stdout 处理: ✅ 注入为 system message,模型可见


UserPromptSubmit

用户每次提交消息前执行。可以对用户输入做预处理、追加安全检查或上下文。

json 复制代码
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "node scripts/validate-input.js",
            "timeout": 10,
            "statusMessage": "Validating input..."
          }
        ]
      }
    ]
  }
}

Hook Input 字段:

字段 类型 说明
hook_event_name "UserPromptSubmit" ---
prompt string 用户输入的原始文本

stdout 处理: ✅ 注入为 system message,模型可见


SessionEnd

会话结束时 执行(进程退出、/clear)。用于清理资源、记录日志。

json 复制代码
{
  "hooks": {
    "SessionEnd": [
      {
        "matcher": "",
        "hooks": [
          { "type": "command", "command": "node scripts/cleanup.js", "timeout": 5 }
        ]
      }
    ]
  }
}

Hook Input 字段:

字段 类型 说明
hook_event_name "SessionEnd" ---
reason `"clear" "resume"

stdout 处理: ❌ 不注入模型,静默执行

超时控制: 默认 1.5s,可通过 CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS 环境变量配置


Hook 命令通用字段

所有类型的 hook 都支持以下字段:

字段 类型 必填 说明
type `"command" "http" "prompt"
command / prompt / url string 具体命令/prompt/URL(依 type 而异)
timeout number 超时时间(秒)
statusMessage string 执行时 spinner 显示的自定义消息
once boolean 仅执行一次后自动移除
if string 条件过滤(权限规则语法,如 "Bash(git *)"
async boolean 后台异步执行,不阻塞主流程(仅 command 类型)
asyncRewake boolean 后台执行且 exit code 2 时唤醒模型(仅 command 类型,隐含 async)

HTTP 类型特有字段

字段 类型 说明
url string POST 请求目标 URL(hook input 以 JSON body 发送)
headers object 自定义请求头,支持 $VAR 环境变量引用
allowedEnvVars string\[\] 允许在 header 值中插值的环境变量白名单

Prompt 类型特有字段

字段 类型 说明
prompt string LLM 评估 prompt,用 $ARGUMENTS 占位符引用 hook input JSON
model string 使用的模型(默认小模型)

配置位置

hooks 配置在 settings.json 中,支持两级:

用户级(全局生效)

~/.claude/settings.json

json 复制代码
{
  "hooks": {
    "SessionStart": [
      {
        "matcher": "",
        "hooks": [
          { "type": "command", "command": "echo 'Hello from global hook'", "timeout": 5 }
        ]
      }
    ]
  }
}

项目级(仅当前项目)

.claude/settings.json(放在项目根目录):

json 复制代码
{
  "hooks": {
    "Setup": [
      {
        "matcher": "",
        "hooks": [
          { "type": "command", "command": "npm install", "timeout": 120 }
        ]
      }
    ],
    "SessionStart": [
      {
        "matcher": "",
        "hooks": [
          { "type": "command", "command": "cat .claude/instructions.md", "timeout": 5 }
        ]
      }
    ],
    "UserPromptSubmit": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "scripts/lint-check.sh",
            "timeout": 15,
            "if": "Write"
          }
        ]
      }
    ],
    "SessionEnd": [
      {
        "matcher": "",
        "hooks": [
          { "type": "command", "command": "scripts/cleanup.sh", "timeout": 5 }
        ]
      }
    ]
  }
}

实用示例

1. 每次启动加载项目文档

json 复制代码
{
  "hooks": {
    "SessionStart": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "cat .claude/project-guide.md",
            "timeout": 5,
            "statusMessage": "Loading project guide..."
          }
        ]
      }
    ]
  }
}

2. 提交前做代码规范检查

json 复制代码
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "node scripts/check-code-style.js \"$CLAUD_PROMPT\"",
            "timeout": 10
          }
        ]
      }
    ]
  }
}

3. HTTP webhook 通知

json 复制代码
{
  "hooks": {
    "SessionEnd": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "http",
            "url": "https://api.example.com/claude-end",
            "timeout": 5,
            "headers": {
              "Authorization": "Bearer $MY_API_TOKEN"
            },
            "allowedEnvVars": ["MY_API_TOKEN"]
          }
        ]
      }
    ]
  }
}

4. 项目初始化时安装依赖

json 复制代码
{
  "hooks": {
    "Setup": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "test -f package.json && npm install || echo 'No package.json found'",
            "timeout": 120,
            "statusMessage": "Installing dependencies..."
          }
        ]
      }
    ]
  }
}

注意事项

  1. 超时控制timeout 字段以为单位。Setup/SessionStart 默认无严格限制,SessionEnd 默认 1.5s 且被 failsafe(5s)兜底
  2. stdout 注入:SessionStart 和 UserPromptSubmit 的 stdout 会作为 system message 发给模型;Setup 和 SessionEnd 不会
  3. 异步执行async: true 的 command hook 在后台运行,不阻塞主流程。asyncRewake: true 在 exit code 2 时可唤醒模型处理错误
  4. 条件过滤if 字段使用权限规则语法(如 "Bash(git *)""Write"),仅在匹配时执行,避免无关操作触发 hook
  5. once :设置为 true 的 hook 执行一次后自动从配置中移除
  6. 安全 :http hook 的 header 环境变量插值需要显式在 allowedEnvVars 中声明
相关推荐
JavaGuide2 小时前
Claude Code 怎么学?推荐 4 个高质量开源教程,从入门到实战
github·ai编程·claude
解决问题2 小时前
关闭聊天窗口时的处理机制
claude
Resistance丶未来6 小时前
Pixelle-Video:AI全自动短视频引擎 接入API教程
人工智能·大模型·api·claude·deepseek·魔芋ai·pixelle-video
解决问题9 小时前
query.ts 中 message的处理流程
claude
解决问题9 小时前
query.ts 请求参数字段详解
claude
星之尘102110 小时前
Claude Code 安装与 MiniMax 配置指南
ai·agent·claude·minimax·vibe coding
码农小旋风10 小时前
Vibe Coding 工具对比:Cursor、Windsurf、Claude Code 哪款更适合你
gpt·chatgpt·claude
DO_Community10 小时前
Claude Code 的开源替代方案:用 OpenCode + DigitalOcean 实现模型自由
人工智能·开源·agent·claude·deepseek
winlife_1 天前
在 Unity 里用 AI 做游戏:funplay-unity-mcp 从安装到第一次让 AI 改场景
人工智能·游戏·unity·ai编程·claude·mcp