Hook
Hook 为响应代理命令和事件而自动化操作提供了可扩展的事件驱动系统。Hook 从目录自动发现,可以通过 CLI 命令管理,类似于 OpenClaw 中技能的工作方式�?
了解方向
Hook 是发生某些事情时运行的小脚本。有两种�?
- Hook(本页):当代理事件触发时在网关内运行,�?
/new、/reset、/stop或生命周期事件�? - Webhook:允许其他系统在 OpenClaw 中触发工作的外部 HTTP webhook。请参阅 Webhook Hook 或使�?
openclaw webhooks获取 Gmail 辅助命令�?
Hook 也可以捆绑在插件中;请参�?Plugins�?
常见用途:
- 重置会话时保存内存快�?
- 保留命令审计跟踪以便故障排除或合�?
- 在会话开始或结束时触发后续自动化
- 在事件触发时将文件写入代理工作区或调用外�?API
如果您可以编写小�?TypeScript 函数,就可以编写 Hook。Hook 会自动被发现,您可以通过 CLI 启用或禁用它们�?
概述
Hook 系统允许您:
- 发出
/new时将会话上下文保存到内存 - 记录所有命令以供审�?
- 在代理生命周期事件上触发自定义自动化
- 在不修改核心代码的情况下扩展 OpenClaw 行为
入门
捆绑�?Hook
OpenClaw 附带了四个自动发现的捆绑 Hook�?
- 💾 session-memory:当您发�?
/new时将会话上下文保存到代理工作区(默认~/.openclaw/workspace/memory/�? - 📎 bootstrap-extra-files:在
agent:bootstrap期间从配置的 glob/路径模式注入额外的工作区引导文件 - 📝 command-logger:将所有命令事件记录到
~/.openclaw/logs/commands.log - 🚀 boot-md:网关启动时运行
BOOT.md(需要启用内�?Hook�?
列出可用�?Hook�?
openclaw hooks list
启用 Hook�?
openclaw hooks enable session-memory
检�?Hook 状态:
openclaw hooks check
获取详细信息�?
openclaw hooks info session-memory
入门引导
在入职期间(openclaw onboard),系统会提示您启用推荐�?Hook。向导会自动发现符合条件�?Hook 并显示供您选择�?
Hook 发现
Hook 从三个目录自动发现(按优先级顺序):
- 工作�?Hook:
<workspace>/hooks/(每个代理,最高优先级�? - 托管 Hook:
~/.openclaw/hooks/(用户安装,跨工作区共享�? - 捆绑 Hook:
<openclaw>/dist/hooks/bundled/(随 OpenClaw 附带�?
托管 Hook 目录可以�?单个 Hook*�?**Hook �?*(包目录)�?
每个 Hook 是一个包含以下内容的目录�?
my-hook/
├── HOOK.md # 元数�?+ 文档
└── handler.ts # 处理器实�?
Hook 包(npm/归档�?
Hook 包是通过 package.json 中的 openclaw.hooks 导出 一个或多个 Hook 的标�?npm 包。安装方式:
openclaw hooks install <path-or-spec>
Npm 规范仅限注册表(包名 + 可选版�?标签)。Git/URL/文件规范被拒绝�?
示例 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 包可以附带依赖项;它们将安装�?~/.openclaw/hooks/<id> 下�?
每个 openclaw.hooks 条目在符号链接解析后必须保持在包目录内;逃逸的条目被拒绝�?
安全说明:openclaw hooks install 使用 npm install --ignore-scripts 安装依赖(无生命周期脚本)。保�?Hook 包依赖树�?�?JS/TS”,避免依�?postinstall 构建的包�?
Hook 结构
HOOK.md 格式
HOOK.md 文件包含 YAML 头部的元数据�?Markdown 文档�?
---
name: my-hook
description: "Short description of what this hook does"
homepage: https://docs.openclaw.ai/automation/hooks#my-hook
metadata:
{ "openclaw": { "emoji": "🔗", "events": ["command:new"], "requires": { "bins": ["node"] } } }
---
# My Hook
Detailed documentation goes here...
## What It Does
- Listens for `/new` commands
- Performs some action
- Logs the result
## Requirements
- Node.js must be installed
## Configuration
No configuration needed.
元数据字�?
metadata.openclaw 对象支持�?
emoji:CLI 显示 emoji(例�?"💾"�?events:要监听的事件数组(例如["command:new", "command:reset"]�?export:使用的命名导出(默认为"default"�?homepage:文�?URLrequires:可选要�?bins:PATH 上需要的二进制文件(例如["git", "node"]�?anyBins:至少存在这些二进制文件之一env:需要的环境变量config:需要的配置路径(例�?["workspace.dir"]�?os:需要的平台(例�?["darwin", "linux"]�?
always:绕过资格检查(布尔值)install:安装方式(对于捆绑 Hook:[{"id":"bundled","kind":"bundled"}]�?
处理器实�?
handler.ts 文件导出 HookHandler 函数�?
const myHandler = 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;
事件上下�?
每个事件包括�?
{
type: 'command' | 'session' | 'agent' | 'gateway' | 'message',
action: string, // e.g., 'new', 'reset', 'stop', 'received', 'sent'
sessionKey: string, // Session identifier
timestamp: Date, // When the event occurred
messages: string[], // Push messages here to send to user
context: {
// Command events:
sessionEntry?: SessionEntry,
sessionId?: string,
sessionFile?: string,
commandSource?: string, // e.g., 'whatsapp', 'telegram'
senderId?: string,
workspaceDir?: string,
bootstrapFiles?: WorkspaceBootstrapFile[],
cfg?: OpenClawConfig,
// Message events (see Message Events section for full details):
from?: string, // message:received
to?: string, // message:sent
content?: string,
channelId?: string,
success?: boolean, // message:sent
}
}
事件类型
命令事件
当代理命令发出时触发�?
command:所有命令事件(通用监听器)command:new:当发出/new命令�?command:reset:当发出/reset命令�?command:stop:当发出/stop命令�?
代理事件
agent:bootstrap:在工作区引导文件注入之前(Hook 可能会改�?context.bootstrapFiles�?
网关事件
当网关启动时触发�?
gateway:startup:频道启动并加载 Hook �?
消息事件
当收到或发送消息时触发�?
message:所有消息事件(通用监听器)message:received:当从任何频道收到入站消息时message:sent:当出站消息成功发送时
消息事件上下�?
消息事件包括关于消息的丰富上下文�?
// message:received context
{
from: string, // 发送者标识符(电话号码、用�?ID 等)
content: string, // 消息内容
timestamp?: number, // 收到时的 Unix 时间�?
channelId: string, // 频道(例�?"whatsapp"�?telegram"�?discord"�?
accountId?: string, // 多账户设置的用户账户 ID
conversationId?: string, // 聊天/会话 ID
messageId?: string, // 提供商的消息 ID
metadata?: { // 额外的提供商特定数据
to?: string,
provider?: string,
surface?: string,
threadId?: string,
senderId?: string,
senderName?: string,
senderUsername?: string,
senderE164?: string,
}
}
// message:sent context
{
to: string, // 收件人标识符
content: string, // 已发送的消息内容
success: boolean, // 发送是否成�?
error?: string, // 发送失败时的错误消�?
channelId: string, // 频道(例�?"whatsapp"�?telegram"�?discord"�?
accountId?: string, // 用户账户 ID
conversationId?: string, // 聊天/会话 ID
messageId?: string, // 提供商返回的消息 ID
}
示例:消息记录器 Hook
const isMessageReceivedEvent = (event: { type: string; action: string }) =>
event.type === "message" && event.action === "received";
const isMessageSentEvent = (event: { type: string; action: string }) =>
event.type === "message" && event.action === "sent";
const handler = async (event) => {
if (isMessageReceivedEvent(event as { type: string; action: string })) {
console.log(`[message-logger] Received from ${event.context.from}: ${event.context.content}`);
} else if (isMessageSentEvent(event as { type: string; action: string })) {
console.log(`[message-logger] Sent to ${event.context.to}: ${event.context.content}`);
}
};
export default handler;
工具结果 Hook(插�?API�?
这些 Hook 不是事件流监听器;它们允许插件在 OpenClaw 持久化工具结果之前同步调整它们�?
tool_result_persist:在工具结果写入会话转录之前转换它们。必须是同步的;返回更新后的工具结果负载�?undefined以保持原样。请参阅 Agent Loop�?
未来事件
计划的事件类型:
session:start:当新会话开始时session:end:当会话结束�?agent:error:当代理遇到错误�?
创建自定�?Hook
1. 选择位置
- 工作�?Hook(
<workspace>/hooks/):每个代理,最高优先级 - 托管 Hook(
~/.openclaw/hooks/):跨工作区共享
2. 创建目录结构
mkdir -p ~/.openclaw/hooks/my-hook
cd ~/.openclaw/hooks/my-hook
3. 创建 HOOK.md
---
name: my-hook
description: "Does something useful"
metadata: { "openclaw": { "emoji": "🎯", "events": ["command:new"] } }
---
# My Custom Hook
This hook does something useful when you issue `/new`.
4. 创建 handler.ts
const handler = async (event) => {
if (event.type !== "command" || event.action !== "new") {
return;
}
console.log("[my-hook] Running!");
// Your logic here
};
export default handler;
5. 启用并测�?
# Verify hook is discovered
openclaw hooks list
# Enable it
openclaw hooks enable my-hook
# Restart your gateway process (menu bar app restart on macOS, or restart your dev process)
# Trigger the event
# Send /new via your messaging channel
配置
新配置格式(推荐�?
{
"hooks": {
"internal": {
"enabled": true,
"entries": {
"session-memory": { "enabled": true },
"command-logger": { "enabled": false }
}
}
}
}
每个 Hook 的配�?
Hook 可以有自定义配置�?
{
"hooks": {
"internal": {
"enabled": true,
"entries": {
"my-hook": {
"enabled": true,
"env": {
"MY_CUSTOM_VAR": "value"
}
}
}
}
}
}
额外目录
从额外目录加�?Hook�?
{
"hooks": {
"internal": {
"enabled": true,
"load": {
"extraDirs": ["/path/to/more/hooks"]
}
}
}
}
旧配置格式(仍然支持�?
旧配置格式仍然向后兼容:
{
"hooks": {
"internal": {
"enabled": true,
"handlers": [
{
"event": "command:new",
"module": "./hooks/handlers/my-handler.ts",
"export": "default"
}
]
}
}
}
注意:module 必须是工作区相对路径。绝对路径和遍历工作区外被拒绝�?
迁移:将�?Hook 用于新的基于发现的系统。旧处理器在基于目录�?Hook 之后加载�?
CLI 命令
列出 Hook
# List all hooks
openclaw hooks list
# Show only eligible hooks
openclaw hooks list --eligible
# Verbose output (show missing requirements)
openclaw hooks list --verbose
# JSON output
openclaw hooks list --json
Hook 信息
# Show detailed info about a hook
openclaw hooks info session-memory
# JSON output
openclaw hooks info session-memory --json
检查资�?
# Show eligibility summary
openclaw hooks check
# JSON output
openclaw hooks check --json
启用/禁用
# Enable a hook
openclaw hooks enable session-memory
# Disable a hook
openclaw hooks disable command-logger
捆绑 Hook 参�?
session-memory
当您发出 /new 时将会话上下文保存到内存�?
事件:command:new
要求:必须配�?workspace.dir
输出:<workspace>/memory/YYYY-MM-DD-slug.md(默认为 ~/.openclaw/workspace�?
功能�?
- 使用重置前的会话条目定位正确的转�?
- 提取最�?15 行对�?
- 使用 LLM 生成描述性文件名片段
- 将会话元数据保存到带日期的内存文�?
示例输出�?
# Session: 2026-01-16 14:30:00 UTC
- **Session Key**: agent:main:main
- **Session ID**: abc123def456
- **Source**: telegram
**文件名示�?*�?
2026-01-16-vendor-pitch.md2026-01-16-api-design.md2026-01-16-1430.md(片段生成失败时的回退时间戳)
启用�?
openclaw hooks enable session-memory
bootstrap-extra-files
�?agent:bootstrap 期间注入额外引导文件(例�?monorepo 本地�?AGENTS.md / TOOLS.md)�?
事件:agent:bootstrap
要求:必须配�?workspace.dir
输出:不写入文件;引导上下文仅在内存中修改�?
配置�?
{
"hooks": {
"internal": {
"enabled": true,
"entries": {
"bootstrap-extra-files": {
"enabled": true,
"paths": ["packages/*/AGENTS.md", "packages/*/TOOLS.md"]
}
}
}
}
}
注意�?
- 路径相对于工作区解析�?
- 文件必须保持在工作区内(realpath 检查)�?
- 仅加载可识别的引导基本名称�?
- 子代理允许列表被保留(仅
AGENTS.md�?TOOLS.md)�?
启用�?
openclaw hooks enable bootstrap-extra-files
command-logger
将所有命令事件记录到集中审计文件�?
事件:command
要求:无
输出:~/.openclaw/logs/commands.log
功能�?
- 捕获事件详情(命令操作、时间戳、会话密钥、发送�?ID、来源)
- �?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"}
查看日志�?
# View recent commands
tail -n 20 ~/.openclaw/logs/commands.log
# Pretty-print with jq
cat ~/.openclaw/logs/commands.log | jq .
# Filter by action
grep '"action":"new"' ~/.openclaw/logs/commands.log | jq .
启用�?
openclaw hooks enable command-logger
boot-md
网关启动时运�?BOOT.md(频道启动后)。必须启用内�?Hook 才能运行�?
事件:gateway:startup
要求:必须配�?workspace.dir
功能�?
- 从工作区读取
BOOT.md - 通过代理运行器运行指�?
- 通过消息工具发送任何请求的出站消息
启用�?
openclaw hooks enable boot-md
最佳实�?
保持处理器快�?
Hook 在命令处理期间运行。保持它们轻量:
// �?Good - async work, returns immediately
const handler: HookHandler = async (event) => {
void processInBackground(event); // Fire and forget
};
// �?Bad - blocks command processing
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
}
};
尽早过滤事件
如果事件不相关则提前返回�?
const handler: HookHandler = async (event) => {
// Only handle 'new' commands
if (event.type !== "command" || event.action !== "new") {
return;
}
// Your logic here
};
使用特定事件�?
尽可能在元数据中指定精确事件�?
metadata: { "openclaw": { "events": ["command:new"] } } # Specific
而不是:
metadata: { "openclaw": { "events": ["command"] } } # General - more overhead
调试
启用 Hook 日志
网关在启动时记录 Hook 加载�?
Registered hook: session-memory -> command:new
Registered hook: bootstrap-extra-files -> agent:bootstrap
Registered hook: command-logger -> command
Registered hook: boot-md -> gateway:startup
检查发�?
列出所有发现的 Hook�?
openclaw hooks list --verbose
检查注�?
在处理器中记录其何时被调用:
const handler: HookHandler = async (event) => {
console.log("[my-handler] Triggered:", event.type, event.action);
// Your logic
};
验证资格
检�?Hook 不符合条件的原因�?
openclaw hooks info my-hook
在输出中查找缺失的要求�?
测试
网关日志
监控网关日志以查�?Hook 执行�?
# macOS
./scripts/clawlog.sh -f
# Other platforms
tail -f ~/.openclaw/gateway.log
直接测试 Hook
隔离测试处理器:
import { test } from "vitest";
import myHandler from "./hooks/my-hook/handler.js";
test("my handler works", async () => {
const event = {
type: "command",
action: "new",
sessionKey: "test-session",
timestamp: new Date(),
messages: [],
context: { foo: "bar" },
};
await myHandler(event);
// Assert side effects
});
架构
核心组件
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:在网关启动时加�?Hooksrc/auto-reply/reply/commands-core.ts:触发命令事�?
发现流程
Gateway startup
�?
Scan directories (workspace �?managed �?bundled)
�?
Parse HOOK.md files
�?
Check eligibility (bins, env, config, os)
�?
Load handlers from eligible hooks
�?
Register handlers for events
事件流程
User sends /new
�?
Command validation
�?
Create hook event
�?
Trigger hook (all registered handlers)
�?
Command processing continues
�?
Session reset
故障排除
Hook 未被发现
-
检查目录结构:
ls -la ~/.openclaw/hooks/my-hook/ # Should show: HOOK.md, handler.ts -
验证 HOOK.md 格式�?
cat ~/.openclaw/hooks/my-hook/HOOK.md # Should have YAML frontmatter with name and metadata -
列出所有发现的 Hook�?
openclaw hooks list
Hook 不符合条�?
检查要求:
openclaw hooks info my-hook
查找缺失的:
- 二进制文件(检�?PATH�?
- 环境变量
- 配置�?
- 操作系统兼容�?
Hook 未执�?
-
验证 Hook 已启用:
openclaw hooks list # Should show �?next to enabled hooks -
重启网关进程以重新加�?Hook�?
-
检查网关日志中的错误:
./scripts/clawlog.sh | grep hook
处理器错�?
检�?TypeScript/导入错误�?
# Test import directly
node -e "import('./path/to/handler.ts').then(console.log)"
迁移指南
从旧配置迁移到发�?
之前�?
{
"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: "My custom hook" metadata: { "openclaw": { "emoji": "🎯", "events": ["command:new"] } } --- # My Hook Does something useful. -
更新配置�?
{ "hooks": { "internal": { "enabled": true, "entries": { "my-hook": { "enabled": true } } } } } -
验证并重启网关进程:
openclaw hooks list # Should show: 🎯 my-hook �?
**迁移的好�?*�?
- 自动发现
- CLI 管理
- 资格检�?
- 更好的文�?
- 一致的结构