SessionEnd
SessionEnd 在 Hawa Code 会话终止时触发。适用于执行清理任务、记录会话统计信息或保存会话状态。
注意:由于 SessionEnd 在会话终止时触发,它无法阻塞会话结束,仅支持 type: "command" 类型的 hook。
关键特性
| 属性 |
说明 |
| 触发时机 |
会话终止时 |
| 能否阻塞 |
否 - 无法阻止会话终止 |
| 支持的 Hook 类型 |
仅支持 command |
| 决策控制 |
无 - 仅用于副作用(日志记录、清理等) |
Matcher 支持
SessionEnd 支持使用 matcher 按会话结束原因进行过滤:
| Matcher |
触发时机 |
clear |
使用 /clear 命令清除会话时 |
other |
其他退出原因(正常退出、异常退出等) |
* |
匹配所有结束原因 |
输入参数
| 字段 |
类型 |
说明 |
session_id |
string |
会话唯一标识符 |
transcript_path |
string |
对话 JSON 文件的完整路径 |
cwd |
string |
当前工作目录 |
permission_mode |
string |
当前权限模式 |
hook_event_name |
string |
固定为 "SessionEnd" |
reason |
string |
会话结束原因:"clear" 或 "other" |
输入示例:
{ "session_id": "abc123", "transcript_path": "/Users/.../.hcode/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", "cwd": "/Users/...", "permission_mode": "default", "hook_event_name": "SessionEnd", "reason": "other" }
|
输出参数
SessionEnd hook 无特定输出要求。脚本的标准输出和错误输出将被记录,但不会影响会话终止流程。
配置示例
基础清理 Hook(匹配所有结束原因)
{ "hooks": { "SessionEnd": [ { "matcher": "*", "hooks": [ { "type": "command", "command": "node ./hooks/session-end.js" } ] } ] } }
|
脚本示例(./hooks/session-end.js):
const fs = require('fs');
const input = fs.readFileSync(0, 'utf-8'); const params = JSON.parse(input);
const sessionId = params.session_id; const reason = params.reason;
const stats = { sessionId: sessionId, endTime: new Date().toISOString(), reason: reason, transcriptPath: params.transcript_path };
fs.appendFileSync( './logs/session-stats.log', JSON.stringify(stats) + '\n' );
console.error(`[SessionEnd] 会话 ${sessionId} 已结束,原因: ${reason}`); process.exit(0);
|
匹配特定退出原因(仅在 /clear 时执行)
{ "hooks": { "SessionEnd": [ { "matcher": "clear", "hooks": [ { "type": "command", "command": "rm -f /tmp/claude-scratch-*.txt" } ] } ] } }
|
多 Matcher 配置
{ "hooks": { "SessionEnd": [ { "matcher": "clear", "hooks": [ { "type": "command", "command": "echo '会话被清除' >> ./logs/cleanup.log" } ] }, { "matcher": "other", "hooks": [ { "type": "command", "command": "node ./hooks/normal-exit.js" } ] } ] } }
|