名称: 钩子 描述: 钩子开发规则 用户可调用: false
钩子开发规则
当处理 .claude/hooks/ 目录中的文件时:
模式
Shell包装器 (.sh) → TypeScript (.ts) 通过 npx tsx
Shell包装器模板
#!/bin/bash
set -e
cd "$CLAUDE_PROJECT_DIR/.claude/hooks"
cat | npx tsx <handler>.ts
TypeScript处理器模式
interface HookInput {
// 事件特定字段
}
async function main() {
const input: HookInput = JSON.parse(await readStdin());
// 处理输入
const output = {
result: 'continue', // 或 'block'
message: '可选系统提醒'
};
console.log(JSON.stringify(output));
}
钩子事件
- PreToolUse - 工具执行前(可以阻止)
- PostToolUse - 工具执行后
- UserPromptSubmit - 处理用户提示前
- PreCompact - 上下文压缩前
- SessionStart - 会话开始/恢复/压缩时
- Stop - 代理完成时
测试
手动测试钩子:
echo '{"type": "resume"}' | .claude/hooks/session-start-continuity.sh
注册
添加钩子到 .claude/settings.json:
{
"hooks": {
"EventName": [{
"matcher": ["pattern"], // 可选
"hooks": [{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/hook.sh"
}]
}]
}
}