Hooks

Hooks 提供了一套可扩展的事件驱动系统,在 agent 命令和事件触发时自动执行操作。Hooks 从目录中自动发现,可以通过 CLI 管理,工作方式类似 OpenClaw 的 skills。

先搞清楚两个概念

Hooks 就是在特定事情发生时运行的小脚本。分两种:

  • Hooks(本页):在 Gateway 内部运行,响应 agent 事件,比如 /new/reset/stop 或生命周期事件。
  • Webhooks:外部 HTTP webhook,让其他系统触发 OpenClaw 里的工作。见 Webhook Hooks 或用 openclaw webhooks 进行 Gmail 相关操作。

Hooks 也可以打包在插件里;见 插件

常见用途:

  • 重置会话时保存一份记忆快照
  • 记录命令操作日志,用于排障或合规审计
  • 会话开始或结束时触发后续自动化
  • 事件触发时往 agent 工作区写文件或调用外部 API

只要你能写一个简单的 TypeScript 函数,就能写 hook。Hooks 会被自动发现,启用或禁用通过 CLI 搞定。

概览

hooks 系统能做这些事:

  • 发出 /new 时把会话上下文保存到记忆
  • 记录所有命令用于审计
  • 在 agent 生命周期事件上触发自定义自动化
  • 不修改核心代码就扩展 OpenClaw 的行为

快速上手

内置 Hooks

OpenClaw 自带四个内置 hook,会被自动发现:

  • session-memory:发出 /new 时把会话上下文保存到 agent 工作区(默认 ~/.openclaw/workspace/memory/
  • bootstrap-extra-files:在 agent:bootstrap 阶段从配置的 glob/路径模式注入额外的工作区引导文件
  • command-logger:把所有命令事件记录到 ~/.openclaw/logs/commands.log
  • boot-md:Gateway 启动时运行 BOOT.md(需要启用 internal hooks)

列出可用 hooks:

openclaw hooks list

启用一个 hook:

openclaw hooks enable session-memory

检查 hook 状态:

openclaw hooks check

查看详细信息:

openclaw hooks info session-memory

引导配置

在引导流程(openclaw onboard)中,会提示你启用推荐的 hooks。向导会自动发现符合条件的 hooks 供你选择。

Hook 发现

Hooks 从三个目录自动发现(按优先级排列):

  1. 工作区 hooks<workspace>/hooks/(每个 agent 独立,最高优先级)
  2. 托管 hooks~/.openclaw/hooks/(用户安装的,跨工作区共享)
  3. 内置 hooks<openclaw>/dist/hooks/bundled/(随 OpenClaw 分发)

托管 hook 目录可以是单个 hookhook 包(package 目录)。

每个 hook 是一个包含以下文件的目录:

my-hook/
├── HOOK.md          # 元数据 + 文档
└── handler.ts       # 处理程序实现

Hook 包(npm/归档)

Hook 包是标准的 npm 包,通过 package.json 中的 openclaw.hooks 导出一个或多个 hooks。安装方式:

openclaw hooks install <path-or-spec>

npm spec 仅限注册表(包名 + 可选的精确版本或 dist-tag)。Git/URL/文件 spec 和 semver 范围会被拒绝。

裸 spec 和 @latest 走稳定通道。如果 npm 把它们解析成了预发布版本,OpenClaw 会停下来要你用预发布标签(如 @beta/@rc)或精确版本号显式确认。

package.json 示例:

{
  "name": "@acme/my-hooks",
  "version": "0.1.0",
  "openclaw": {
    "hooks": ["./hooks/my-hook", "./hooks/other-hook"]
  }
}

每个条目指向一个包含 HOOK.mdhandler.ts(或 index.ts)的 hook 目录。Hook 包可以带依赖;安装到 ~/.openclaw/hooks/<id> 下。每个 openclaw.hooks 条目在符号链接解析后必须留在包目录内;逃逸的条目会被拒绝。

安全提示:openclaw hooks installnpm install --ignore-scripts 安装依赖(不执行生命周期脚本)。hook 包的依赖树要保持”纯 JS/TS”,避免依赖需要 postinstall 构建的包。

Hook 结构

HOOK.md 格式

HOOK.md 文件包含 YAML frontmatter 的元数据加 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:文档 URL
  • requires:可选的依赖要求
    • bins:PATH 中需要的可执行文件(如 ["git", "node"]
    • anyBins:这些可执行文件中至少要有一个
    • env:需要的环境变量
    • config:需要的配置路径(如 ["workspace.dir"]
    • os:需要的平台(如 ["darwin", "linux"]
  • always:跳过资格检查(布尔值)
  • install:安装方式(内置 hooks 用 [{"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,              // 如 'new', 'reset', 'stop', 'received', 'sent'
  sessionKey: string,          // 会话标识
  timestamp: Date,             // 事件发生时间
  messages: string[],          // 往这里 push 消息可以发给用户
  context: {
    // 命令事件:
    sessionEntry?: SessionEntry,
    sessionId?: string,
    sessionFile?: string,
    commandSource?: string,    // 如 'whatsapp', 'telegram'
    senderId?: string,
    workspaceDir?: string,
    bootstrapFiles?: WorkspaceBootstrapFile[],
    cfg?: OpenClawConfig,
    // 消息事件(完整细节见消息事件部分):
    from?: string,             // message:received
    to?: string,               // message:sent
    content?: string,
    channelId?: string,
    success?: boolean,         // message:sent
  }
}

事件类型

命令事件

agent 命令发出时触发:

  • command:所有命令事件(通用监听器)
  • command:new:发出 /new 命令时
  • command:reset:发出 /reset 命令时
  • command:stop:发出 /stop 命令时

会话事件

  • session:compact:before:压缩操作总结历史之前
  • session:compact:after:压缩完成并生成摘要元数据之后

内部 hook 负载以 type: "session"action: "compact:before" / action: "compact:after" 发出;监听器用上面的组合键订阅。具体的处理程序注册用 ${type}:${action} 格式。对这些事件,注册 session:compact:beforesession:compact:after

Agent 事件

  • agent:bootstrap:工作区引导文件注入之前(hook 可以修改 context.bootstrapFiles

Gateway 事件

Gateway 启动时触发:

  • gateway:startup:频道启动且 hooks 加载完成之后

消息事件

消息收发时触发:

  • message:所有消息事件(通用监听器)
  • message:received:从任何频道收到入站消息时触发。在媒体理解处理之前的早期阶段触发。内容可能包含尚未处理的原始占位符如 <media:audio>
  • message:transcribed:消息被完全处理后触发,包括音频转录和链接理解。此时 transcript 包含音频消息的完整转录文本。需要访问转录后音频内容时用这个 hook。
  • message:preprocessed:每条消息在所有媒体 + 链接理解完成后触发,让 hook 能访问完全增强后的内容(转录、图片描述、链接摘要),此时 agent 还没看到这些内容。
  • message:sent:出站消息成功发送时

消息事件上下文

消息事件包含丰富的上下文信息:

// message:received 上下文
{
  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 上下文
{
  to: string,             // 接收者标识
  content: string,        // 已发送的消息内容
  success: boolean,       // 发送是否成功
  error?: string,         // 发送失败时的错误信息
  channelId: string,      // 频道(如 "whatsapp", "telegram", "discord")
  accountId?: string,     // 提供商账号 ID
  conversationId?: string, // 聊天/对话 ID
  messageId?: string,     // 提供商返回的消息 ID
  isGroup?: boolean,      // 此出站消息是否属于群组/频道上下文
  groupId?: string,       // 群组/频道标识,用于与 message:received 关联
}

// message:transcribed 上下文
{
  body?: string,          // 增强前的原始入站内容
  bodyForAgent?: string,  // agent 可见的增强后内容
  transcript: string,     // 音频转录文本
  channelId: string,      // 频道(如 "telegram", "whatsapp")
  conversationId?: string,
  messageId?: string,
}

// message:preprocessed 上下文
{
  body?: string,          // 原始入站内容
  bodyForAgent?: string,  // 媒体/链接理解后的最终增强内容
  transcript?: string,    // 有音频时的转录文本
  channelId: string,      // 频道(如 "telegram", "whatsapp")
  conversationId?: string,
  messageId?: string,
  isGroup?: boolean,
  groupId?: string,
}

示例:消息日志 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;

工具结果 Hooks(插件 API)

这些 hooks 不是事件流监听器;它们让插件在 OpenClaw 持久化工具结果之前同步调整结果。

  • tool_result_persist:在工具结果写入会话转录之前进行转换。必须同步;返回更新后的工具结果负载,或 undefined 保持原样。见 Agent Loop

插件 Hook 事件

通过插件 hook runner 暴露的压缩生命周期 hooks:

  • before_compaction:压缩前运行,带计数/token 元数据
  • after_compaction:压缩后运行,带压缩摘要元数据

未来事件

计划中的事件类型:

  • session:start:新会话开始时
  • session:end:会话结束时
  • agent:error:agent 遇到错误时

创建自定义 Hook

1. 选位置

  • 工作区 hooks<workspace>/hooks/):每个 agent 独立,最高优先级
  • 托管 hooks~/.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. 启用并测试

# 确认 hook 被发现
openclaw hooks list

# 启用
openclaw hooks enable my-hook

# 重启 gateway 进程(macOS 上重启菜单栏应用,或重启开发进程)

# 触发事件
# 通过消息频道发送 /new

配置

新配置格式(推荐)

{
  "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"]
      }
    }
  }
}

旧配置格式(仍然支持)

旧的配置格式为了向后兼容仍然可用:

{
  "hooks": {
    "internal": {
      "enabled": true,
      "handlers": [
        {
          "event": "command:new",
          "module": "./hooks/handlers/my-handler.ts",
          "export": "default"
        }
      ]
    }
  }
}

注意:module 必须是工作区相对路径。绝对路径和逃出工作区的路径会被拒绝。

迁移建议:新 hook 用基于发现的新系统。旧的 handlers 在目录 hooks 之后加载。

CLI 命令

列出 Hooks

# 列出所有 hooks
openclaw hooks list

# 只显示符合条件的 hooks
openclaw hooks list --eligible

# 详细输出(显示缺失的依赖)
openclaw hooks list --verbose

# JSON 输出
openclaw hooks list --json

Hook 信息

# 显示某个 hook 的详细信息
openclaw hooks info session-memory

# JSON 输出
openclaw hooks info session-memory --json

检查资格

# 显示资格摘要
openclaw hooks check

# JSON 输出
openclaw hooks check --json

启用/禁用

# 启用 hook
openclaw hooks enable session-memory

# 禁用 hook
openclaw hooks disable command-logger

内置 hook 参考

session-memory

发出 /new 时把会话上下文保存到记忆。

事件command:new

依赖:需要配置 workspace.dir

输出<workspace>/memory/YYYY-MM-DD-slug.md(默认 ~/.openclaw/workspace

工作原理

  1. 使用重置前的会话条目定位正确的转录
  2. 提取最后 15 行对话
  3. 用 LLM 生成描述性的文件名 slug
  4. 把会话元数据保存到带日期的记忆文件

输出示例

# 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 生成失败时的时间戳回退)

启用

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 检查)。
  • 只加载已识别的引导文件基础名。
  • 子 agent 允许列表被保留(仅限 AGENTS.mdTOOLS.md)。

启用

openclaw hooks enable bootstrap-extra-files

command-logger

把所有命令事件记录到集中的审计文件。

事件command

依赖:无

输出~/.openclaw/logs/commands.log

工作原理

  1. 捕获事件详情(命令动作、时间戳、会话键、发送者 ID、来源)
  2. 以 JSONL 格式追加到日志文件
  3. 后台静默运行

日志条目示例

{"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

boot-md

Gateway 启动时运行 BOOT.md(在频道启动之后)。需要启用 internal hooks。

事件gateway:startup

依赖:需要配置 workspace.dir

工作原理

  1. 从工作区读取 BOOT.md
  2. 通过 agent runner 执行其中的指令
  3. 通过消息工具发送请求的出站消息

启用

openclaw hooks enable boot-md

最佳实践

保持处理程序轻快

Hooks 在命令处理期间运行,别搞太重:

// ✓ 好 - 异步工作,立即返回
const handler: HookHandler = async (event) => {
  void processInBackground(event); // 发射后不管
};

// ✗ 差 - 阻塞命令处理
const handler: HookHandler = async (event) => {
  await slowDatabaseQuery(event);
  await evenSlowerAPICall(event);
};

优雅处理错误

风险操作一定要包 try-catch:

const handler: HookHandler = async (event) => {
  try {
    await riskyOperation(event);
  } catch (err) {
    console.error("[my-handler] Failed:", err instanceof Error ? err.message : String(err));
    // 不要抛出 - 让其他 handler 继续运行
  }
};

尽早过滤事件

不相关的事件直接 return:

const handler: HookHandler = async (event) => {
  // 只处理 'new' 命令
  if (event.type !== "command" || event.action !== "new") {
    return;
  }

  // 业务逻辑
};

使用精确的事件键

元数据中尽量指定具体事件:

metadata: { "openclaw": { "events": ["command:new"] } } # 精确

而不是:

metadata: { "openclaw": { "events": ["command"] } } # 笼统 - 开销更大

调试

启用 Hook 日志

Gateway 启动时会记录 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

检查发现

列出所有被发现的 hooks:

openclaw hooks list --verbose

检查注册

在处理程序中加日志确认是否被调用:

const handler: HookHandler = async (event) => {
  console.log("[my-handler] Triggered:", event.type, event.action);
  // 业务逻辑
};

验证资格

检查某个 hook 为什么不符合条件:

openclaw hooks info my-hook

看输出中是否有缺失的依赖。

测试

Gateway 日志

监控 gateway 日志观察 hook 执行:

# macOS
./scripts/clawlog.sh -f

# 其他平台
tail -f ~/.openclaw/gateway.log

直接测试 Hooks

单独测试处理程序:

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);

  // 断言副作用
});

架构

核心组件

  • 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:Gateway 启动时加载 hooks
  • src/auto-reply/reply/commands-core.ts:触发命令事件

发现流程

Gateway 启动

扫描目录(工作区 → 托管 → 内置)

解析 HOOK.md 文件

检查资格(可执行文件、环境变量、配置、平台)

从符合条件的 hooks 加载处理程序

为事件注册处理程序

事件流程

用户发送 /new

命令验证

创建 hook 事件

触发 hook(所有已注册的处理程序)

命令处理继续

会话重置

排障

Hook 没被发现

  1. 检查目录结构:

    ls -la ~/.openclaw/hooks/my-hook/
    # 应该看到:HOOK.md, handler.ts
  2. 验证 HOOK.md 格式:

    cat ~/.openclaw/hooks/my-hook/HOOK.md
    # 应该有带 name 和 metadata 的 YAML frontmatter
  3. 列出所有被发现的 hooks:

    openclaw hooks list

Hook 不符合条件

检查依赖:

openclaw hooks info my-hook

看是否缺少:

  • 可执行文件(检查 PATH)
  • 环境变量
  • 配置值
  • 操作系统兼容性

Hook 没有执行

  1. 确认 hook 已启用:

    openclaw hooks list
    # 启用的 hooks 旁边应该有 ✓
  2. 重启 gateway 进程让 hooks 重新加载。

  3. 检查 gateway 日志有没有错误:

    ./scripts/clawlog.sh | grep hook

处理程序错误

检查 TypeScript/import 错误:

# 直接测试导入
node -e "import('./path/to/handler.ts').then(console.log)"

迁移指南

从旧配置迁移到发现系统

之前

{
  "hooks": {
    "internal": {
      "enabled": true,
      "handlers": [
        {
          "event": "command:new",
          "module": "./hooks/handlers/my-handler.ts"
        }
      ]
    }
  }
}

之后

  1. 创建 hook 目录:

    mkdir -p ~/.openclaw/hooks/my-hook
    mv ./hooks/handlers/my-handler.ts ~/.openclaw/hooks/my-hook/handler.ts
  2. 创建 HOOK.md:

    ---
    name: my-hook
    description: "My custom hook"
    metadata: { "openclaw": { "emoji": "🎯", "events": ["command:new"] } }
    ---
    
    # My Hook
    
    Does something useful.
  3. 更新配置:

    {
      "hooks": {
        "internal": {
          "enabled": true,
          "entries": {
            "my-hook": { "enabled": true }
          }
        }
      }
    }
  4. 确认并重启 gateway 进程:

    openclaw hooks list
    # 应该看到:🎯 my-hook ✓

迁移的好处

  • 自动发现
  • CLI 管理
  • 资格检查
  • 更好的文档
  • 统一的结构

另见