钩子
钩子提供了一个可扩展的事件驱动系统,用于自动化响应智能体命令和事件的操作。钩子从目录中自动发现,可以通过 CLI 命令进行管理,类似于 openclaw 中技能的工作方式。
入门指南
钩子是在某些事件发生时运行的小脚本。有两种类型:
- 钩子(本页):在网关内部运行,当智能体事件触发时,如
/new、/reset、/stop或生命周期事件。 - Webhooks:外部 HTTP webhooks,允许其他系统在 openclaw 中触发工作。请参阅 Webhook 钩子 或使用
openclaw webhooks获取 Gmail 辅助命令。
钩子也可以捆绑在插件内部;请参阅 插件。
常见用途:
- 重置会话时保存内存快照
- 保留命令审计跟踪以进行故障排除或合规性检查
- 会话开始或结束时触发后续自动化
- 事件触发时将文件写入智能体工作空间或调用外部 API
如果您能编写一个小的 TypeScript 函数,您就能编写一个钩子。钩子会自动发现,您可以通过 CLI 启用或禁用它们。
概述
钩子系统允许您:
- 发出
/new命令时将会话上下文保存到内存 - 记录所有命令以进行审计
- 在智能体生命周期事件上触发自定义自动化
- 无需修改核心代码即可扩展 openclaw 的行为
开始使用
捆绑钩子
openclaw 附带四个自动发现的捆绑钩子:
- 💾 session-memory:发出
/new命令时将会话上下文保存到您的智能体工作空间(默认~/clawd/memory/) - 📝 command-logger:将所有命令事件记录到
~/.clawdbot/logs/commands.log - 🚀 boot-md:网关启动时运行
BOOT.md(需要启用内部钩子) - 😈 soul-evil:在清除窗口期间或随机机会下将注入的
SOUL.md内容替换为SOUL_EVIL.md
列出可用钩子:
openclaw hooks list启用钩子:
openclaw hooks enable session-memory检查钩子状态:
openclaw hooks check获取详细信息:
openclaw hooks info session-memory入门引导
在入门引导期间(openclaw onboard),系统会提示您启用推荐的钩子。向导会自动发现符合条件的钩子并呈现供您选择。
钩子发现
钩子从三个目录自动发现(按优先级顺序):
- 工作空间钩子:
<workspace>/hooks/(每个智能体,最高优先级) - 托管钩子:
~/.clawdbot/hooks/(用户安装,跨工作空间共享) - 捆绑钩子:
<openclaw>/dist/hooks/bundled/(随 openclaw 提供)
托管钩子目录可以是单个钩子或钩子包(包目录)。
每个钩子是一个包含以下内容的目录:
my-hook/
├── HOOK.md # 元数据 + 文档
└── handler.ts # 处理程序实现钩子包(npm/归档文件)
钩子包是标准的 npm 包,通过 package.json 中的 openclaw.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)的钩子目录。 钩子包可以包含依赖项;它们将安装在 ~/.clawdbot/hooks/<id> 下。
钩子结构
HOOK.md 格式
HOOK.md 文件包含 YAML 前置元数据和 Markdown 文档:
---
name: my-hook
description: "此钩子功能的简短描述"
homepage: https://docs.molt.bot/hooks#my-hook
metadata: {"openclaw":{"emoji":"🔗","events":["command:new"],"requires":{"bins":["node"]}}}
---
# 我的钩子
详细文档放在这里...
## 功能
- 监听 `/new` 命令
- 执行某些操作
- 记录结果
## 要求
- 必须安装 Node.js
## 配置
无需配置。元数据字段
metadata.openclaw 对象支持:
emoji:CLI 显示的表情符号(例如"💾")events:要监听的事件数组(例如["command:new", "command:reset"])export:要使用的命名导出(默认为"default")homepage:文档 URLrequires:可选要求bins:PATH 上必需的二进制文件(例如["git", "node"])anyBins:至少存在这些二进制文件中的一个env:必需的环境变量config:必需的配置路径(例如["workspace.dir"])os:必需的平台(例如["darwin", "linux"])
always:绕过资格检查(布尔值)install:安装方法(对于捆绑钩子:[{"id":"bundled","kind":"bundled"}])
Handler Implementation
The handler.ts file exports a HookHandler function:
import type { HookHandler } from '../../src/hooks/hooks.js';
const myHandler: HookHandler = async (event) => {
// Only trigger on 'new' command
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()}`);
// Your custom logic here
// Optionally send message to user
event.messages.push('✨ My hook executed!');
};
export default myHandler;Event Context
Each event includes:
{
type: 'command' | 'session' | 'agent' | 'gateway',
action: string, // e.g., 'new', 'reset', 'stop'
sessionKey: string, // Session identifier
timestamp: Date, // When the event occurred
messages: string[], // Push messages here to send to user
context: {
sessionEntry?: SessionEntry,
sessionId?: string,
sessionFile?: string,
commandSource?: string, // e.g., 'whatsapp', 'telegram'
senderId?: string,
workspaceDir?: string,
bootstrapFiles?: WorkspaceBootstrapFile[],
cfg?: openclawConfig
}
}事件类型
命令事件
在发出智能体命令时触发:
command:所有命令事件(通用监听器)command:new:发出/new命令时command:reset:发出/reset命令时command:stop:发出/stop命令时
智能体事件
agent:bootstrap:在工作空间引导文件注入之前(钩子可以修改context.bootstrapFiles)
网关事件
在网关启动时触发:
gateway:startup:在通道启动且钩子加载后
工具结果钩子(插件 API)
这些钩子不是事件流监听器;它们允许插件在 openclaw 持久化工具结果之前同步调整它们。
tool_result_persist:在工具结果写入会话记录之前转换它们。必须是同步的;返回更新的工具结果负载或undefined以保持原样。请参阅智能体循环。
未来事件
计划的事件类型:
session:start:新会话开始时session:end:会话结束时agent:error:智能体遇到错误时message:sent:消息发送时message:received:消息接收时
创建自定义钩子
1. 选择位置
- 工作空间钩子(
<workspace>/hooks/):每个智能体,最高优先级 - 托管钩子(
~/.clawdbot/hooks/):跨工作空间共享
2. 创建目录结构
mkdir -p ~/.clawdbot/hooks/my-hook
cd ~/.clawdbot/hooks/my-hook3. 创建 HOOK.md
---
name: my-hook
description: "执行有用的操作"
metadata: {"openclaw":{"emoji":"🎯","events":["command:new"]}}
---
# 我的自定义钩子
当您发出 `/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] 运行中!');
// 您的逻辑在这里
};
export default handler;5. 启用和测试
# 验证钩子是否被发现
openclaw hooks list
# 启用它
openclaw hooks enable my-hook
# 重启您的网关进程(在 macOS 上重启菜单栏应用,或重启您的开发进程)
# 触发事件
# 通过您的消息通道发送 /newConfiguration
New Config Format (Recommended)
{
"hooks": {
"internal": {
"enabled": true,
"entries": {
"session-memory": { "enabled": true },
"command-logger": { "enabled": false }
}
}
}
}Per-Hook Configuration
Hooks can have custom configuration:
{
"hooks": {
"internal": {
"enabled": true,
"entries": {
"my-hook": {
"enabled": true,
"env": {
"MY_CUSTOM_VAR": "value"
}
}
}
}
}
}Extra Directories
Load hooks from additional directories:
{
"hooks": {
"internal": {
"enabled": true,
"load": {
"extraDirs": ["/path/to/more/hooks"]
}
}
}
}Legacy Config Format (Still Supported)
The old config format still works for backwards compatibility:
{
"hooks": {
"internal": {
"enabled": true,
"handlers": [
{
"event": "command:new",
"module": "./hooks/handlers/my-handler.ts",
"export": "default"
}
]
}
}
}Migration: Use the new discovery-based system for new hooks. Legacy handlers are loaded after directory-based hooks.
CLI 命令
列出钩子
# 列出所有钩子
openclaw hooks list
# 仅显示符合条件的钩子
openclaw hooks list --eligible
# 详细输出(显示缺失的要求)
openclaw hooks list --verbose
# JSON 输出
openclaw hooks list --json钩子信息
# 显示钩子的详细信息
openclaw hooks info session-memory
# JSON 输出
openclaw hooks info session-memory --json检查资格
# 显示资格摘要
openclaw hooks check
# JSON 输出
openclaw hooks check --json启用/禁用
# 启用钩子
openclaw hooks enable session-memory
# 禁用钩子
openclaw hooks disable command-logger捆绑钩子
session-memory
发出 /new 命令时将会话上下文保存到内存。
事件:command:new
要求:必须配置 workspace.dir
输出:<workspace>/memory/YYYY-MM-DD-slug.md(默认为 ~/clawd)
功能:
- 使用重置前的会话条目定位正确的记录
- 提取最后 15 行对话
- 使用 LLM 生成描述性文件名 slug
- 将会话元数据保存到带日期标记的内存文件
示例输出:
# 会话:2026-01-16 14:30:00 UTC
- **会话密钥**:agent:main:main
- **会话 ID**:abc123def456
- **来源**:telegram文件名示例:
2026-01-16-vendor-pitch.md2026-01-16-api-design.md2026-01-16-1430.md(如果 slug 生成失败,则使用时间戳回退)
启用:
openclaw hooks enable session-memorycommand-logger
Logs all command events to a centralized audit file.
Events: command
Requirements: None
Output: ~/.clawdbot/logs/commands.log
What it does:
- Captures event details (command action, timestamp, session key, sender ID, source)
- Appends to log file in JSONL format
- Runs silently in the background
Example log entries:
{"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":"user@example.com","source":"whatsapp"}View logs:
# View recent commands
tail -n 20 ~/.clawdbot/logs/commands.log
# Pretty-print with jq
cat ~/.clawdbot/logs/commands.log | jq .
# Filter by action
grep '"action":"new"' ~/.clawdbot/logs/commands.log | jq .Enable:
openclaw hooks enable command-loggersoul-evil
Swaps injected SOUL.md content with SOUL_EVIL.md during a purge window or by random chance.
Events: agent:bootstrap
Docs: SOUL Evil Hook
Output: No files written; swaps happen in-memory only.
Enable:
openclaw hooks enable soul-evilConfig:
{
"hooks": {
"internal": {
"enabled": true,
"entries": {
"soul-evil": {
"enabled": true,
"file": "SOUL_EVIL.md",
"chance": 0.1,
"purge": { "at": "21:00", "duration": "15m" }
}
}
}
}
}boot-md
Runs BOOT.md when the gateway starts (after channels start). Internal hooks must be enabled for this to run.
Events: gateway:startup
Requirements: workspace.dir must be configured
What it does:
- Reads
BOOT.mdfrom your workspace - Runs the instructions via the agent runner
- Sends any requested outbound messages via the message tool
Enable:
openclaw hooks enable boot-md最佳实践
保持处理程序快速
钩子在命令处理期间运行。保持它们轻量级:
// ✓ 良好 - 异步工作,立即返回
const handler: HookHandler = async (event) => {
void processInBackground(event); // 触发后不管
};
// ✗ 不好 - 阻塞命令处理
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));
// Don't throw - let other handlers run
}
};Filter Events Early
Return early if the event isn't relevant:
const handler: HookHandler = async (event) => {
// Only handle 'new' commands
if (event.type !== 'command' || event.action !== 'new') {
return;
}
// Your logic here
};Use Specific Event Keys
Specify exact events in metadata when possible:
metadata: {"openclaw":{"events":["command:new"]}} # SpecificRather than:
metadata: {"openclaw":{"events":["command"]}} # General - more overhead调试
启用钩子日志记录
网关在启动时记录钩子加载:
注册钩子:session-memory -> command:new
注册钩子:command-logger -> command
注册钩子:boot-md -> gateway:startup检查发现
列出所有发现的钩子:
openclaw hooks list --verbose检查注册
在您的处理程序中,记录调用时间:
const handler: HookHandler = async (event) => {
console.log('[my-handler] 触发:', event.type, event.action);
// 您的逻辑
};验证资格
检查钩子不符合条件的原因:
openclaw hooks info my-hook在输出中查找缺失的要求。
测试
网关日志
监控网关日志以查看钩子执行:
# macOS
./scripts/clawlog.sh -f
# 其他平台
tail -f ~/.clawdbot/gateway.log直接测试钩子
隔离测试您的处理程序:
import { test } from 'vitest';
import { createHookEvent } from './src/hooks/hooks.js';
import myHandler from './hooks/my-hook/handler.js';
test('我的处理程序工作正常', async () => {
const event = createHookEvent('command', 'new', 'test-session', {
foo: 'bar'
});
await myHandler(event);
// 断言副作用
});架构
核心组件
src/hooks/types.ts: 类型定义src/hooks/workspace.ts: 目录扫描和加载src/hooks/frontmatter.ts: HOOK.md 元数据解析src/hooks/config.ts: 资格检查src/hooks/hooks-status.ts: 状态报告src/hooks/loader.ts: 动态模块加载器src/cli/hooks-cli.ts: CLI 命令src/gateway/server-startup.ts: 在网关启动时加载钩子src/auto-reply/reply/commands-core.ts: 触发命令事件
发现流程
网关启动
↓
扫描目录(工作空间 → 托管 → 捆绑)
↓
解析 HOOK.md 文件
↓
检查资格(二进制文件、环境变量、配置、操作系统)
↓
从符合条件的钩子加载处理程序
↓
为事件注册处理程序事件流程
用户发送 /new
↓
命令验证
↓
创建钩子事件
↓
触发钩子(所有注册的处理程序)
↓
命令处理继续
↓
会话重置故障排除
钩子未被发现
检查目录结构:
bashls -la ~/.clawdbot/hooks/my-hook/ # 应该显示:HOOK.md, handler.ts验证 HOOK.md 格式:
bashcat ~/.clawdbot/hooks/my-hook/HOOK.md # 应该包含带有名称和元数据的 YAML 前置内容列出所有发现的钩子:
bashopenclaw hooks list
钩子不符合条件
检查要求:
openclaw hooks info my-hook查找缺失的:
- 二进制文件(检查 PATH)
- 环境变量
- 配置值
- 操作系统兼容性
钩子未执行
验证钩子是否启用:
bashopenclaw hooks list # 应该在启用的钩子旁边显示 ✓重启您的网关进程以便钩子重新加载。
检查网关日志中的错误:
bash./scripts/clawlog.sh | grep hook
处理程序错误
检查 TypeScript/导入错误:
# 直接测试导入
node -e "import('./path/to/handler.ts').then(console.log)"迁移指南
从旧版配置迁移到发现机制
迁移前:
{
"hooks": {
"internal": {
"enabled": true,
"handlers": [
{
"event": "command:new",
"module": "./hooks/handlers/my-handler.ts"
}
]
}
}
}迁移后:
创建钩子目录:
bashmkdir -p ~/.clawdbot/hooks/my-hook mv ./hooks/handlers/my-handler.ts ~/.clawdbot/hooks/my-hook/handler.ts创建 HOOK.md:
markdown--- name: my-hook description: "我的自定义钩子" metadata: {"openclaw":{"emoji":"🎯","events":["command:new"]}} --- # 我的钩子 执行一些有用的操作。更新配置:
json{ "hooks": { "internal": { "enabled": true, "entries": { "my-hook": { "enabled": true } } } } }验证并重启您的网关进程:
bashopenclaw hooks list # 应该显示:🎯 my-hook ✓
迁移的好处:
- 自动发现
- CLI 管理
- 资格检查
- 更好的文档
- 一致的结构