Claude Code中生命周期Hooks的使用指南介绍

  发布时间:2026-06-04 09:11:58   作者:解决问题   我要评论
Hooks 是用户自定义的脚本/命令,在 Claude Code 的特定生命周期节点自动执行,支持 4 种类型、4 个生命周期事件,下面小编就和大家详细介绍一下Hook这四种类型的具体使用吧

概述

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 启动时运行一次,用于项目初始化。

{
  "hooks": {
    "Setup": [
      {
        "matcher": "",
        "hooks": [
          { "type": "command", "command": "npm install", "timeout": 60 }
        ]
      }
    ]
  }
}

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

字段类型说明
hook_event_name"Setup"
trigger"init" | "maintenance"触发来源
session_idstring当前会话 ID
cwdstring工作目录
transcript_pathstring会话日志路径

stdout 处理: ❌ 不注入模型

SessionStart

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

{
  "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" | "clear" | "compact"触发来源
agent_typestring (optional)agent 类型
modelstring (optional)当前模型

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

UserPromptSubmit

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

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

Hook Input 字段:

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

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

SessionEnd

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

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

Hook Input 字段:

字段类型说明
hook_event_name"SessionEnd"
reason"clear" | "resume" | "logout" | "prompt_input_exit" | "other"结束原因

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

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

Hook 命令通用字段

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

字段类型必填说明
type"command" | "http" | "prompt" | "agent"Hook 类型
command / prompt / urlstring具体命令/prompt/URL(依 type 而异)
timeoutnumber超时时间(秒)
statusMessagestring执行时 spinner 显示的自定义消息
onceboolean仅执行一次后自动移除
ifstring条件过滤(权限规则语法,如 "Bash(git *)"
asyncboolean后台异步执行,不阻塞主流程(仅 command 类型)
asyncRewakeboolean后台执行且 exit code 2 时唤醒模型(仅 command 类型,隐含 async)

HTTP 类型特有字段

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

Prompt 类型特有字段

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

配置位置

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

用户级(全局生效)

~/.claude/settings.json

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

项目级(仅当前项目)

.claude/settings.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. 每次启动加载项目文档

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

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

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

3. HTTP webhook 通知

{
  "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. 项目初始化时安装依赖

{
  "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 中声明

以上就是Claude Code中生命周期Hooks的使用指南介绍的详细内容,更多关于Claude Code生命周期Hooks的资料请关注脚本之家其它相关文章!

相关文章

  • Claude Code Hooks 选装实战指南

    Claudede Hooks实战指南,涵盖三级拦截体系,两脚本开箱即用,覆盖致命、高风险、警告三级操作,通过配置settings.json灵活定制拦截策略,支持PowerShell与原生Toast通知,适用于
    2026-06-03
  • 一文详解Claude Code中Hooks的使用

    Claude Code 每次调用工具、等待输入、结束会话,都会触发对应的Hook生命周期事件,Hook 脚本除了做判断和记录,还可以把事件转发到本地 socket,让一个常驻进程处理所有状
    2026-06-02

最新评论