Hooks
Hooks 提供了一个可扩展的事件驱动系统,用于自动执行响应代理命令和事件的操作。Hooks 会从目录中自动发现,并可以通过 CLI 命令进行管理,类似于技能在 OpenClaw 中的工作方式。
Hooks 是在发生某些情况时运行的小型脚本。有两种类型:
- Hooks (本页):当代理事件触发时在 Gateway(网关) 网关 内部运行,例如
/new、/reset、/stop或生命周期事件。 - Webhooks:外部 HTTP Webhook,允许其他系统在 OpenClaw 中触发工作。请参阅 Webhook Hooks 或使用
openclaw webhooks获取 Gmail 辅助命令。
Hooks 也可以打包在插件内部;请参阅 Plugins。
常见用途:
- 重置会话时保存内存快照
- 保留命令的审计跟踪以便进行故障排除或合规检查
- 在会话开始或结束时触发后续自动化
- 在事件触发时将文件写入代理工作区或调用外部 API
如果您能编写一个小型 TypeScript 函数,就可以编写一个 hook。Hooks 会自动被发现,您可以通过 CLI 启用或禁用它们。
Hooks 系统允许您:
- 当发出
/new时,将会话上下文保存到内存 - 记录所有命令以进行审计
- 在代理生命周期事件上触发自定义自动化
- 在不修改核心代码的情况下扩展 OpenClaw 的行为
内置 Hooks
Section titled “内置 Hooks”OpenClaw 附带了四个自动发现的内置 hooks:
- 💾 会话-memory:当您发出
/new时,将会话上下文保存到您的工作区(默认为~/.openclaw/workspace/memory/) - 📝 command-logger:将所有命令事件记录到
~/.openclaw/logs/commands.log - 🚀 boot-md:在网关启动时运行
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在入职(openclaw onboard)期间,系统将提示您启用推荐的 hooks。向导会自动发现符合条件的 hooks 并将其显示出来供您选择。
Hook 发现
Section titled “Hook 发现”Hooks 会从三个目录中自动发现(按优先级顺序):
- 工作区 hooks:
<workspace>/hooks/(每个代理,优先级最高) - 托管 hooks:
~/.openclaw/hooks/(用户安装,在工作区之间共享) - 内置 hooks:
<openclaw>/dist/hooks/bundled/(随 OpenClaw 附带)
托管的 hook 目录可以是单个 hook 或 hook 包(package 目录)。
每个 hook 是一个包含以下内容的目录:
my-hook/├── HOOK.md # Metadata + documentation└── handler.ts # Handler implementationHook 包 (npm/archives)
Section titled “Hook 包 (npm/archives)”Hook 包是标准的 npm 包,通过 openclaw.hooks 在 package.json 中导出一个或多个 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 包可以附带依赖项;它们将安装在 ~/.openclaw/hooks/<id> 下。
Hook 结构
Section titled “Hook 结构”HOOK.md 格式
Section titled “HOOK.md 格式”HOOK.md 文件包含 YAML frontmatter 中的元数据和 Markdown 文档:
---name: my-hookdescription: "Short description of what this hook does"homepage: https://docs.openclaw.ai/hooks#my-hookmetadata: { "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 显示的表情符号(例如"💾")events:要监听的事件数组(例如["command:new", "command:reset"])export:要使用的命名导出(默认为"default")homepage:文档 URLrequires:可选要求bins:PATH 上所需的二进制文件(例如["git", "node"])anyBins:必须至少存在其中一个二进制文件env:所需的环境变量config:所需的配置路径(例如["workspace.dir"])os:所需的平台(例如["darwin", "linux"])
always:绕过资格检查(布尔值)install:安装方法(对于打包的 hooks:[{"id":"bundled","kind":"bundled"}])
handler.ts 文件导出一个 HookHandler 函数:
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;每个事件包括:
{ 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:在注入工作区引导文件之前(hooks 可以更改context.bootstrapFiles)
Gateway(网关) 网关 事件
Section titled “Gateway(网关) 网关 事件”在 Gateway 启动时触发:
gateway:startup:在通道启动且 hooks 加载之后
工具结果钩子
Section titled “工具结果钩子”这些钩子不是事件流监听器;它们允许插件在 OpenClaw 持久化工具结果之前同步调整这些结果。
tool_result_persist:在工具结果写入会话记录之前对其进行转换。必须是同步的;返回更新后的工具结果负载或undefined以保持原样。请参阅 Agent Loop。
计划中的事件类型:
session:start:当新会话开始时session:end:当会话结束时agent:error:当代理遇到错误时message:sent:当发送消息时message:received:当接收消息时
创建自定义 Hooks
Section titled “创建自定义 Hooks”1. 选择位置
Section titled “1. 选择位置”- Workspace hooks (
<workspace>/hooks/):针对每个代理,优先级最高 - Managed hooks (
~/.openclaw/hooks/):在工作区之间共享
2. 创建目录结构
Section titled “2. 创建目录结构”mkdir -p ~/.openclaw/hooks/my-hookcd ~/.openclaw/hooks/my-hook3. 创建 HOOK.md
Section titled “3. 创建 HOOK.md”---name: my-hookdescription: "Does something useful"metadata: { "openclaw": { "emoji": "🎯", "events": ["command:new"] } }---
# My Custom Hook
This hook does something useful when you issue `/new`.4. 创建 handler.ts
Section titled “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!"); // Your logic here};
export default handler;5. 启用和测试
Section titled “5. 启用和测试”# Verify hook is discoveredopenclaw hooks list
# Enable itopenclaw 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新配置格式(推荐)
Section titled “新配置格式(推荐)”{ "hooks": { "internal": { "enabled": true, "entries": { "session-memory": { "enabled": true }, "command-logger": { "enabled": false } } } }}单个 Hook 的配置
Section titled “单个 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"] } } }}旧配置格式(仍然支持)
Section titled “旧配置格式(仍然支持)”为了向后兼容,旧的配置格式仍然有效:
{ "hooks": { "internal": { "enabled": true, "handlers": [ { "event": "command:new", "module": "./hooks/handlers/my-handler.ts", "export": "default" } ] } }}迁移:对于新的 hooks,请使用新的基于发现的系统。旧的处理程序在基于目录的 hooks 之后加载。
CLI 命令
Section titled “CLI 命令”列出 Hooks
Section titled “列出 Hooks”# List all hooksopenclaw hooks list
# Show only eligible hooksopenclaw hooks list --eligible
# Verbose output (show missing requirements)openclaw hooks list --verbose
# JSON outputopenclaw hooks list --jsonHook 信息
Section titled “Hook 信息”# Show detailed info about a hookopenclaw hooks info session-memory
# JSON outputopenclaw hooks info session-memory --json# Show eligibility summaryopenclaw hooks check
# JSON outputopenclaw hooks check --json# Enable a hookopenclaw hooks enable session-memory
# Disable a hookopenclaw hooks disable command-logger捆绑的 Hooks
Section titled “捆绑的 Hooks”会话-memory
Section titled “会话-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(如果 slug 生成失败则使用回退时间戳)
启用:
openclaw hooks enable session-memorycommand-logger
Section titled “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 commandstail -n 20 ~/.openclaw/logs/commands.log
# Pretty-print with jqcat ~/.openclaw/logs/commands.log | jq .
# Filter by actiongrep '"action":"new"' ~/.openclaw/logs/commands.log | jq .启用:
openclaw hooks enable command-loggersoul-evil
Section titled “soul-evil”在清除窗口期间或随机将注入的 SOUL.md 内容与 SOUL_EVIL.md 交换。
事件: agent:bootstrap
文档: SOUL Evil Hook
输出:不写入文件;交换仅在内存中进行。
启用:
openclaw hooks enable soul-evil配置:
{ "hooks": { "internal": { "enabled": true, "entries": { "soul-evil": { "enabled": true, "file": "SOUL_EVIL.md", "chance": 0.1, "purge": { "at": "21:00", "duration": "15m" } } } } }}boot-md
Section titled “boot-md”在网关启动时(通道启动之后)运行 BOOT.md。
必须启用内部 Hook 才能运行此功能。
事件: gateway:startup
要求:必须配置 workspace.dir
作用:
- 从您的工作区读取
BOOT.md - 通过代理运行器运行指令
- 通过消息工具发送任何请求的出站消息
启用:
openclaw hooks enable boot-md保持处理程序快速
Section titled “保持处理程序快速”Hook 在命令处理期间运行。请保持轻量:
// ✓ Good - async work, returns immediatelyconst handler: HookHandler = async (event) => { void processInBackground(event); // Fire and forget};
// ✗ Bad - blocks command processingconst handler: HookHandler = async (event) => { await slowDatabaseQuery(event); await evenSlowerAPICall(event);};优雅地处理错误
Section titled “优雅地处理错误”始终包装有风险的操作:
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 }};尽早过滤事件
Section titled “尽早过滤事件”如果事件不相关,请尽早返回:
const handler: HookHandler = async (event) => { // Only handle 'new' commands if (event.type !== "command" || event.action !== "new") { return; }
// Your logic here};使用特定的事件键
Section titled “使用特定的事件键”尽可能在元数据中指定确切的事件:
metadata: { "openclaw": { "events": ["command:new"] } } # Specific而不是:
metadata: { "openclaw": { "events": ["command"] } } # General - more overhead启用 Hook 日志记录
Section titled “启用 Hook 日志记录”网关在启动时记录 Hook 加载情况:
Registered hook: session-memory -> command:newRegistered hook: command-logger -> commandRegistered hook: boot-md -> gateway:startup检查设备发现
Section titled “检查设备发现”列出所有已发现的 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查找输出中缺少的要求。
Gateway(网关) 网关 日志
Section titled “Gateway(网关) 网关 日志”监控网关日志以查看 Hook 执行情况:
# macOS./scripts/clawlog.sh -f
# Other platformstail -f ~/.openclaw/gateway.log直接测试 Hooks
Section titled “直接测试 Hooks”单独测试您的处理程序:
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);
// 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:在网关启动时加载 hookssrc/auto-reply/reply/commands-core.ts:触发命令事件
设备发现流程
Section titled “设备发现流程”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 eventsUser sends /new ↓Command validation ↓Create hook event ↓Trigger hook (all registered handlers) ↓Command processing continues ↓Session resetHook 未被发现
Section titled “Hook 未被发现”-
检查目录结构:
Terminal window ls -la ~/.openclaw/hooks/my-hook/# Should show: HOOK.md, handler.ts -
验证 HOOK.md 格式:
Terminal window cat ~/.openclaw/hooks/my-hook/HOOK.md# Should have YAML frontmatter with name and metadata -
列出所有已发现的 hooks:
Terminal window openclaw hooks list
Hook 不符合资格
Section titled “Hook 不符合资格”检查要求:
openclaw hooks info my-hook查找缺失项:
- 二进制文件(检查 PATH)
- 环境变量
- 配置值
- 操作系统兼容性
Hook 未执行
Section titled “Hook 未执行”-
验证 hook 是否已启用:
Terminal window openclaw hooks list# Should show ✓ next to enabled hooks -
重启您的网关进程以重新加载 hooks。
-
检查网关日志中的错误:
Terminal window ./scripts/clawlog.sh | grep hook
处理程序错误
Section titled “处理程序错误”检查 TypeScript/导入错误:
# Test import directlynode -e "import('./path/to/handler.ts').then(console.log)"从旧版配置到设备发现
Section titled “从旧版配置到设备发现”之前:
{ "hooks": { "internal": { "enabled": true, "handlers": [ { "event": "command:new", "module": "./hooks/handlers/my-handler.ts" } ] } }}之后:
-
创建 hook 目录:
Terminal window mkdir -p ~/.openclaw/hooks/my-hookmv ./hooks/handlers/my-handler.ts ~/.openclaw/hooks/my-hook/handler.ts -
创建 HOOK.md:
---name: my-hookdescription: "My custom hook"metadata: { "openclaw": { "emoji": "🎯", "events": ["command:new"] } }---# My HookDoes something useful. -
更新配置:
{"hooks": {"internal": {"enabled": true,"entries": {"my-hook": { "enabled": true }}}}} -
验证并重启您的网关进程:
Terminal window openclaw hooks list# Should show: 🎯 my-hook ✓
迁移的好处:
- 自动设备发现
- CLI 管理
- 资格检查
- 更完善的文档
- 统一的结构