Claude 代码钩子:它们是什么以及我实际如何使用它们

📄 中文摘要

Claude 代码钩子允许在会话生命周期的特定时刻运行脚本,包括工具运行前、运行后、会话开始时和会话结束时。这些钩子功能强大但使用不足。四个主要钩子点包括:PreToolUse,在工具执行之前运行,适合进行日志记录、验证和成本跟踪;PostToolUse,在工具完成后运行,适合进行自动格式化、文件编辑后的测试运行和任务日志更新;SessionStart,在会话打开时运行,适合加载状态、读取任务文件和打印状态摘要;SessionEnd,在会话关闭时运行,但需注意如果容器意外终止,这个钩子可能不会被触发。

📄 English Summary

Claude Code hooks: what they are and what I actually use them for

Claude code hooks allow scripts to be executed at specific points in the session lifecycle, including before a tool runs, after it runs, at session start, and at session end. These hooks are powerful yet underutilized. The four main hook points include: PreToolUse, which runs before a tool executes and is useful for logging, validation, and cost tracking; PostToolUse, which runs after a tool completes and is suitable for auto-formatting, running tests after file edits, and updating a task log; SessionStart, which runs when a session opens and is good for loading state, reading the task file, and printing a status summary; and SessionEnd, which runs when a session closes, but care must be taken as it may not fire if the container is killed unexpectedly.

Powered by Cloudflare Workers + Payload CMS + Claude 3.5

数据源: OpenAI, Google AI, DeepMind, AWS ML Blog, HuggingFace 等