Hooks

Hooks 提供一套可擴充的事件驅動系統,用於在代理指令和事件發生時自動執行動作。Hooks 會從目錄自動探索,並可透過 CLI 指令管理,類似 OpenClaw 中的 skills 運作方式。

快速認識

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

OpenClaw 出廠隨附四個會自動探索的內建 hooks:

  • session-memory:當你發出 /new 時,將工作階段上下文儲存到代理工作區(預設 ~/.openclaw/workspace/memory/
  • bootstrap-extra-files:在 agent:bootstrap 期間,從設定的 glob/path 模式注入額外的工作區啟動檔案
  • 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/(逐代理,最高優先)
  2. 受管理 hooks~/.openclaw/hooks/(使用者安裝,跨工作區共享)
  3. 內建 hooks<openclaw>/dist/hooks/bundled/(隨 OpenClaw 出貨)

受管理 hook 目錄可以是單一 hookhook 套件(package 目錄)。

每個 hook 是一個包含以下內容的目錄:

my-hook/
├── HOOK.md          # 元資料 + 文件
└── handler.ts       # 處理器實作

Hook 套件(npm/archives)

Hook 套件是標準的 npm 套件,透過 package.json 中的 openclaw.hooks 匯出一或多個 hooks。安裝方式:

openclaw hooks install <path-or-spec>

npm spec 僅限 registry(套件名稱 + 選用的精確版本或 dist-tag)。 Git/URL/file spec 和 semver 範圍會被拒絕。

裸 spec 和 @latest 走穩定軌道。如果 npm 將任一解析為預發行版本,OpenClaw 會停下來要求你用預發行 tag 如 @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 install 使用 npm 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 的顯示表情符號(例如 "💾"
  • 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.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[],          // 推入訊息以發送給使用者
  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
  }
}

事件類型

指令事件

在代理指令發出時觸發:

  • command:所有指令事件(通用監聽器)
  • command:new:發出 /new
  • command:reset:發出 /reset
  • command:stop:發出 /stop

工作階段事件

  • session:compact:before:壓縮摘要歷史之前
  • session:compact:after:壓縮完成並帶有摘要元資料之後

內部 hook payload 以 type: "session" 搭配 action: "compact:before" / action: "compact:after" 發出這些事件;監聽器使用上方的組合鍵訂閱。 具體的處理器註冊使用字面鍵格式 ${type}:${action}。對於這些事件,註冊 session:compact:beforesession:compact:after

代理事件

  • agent:bootstrap:工作區啟動檔案注入之前(hooks 可以修改 context.bootstrapFiles

Gateway 事件

Gateway 啟動時觸發:

  • gateway:startup:頻道啟動且 hooks 載入之後

訊息事件

訊息接收或發送時觸發:

  • message:所有訊息事件(通用監聽器)
  • message:received:從任何頻道接收到入站訊息時觸發。在媒體理解處理之前的早期階段觸發。內容可能包含尚未處理的原始佔位符如 <media:audio>
  • message:transcribed:訊息完全處理完成時,包括音訊轉錄和連結理解。此時 transcript 包含音訊訊息的完整轉錄文字。需要存取轉錄音訊內容時使用此 hook。
  • message:preprocessed:每則訊息在所有媒體 + 連結理解完成後觸發,讓 hooks 存取完全豐富化的內文(轉錄、圖片描述、連結摘要),在代理看到之前。
  • 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,  // 代理可見的豐富化內文
  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:在工具結果寫入工作階段記錄之前進行轉換。必須是同步的;回傳更新後的工具結果 payload 或 undefined 以保持原樣。參閱 Agent Loop

外掛 Hook 事件

透過外掛 hook 執行器公開的壓縮生命週期 hooks:

  • before_compaction:壓縮前,帶有計數/token 元資料
  • after_compaction:壓縮後,帶有壓縮摘要元資料

未來事件

計劃中的事件類型:

  • session:start:新工作階段開始時
  • session:end:工作階段結束時
  • agent:error:代理遇到錯誤時

建立自訂 Hooks

1. 選擇位置

  • 工作區 hooks<workspace>/hooks/):逐代理,最高優先
  • 受管理 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 上重啟選單列 app,或重啟你的開發行程)

# 觸發事件
# 透過你的訊息頻道發送 /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 必須是工作區相對路徑。絕對路徑和穿越工作區外的路徑會被拒絕。

遷移:新 hooks 請使用基於探索的新系統。舊版處理器在目錄型 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 產生描述性的檔名前綴
  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 檢查)。
  • 僅載入被認可的啟動基本檔名。
  • 子代理允許清單已保留(僅限 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. 透過代理執行器執行指示
  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);
};

優雅處理錯誤

對有風險的操作務必加上包裝:

const handler: HookHandler = async (event) => {
  try {
    await riskyOperation(event);
  } catch (err) {
    console.error("[my-handler] Failed:", err instanceof Error ? err.message : String(err));
    // 不要拋出 - 讓其他處理器繼續執行
  }
};

盡早篩選事件

如果事件不相關,盡早回傳:

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 檔案

檢查符合條件(bins、env、config、os)

從符合條件的 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)
  • 環境變數
  • 設定值
  • OS 相容性

Hook 未執行

  1. 確認 hook 已啟用:

    openclaw hooks list
    # 啟用的 hooks 旁邊應該顯示 ✓
  2. 重新啟動 Gateway 行程以重新載入 hooks。

  3. 檢查 Gateway 日誌是否有錯誤:

    ./scripts/clawlog.sh | grep hook

處理器錯誤

檢查 TypeScript/import 錯誤:

# 直接測試 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 管理
  • 符合條件檢查
  • 更好的文件
  • 一致的結構

另請參閱