Hooks(钩子)
Hooks 提供了一个可扩展的事件驱动系统,用于自动化响应 agent 命令和事件的操作。Hooks 会自动从目录中发现,并可以通过 CLI 命令进行管理,类似于 OpenClaw 中 skills(技能)的工作方式。
入门指南
Hooks 是在某些事情发生时运行的小脚本。有两种类型:
- Hooks(本页):在 agent 事件触发时在 Gateway 内运行,如 /new、/reset、/stop 或生命周期事件。
- Webhooks:外部 HTTP webhooks,让其他系统在 OpenClaw 中触发工作。参见 Webhook Hooks 或使用 openclaw webhooks 获取 Gmail 助手命令。
Hooks 也可以捆绑在 plugins(插件)内;参见 Plugins。
常见用途:
- 在重置 session(会话)时保存 memory(内存)快照
- 保留命令的审计跟踪以进行故障排查或合规
- 在 session 开始或结束时触发后续自动化
- 在事件触发时将文件写入 agent workspace(工作区)或调用外部 APIs
如果您会编写小型 TypeScript 函数,您就可以编写 hook。Hooks 会自动发现,您可以通过 CLI 启用或禁用它们。
概述
Hooks 系统允许您:
- 在发出 /new 时将 session context(会话上下文)保存到 memory
- 记录所有命令以进行审计
- 在 agent 生命周期事件上触发自定义自动化
- 在不修改核心代码的情况下扩展 OpenClaw 的行为
开始使用
捆绑的 Hooks
OpenClaw 附带四个自动发现的捆绑 hooks:
- 💾 session-memory:在您发出 /new 时将 session context 保存到您的 agent workspace(默认 ~/.openclaw/workspace/memory/)
- 📝 command-logger:将所有命令事件记录到 ~/.openclaw/logs/commands.log
- 🚀 boot-md:在 gateway 启动时运行 BOOT.md(需要启用内部 hooks)
- 😈 soul-evil:在清除窗口期间或随机情况下将注入的 SOUL.md 内容与 SOUL_EVIL.md 交换
列出可用的 hooks:
openclaw hooks list
启用 hook:
openclaw hooks enable session-memory
检查 hook 状态:
openclaw hooks check
获取详细信息:
openclaw hooks info session-memory
Onboarding(入门引导)
在 onboarding(openclaw onboard)期间,系统会提示您启用推荐的 hooks。向导会自动发现符合条件的 hooks 并提供选择。
Hook Discovery(发现)
Hooks 会自动从三个目录发现(按优先级顺序):
- Workspace hooks:<workspace>/hooks/(每个 agent,最高优先级)
- Managed hooks:~/.openclaw/hooks/(用户安装,跨 workspaces 共享)
- Bundled hooks:<openclaw>/dist/hooks/bundled/(OpenClaw 附带)
Managed hook 目录可以是 单个 hook 或 hook pack(钩子包)(package(包)目录)。
每个 hook 是一个包含以下内容的目录:
my-hook/
├── HOOK.md # Metadata(元数据)+ 文档
└── handler.ts # Handler(处理器)实现
Hook Packs (npm/archives)
Hook packs 是标准的 npm packages,通过 package.json 中的 openclaw.hooks 导出一个或多个 hooks。使用以下命令安装:
openclaw hooks install <path-or-spec>
示例 package.json:
{
"name": "@acme/my-hooks",
"version": "0.1.0",
"openclaw": {
"hooks": ["./hooks/my-hook", "./hooks/other-hook"]
}
}
每个条目指向一个包含 HOOK.md 和 handler.ts(或 index.ts)的 hook 目录。 Hook packs 可以附带依赖项;它们将安装在 ~/.openclaw/hooks/<id> 下。
Hook Structure(结构)
HOOK.md 格式
HOOK.md 文件在 YAML frontmatter 中包含 metadata 以及 Markdown 文档:
---
name: my-hook
description: "对这个 hook 功能的简短描述"
homepage: https://docs.openclaw.ai/hooks#my-hook
metadata: {"openclaw":{"emoji":"🔗","events":["command:new"],"requires":{"bins":["node"]}}}
---
# My Hook
详细文档在这里...
## What It Does
- 监听 `/new` 命令
- 执行某些操作
- 记录结果
## Requirements
- 必须安装 Node.js
## Configuration
无需配置。
Metadata 字段
metadata.openclaw 对象支持:
- emoji:CLI 的显示 emoji(例如 "💾")
- events:要监听的事件数组(例如 ["command:new", "command:reset"])
- export:要使用的命名导出(默认为 "default")
- homepage:文档 URL
- requires:可选要求
- bins:PATH 上所需的二进制文件(例如 ["git", "node"])
- anyBins:必须存在这些二进制文件中的至少一个
- env:所需的环境变量
- config:所需的配置路径(例如 ["workspace.dir"])
- os:所需平台(例如 ["darwin", "linux"])
- always:绕过资格检查(boolean(布尔值))
- install:安装方法(对于捆绑 hooks:[{"id":"bundled","kind":"bundled"}])
Handler Implementation(实现)
handler.ts 文件导出一个 HookHandler 函数:
import type { HookHandler } from '../../src/hooks/hooks.js';
const myHandler: HookHandler = async (event) => {
// 仅在 'new' 命令时触发
if (event.type !== 'command' || event.action !== 'new') {
return;
}
console.log(`[my-hook] New command triggered`);
console.log(` Session: ${event.sessionKey}`);
console.log(` Timestamp: ${event.timestamp.toISOString()}`);
// 您的自定义逻辑在这里
// 可选地向用户发送消息
event.messages.push('✨ My hook executed!');
};
export default myHandler;
Event Context(事件上下文)
每个事件包括:
{
type: 'command' | 'session' | 'agent' | 'gateway',
action: string, // 例如 'new'、'reset'、'stop'
sessionKey: string, // Session 标识符
timestamp: Date, // 事件发生时间
messages: string[], // 在这里推送消息以发送给用户
context: {
sessionEntry?: SessionEntry,
sessionId?: string,
sessionFile?: string,
commandSource?: string, // 例如 'whatsapp'、'telegram'
senderId?: string,
workspaceDir?: string,
bootstrapFiles?: WorkspaceBootstrapFile[],
cfg?: OpenClawConfig
}
}
Event Types(事件类型)
Command Events(命令事件)
在发出 agent 命令时触发:
- command:所有命令事件(通用监听器)
- command:new:发出 /new 命令时
- command:reset:发出 /reset 命令时
- command:stop:发出 /stop 命令时
Agent Events(Agent 事件)
- agent:bootstrap:在注入 workspace bootstrap 文件之前(hooks 可能改变 context.bootstrapFiles)
Gateway Events(Gateway 事件)
在 gateway 启动时触发:
- gateway:startup:在 channels 启动和 hooks 加载后
Tool Result Hooks (Plugin API)
这些 hooks 不是事件流监听器;它们让 plugins 在 OpenClaw 持久化 tool results(工具结果)之前同步调整它们。
- tool_result_persist:在将 tool results 写入 session transcript(会话记录)之前对其进行转换。必须是同步的;返回更新的 tool result payload(载荷)或 undefined 以保持原样。参见 Agent Loop。
Future Events(未来事件)
计划的事件类型:
- session:start:当新 session 开始时
- session:end:当 session 结束时
- agent:error:当 agent 遇到错误时
- message:sent:当消息发送时
- message:received:当消息接收时
Creating Custom Hooks(创建自定义 Hooks)
1. 选择位置
- Workspace hooks(<workspace>/hooks/):每个 agent,最高优先级
- Managed hooks(~/.openclaw/hooks/):跨 workspaces 共享
2. 创建目录结构
mkdir -p ~/.openclaw/hooks/my-hook
cd ~/.openclaw/hooks/my-hook
3. 创建 HOOK.md
---
name: my-hook
description: "做一些有用的事情"
metadata: {"openclaw":{"emoji":"🎯","events":["command:new"]}}
---
# My Custom Hook
这个 hook 在您发出 `/new` 时做一些有用的事情。
4. 创建 handler.ts
import type { HookHandler } from '../../src/hooks/hooks.js';
const handler: HookHandler = async (event) => {
if (event.type !== 'command' || event.action !== 'new') {
return;
}
console.log('[my-hook] Running!');
// 您的逻辑在这里
};
export default handler;
5. 启用并测试
# 验证 hook 已被发现
openclaw hooks list
# 启用它
openclaw hooks enable my-hook
# 重启您的 gateway 进程(macOS 上的菜单栏应用重启,或重启您的开发进程)
# 触发事件
# 通过您的消息 channel 发送 /new
Configuration(配置)
新配置格式(推荐)
{
"hooks": {
"internal": {
"enabled": true,
"entries": {
"session-memory": { "enabled": true },
"command-logger": { "enabled": false }
}
}
}
}
每个 Hook 的配置
Hooks 可以有自定义配置:
{
"hooks": {
"internal": {
"enabled": true,
"entries": {
"my-hook": {
"enabled": true,
"env": {
"MY_CUSTOM_VAR": "value"
}
}
}
}
}
}
额外目录
从额外目录加载 hooks:
{
"hooks": {
"internal": {
"enabled": true,
"load": {
"extraDirs": ["/path/to/more/hooks"]
}
}
}
}
Legacy Config Format(仍受支持)
旧的配置格式仍然适用于向后兼容:
{
"hooks": {
"internal": {
"enabled": true,
"handlers": [
{
"event": "command:new",
"module": "./hooks/handlers/my-handler.ts",
"export": "default"
}
]
}
}
}
迁移:为新 hooks 使用基于发现的新系统。Legacy handlers(传统处理器)在基于目录的 hooks 之后加载。
CLI Commands(CLI 命令)
List Hooks(列出 Hooks)
# 列出所有 hooks
openclaw hooks list
# 仅显示符合条件的 hooks
openclaw hooks list --eligible
# 详细输出(显示缺少的要求)
openclaw hooks list --verbose
# JSON 输出
openclaw hooks list --json
Hook Information(Hook 信息)
# 显示有关 hook 的详细信息
openclaw hooks info session-memory
# JSON 输出
openclaw hooks info session-memory --json
Check Eligibility(检查资格)
# 显示资格摘要
openclaw hooks check
# JSON 输出
openclaw hooks check --json
Enable/Disable(启用/禁用)
# 启用 hook
openclaw hooks enable session-memory
# 禁用 hook
openclaw hooks disable command-logger
Bundled Hooks(捆绑的 Hooks)
session-memory
在您发出 /new 时将 session context 保存到 memory。
Events:command:new
Requirements:必须配置 workspace.dir
Output:<workspace>/memory/YYYY-MM-DD-slug.md(默认为 ~/.openclaw/workspace)
它的作用:
- 使用重置前的 session entry 来定位正确的 transcript(记录)
- 提取对话的最后 15 行
- 使用 LLM 生成描述性的文件名 slug
- 将 session metadata 保存到日期记录文件
输出示例:
# Session: 2026-01-16 14:30:00 UTC
- **Session Key**: agent:main:main
- **Session ID**: abc123def456
- **Source**: telegram
文件名示例:
- 2026-01-16-vendor-pitch.md
- 2026-01-16-api-design.md
- 2026-01-16-1430.md(如果 slug 生成失败则回退到 timestamp(时间戳))
启用:
openclaw hooks enable session-memory
command-logger
将所有命令事件记录到集中式审计文件。
Events:command
Requirements:无
Output:~/.openclaw/logs/commands.log
它的作用:
- 捕获事件详细信息(命令操作、时间戳、session key、sender ID、source)
- 以 JSONL 格式附加到日志文件
- 在后台静默运行
日志条目示例:
{"timestamp":"2026-01-16T14:30:00.000Z","action":"new","sessionKey":"agent:main:main","senderId":"+1234567890","source":"telegram"}
{"timestamp":"2026-01-16T15:45:22.000Z","action":"stop","sessionKey":"agent:main:main","senderId":"[email protected]","source":"whatsapp"}
查看日志:
# 查看最近的命令
tail -n 20 ~/.openclaw/logs/commands.log
# 使用 jq 格式化输出
cat ~/.openclaw/logs/commands.log | jq .
# 按操作过滤
grep '"action":"new"' ~/.openclaw/logs/commands.log | jq .
启用:
openclaw hooks enable command-logger
soul-evil
在清除窗口期间或随机情况下将注入的 SOUL.md 内容与 SOUL_EVIL.md 交换。
Events:agent:bootstrap
Docs:SOUL Evil Hook
Output:不写入文件;交换仅在内存中发生。
启用:
openclaw hooks enable soul-evil
Config:
{
"hooks": {
"internal": {
"enabled": true,
"entries": {
"soul-evil": {
"enabled": true,
"file": "SOUL_EVIL.md",
"chance": 0.1,
"purge": { "at": "21:00", "duration": "15m" }
}
}
}
}
}
boot-md
在 gateway 启动时运行 BOOT.md(在 channels 启动后)。 必须启用内部 hooks 才能运行。
Events:gateway:startup
Requirements:必须配置 workspace.dir
它的作用:
- 从您的 workspace 读取 BOOT.md
- 通过 agent runner 运行指令
- 通过 message tool 发送任何请求的出站消息
启用:
openclaw hooks enable boot-md
Best Practices(最佳实践)
保持 Handlers 快速
Hooks 在命令处理期间运行。保持它们轻量级:
// ✓ 好 - 异步工作,立即返回
const handler: HookHandler = async (event) => {
void processInBackground(event); // Fire and forget(发射后不管)
};
// ✗ 坏 - 阻塞命令处理
const handler: HookHandler = async (event) => {
await slowDatabaseQuery(event);
await evenSlowerAPICall(event);
};
优雅地处理错误
始终包装有风险的操作:
const handler: HookHandler = async (event) => {
try {
await riskyOperation(event);
} catch (err) {
console.error('[my-handler] Failed:', err instanceof Error ? err.message : String(err));
// 不要抛出 - 让其他 handlers 运行
}
};
尽早过滤事件
如果事件不相关,尽早返回:
const handler: HookHandler = async (event) => {
// 仅处理 'new' 命令
if (event.type !== 'command' || event.action !== 'new') {
return;
}
// 您的逻辑在这里
};
使用特定事件键
在 metadata 中尽可能指定确切的事件:
metadata: {"openclaw":{"events":["command:new"]}} # 具体
而不是:
metadata: {"openclaw":{"events":["command"]}} # 通用 - 更多开销
Debugging(调试)
启用 Hook Logging(日志记录)
Gateway 在启动时记录 hook 加载:
Registered hook: session-memory -> command:new
Registered hook: command-logger -> command
Registered hook: boot-md -> gateway:startup
检查 Discovery
列出所有发现的 hooks:
openclaw hooks list --verbose
检查 Registration(注册)
在您的 handler 中,记录它何时被调用:
const handler: HookHandler = async (event) => {
console.log('[my-handler] Triggered:', event.type, event.action);
// 您的逻辑
};
验证资格
检查为什么 hook 不符合条件:
openclaw hooks info my-hook
在输出中查找缺少的要求。
Testing(测试)
Gateway Logs
监视 gateway 日志以查看 hook 执行:
# macOS
./scripts/clawlog.sh -f
# 其他平台
tail -f ~/.openclaw/gateway.log
直接测试 Hooks
单独测试您的 handlers:
import { test } from 'vitest';
import { createHookEvent } from './src/hooks/hooks.js';
import myHandler from './hooks/my-hook/handler.js';
test('my handler works', async () => {
const event = createHookEvent('command', 'new', 'test-session', {
foo: 'bar'
});
await myHandler(event);
// 断言副作用
});
Architecture(架构)
Core Components(核心组件)
- src/hooks/types.ts:类型定义
- src/hooks/workspace.ts:目录扫描和加载
- src/hooks/frontmatter.ts:HOOK.md metadata 解析
- src/hooks/config.ts:资格检查
- src/hooks/hooks-status.ts:状态报告
- src/hooks/loader.ts:动态模块加载器
- src/cli/hooks-cli.ts:CLI 命令
- src/gateway/server-startup.ts:在 gateway 启动时加载 hooks
- src/auto-reply/reply/commands-core.ts:触发命令事件
Discovery Flow(发现流程)
Gateway 启动
↓
扫描目录(workspace → managed → bundled)
↓
解析 HOOK.md 文件
↓
检查资格(bins、env、config、os)
↓
从符合条件的 hooks 加载 handlers
↓
为事件注册 handlers
Event Flow(事件流程)
用户发送 /new
↓
命令验证
↓
创建 hook 事件
↓
触发 hook(所有已注册的 handlers)
↓
命令处理继续
↓
Session 重置
Troubleshooting(故障排查)
Hook Not Discovered(Hook 未被发现)
-
检查目录结构:
ls -la ~/.openclaw/hooks/my-hook/ # 应该显示:HOOK.md、handler.ts -
验证 HOOK.md 格式:
cat ~/.openclaw/hooks/my-hook/HOOK.md # 应该有包含 name 和 metadata 的 YAML frontmatter -
列出所有发现的 hooks:
openclaw hooks list
Hook Not Eligible(Hook 不符合条件)
检查要求:
openclaw hooks info my-hook
查找缺少的:
- Binaries(二进制文件)(检查 PATH)
- Environment variables(环境变量)
- Config values(配置值)
- OS compatibility(操作系统兼容性)
Hook Not Executing(Hook 未执行)
-
验证 hook 已启用:
openclaw hooks list # 应该在已启用的 hooks 旁边显示 ✓ -
重启您的 gateway 进程以便 hooks 重新加载。
-
检查 gateway 日志以查找错误:
./scripts/clawlog.sh | grep hook
Handler Errors(Handler 错误)
检查 TypeScript/import 错误:
# 直接测试 import
node -e "import('./path/to/handler.ts').then(console.log)"
Migration Guide(迁移指南)
从 Legacy Config 到 Discovery
之前:
{
"hooks": {
"internal": {
"enabled": true,
"handlers": [
{
"event": "command:new",
"module": "./hooks/handlers/my-handler.ts"
}
]
}
}
}
之后:
-
创建 hook 目录:
mkdir -p ~/.openclaw/hooks/my-hook mv ./hooks/handlers/my-handler.ts ~/.openclaw/hooks/my-hook/handler.ts -
创建 HOOK.md:
--- name: my-hook description: "我的自定义 hook" metadata: {"openclaw":{"emoji":"🎯","events":["command:new"]}} --- # My Hook 做一些有用的事情。 -
更新配置:
{ "hooks": { "internal": { "enabled": true, "entries": { "my-hook": { "enabled": true } } } } } -
验证并重启您的 gateway 进程:
openclaw hooks list # 应该显示:🎯 my-hook ✓
迁移的好处:
- 自动发现
- CLI 管理
- 资格检查
- 更好的文档
- 一致的结构