hooks
设计理念
问题
解决方案
事件发生 → 触发 Hook → 执行操作事件发生 → 触发 Hook → 执行操作{
"name": "Lint on Save",
"version": "1.0.0",
"description": "Run linter when TypeScript files are saved",
"when": {
"type": "fileEdited",
"patterns": ["*.ts", "*.tsx"]
},
"then": {
"type": "runCommand",
"command": "npm run lint"
}
}interface Hook {
name: string;
version: string;
description?: string;
when: HookTrigger;
then: HookAction;
}
type HookTrigger =
| { type: 'fileEdited'; patterns: string[] }
| { type: 'fileCreated'; patterns: string[] }
| { type: 'fileDeleted'; patterns: string[] }
| { type: 'promptSubmit' }
| { type: 'agentStop' }
| { type: 'preToolUse'; toolTypes: string[] }
| { type: 'postToolUse'; toolTypes: string[] }
| { type: 'userTriggered' };
type HookAction =
| { type: 'askAgent'; prompt: string }
| { type: 'runCommand'; command: string; timeout?: number };{
"when": {
"type": "fileEdited",
"patterns": ["*.ts", "*.tsx"]
},
"then": {
"type": "runCommand",
"command": "npm run lint"
}
}{
"when": {
"type": "fileCreated",
"patterns": ["*.test.ts"]
},
"then": {
"type": "askAgent",
"prompt": "Add test template to the new file"
}
}{
"when": {
"type": "fileDeleted",
"patterns": ["*.ts"]
},
"then": {
"type": "askAgent",
"prompt": "Check if any imports need to be updated"
}
}{
"when": {
"type": "promptSubmit"
},
"then": {
"type": "runCommand",
"command": "git status"
}
}{
"when": {
"type": "agentStop"
},
"then": {
"type": "runCommand",
"command": "npm run test"
}
}{
"when": {
"type": "preToolUse",
"toolTypes": ["write"]
},
"then": {
"type": "askAgent",
"prompt": "Verify this write operation is safe"
}
}{
"when": {
"type": "postToolUse",
"toolTypes": ["write"]
},
"then": {
"type": "runCommand",
"command": "git add -A"
}
}{
"type": "askAgent",
"prompt": "Review the changes and suggest improvements"
}{
"type": "runCommand",
"command": "npm run lint",
"timeout": 30000
}await createHook({
id: 'format-on-save',
name: 'Format on Save',
description: 'Auto-format code when files are saved',
eventType: 'fileEdited',
filePatterns: '*.ts,*.tsx',
hookAction: 'runCommand',
command: 'npm run format',
why: 'Ensure consistent code formatting',
});// .kiro/hooks/my-hook.json
{
"name": "My Hook",
"version": "1.0.0",
"when": {
"type": "fileEdited",
"patterns": ["*.ts"]
},
"then": {
"type": "runCommand",
"command": "npm run lint"
}
}# 在 Kiro 中查看
Explorer → Agent Hooks
# 或使用命令
claude-code hooks list{
"name": "My Hook",
"enabled": false, // 禁用 Hook
"when": { ... },
"then": { ... }
}{
"name": "Test on Save",
"when": {
"type": "fileEdited",
"patterns": ["src/**/*.ts"]
},
"then": {
"type": "runCommand",
"command": "npm run test -- --related"
}
}{
"name": "Review Changes",
"when": {
"type": "postToolUse",
"toolTypes": ["write"]
},
"then": {
"type": "askAgent",
"prompt": "Review the changes for potential issues"
}
}{
"name": "Auto Commit",
"when": {
"type": "agentStop"
},
"then": {
"type": "runCommand",
"command": "git add -A && git commit -m 'Auto commit'"
}
}