Skip to content

Hooks 机制

Hooks 系统让插件可以在关键生命周期事件中注入自定义逻辑——消息拦截、工具调用包装、会话管理、日志审计等。

可用 Hooks

Source: src/plugins/hooks.ts

Hook 名称一览

Hook 名称触发时机典型用途
gateway-startGateway 启动完成初始化外部服务
gateway-stopGateway 关闭前清理资源
session-start会话开始加载会话上下文
session-end会话结束保存会话状态
before-agent-startAgent 开始执行前注入上下文
message-received收到用户消息消息拦截、过滤
message-sending发送消息前消息修改、审计
message-sent消息发送成功后日志记录
before-tool-call工具调用前权限检查、参数修改
after-tool-call工具调用后结果处理、审计
before-compaction上下文压缩前保存重要信息
after-compaction上下文压缩后恢复状态
tool-result-persist工具结果持久化时数据归档

Hook 注册

typescript
// src/plugins/hooks.ts (simplified)
interface PluginHookRegistration<K extends PluginHookName> {
  event: K;                    // Hook event name
  handler: PluginHookHandler<K>;  // Handler function
  priority?: number;           // Execution priority (lower = earlier)
}

插件通过 API 注册 Hook:

typescript
// Example: audit logging hook
api.registerHook({
  event: "message-sent",
  handler: async (ctx) => {
    await auditLog.record({
      sessionKey: ctx.sessionKey,
      channel: ctx.channel,
      direction: ctx.direction,
      timestamp: Date.now(),
    });
  },
  priority: 100,  // Run after other hooks
});

Hook 上下文类型

每种 Hook 接收不同的上下文:

Agent 上下文

typescript
interface PluginHookAgentContext {
  runId: string;           // Agent run ID
  config: AgentConfig;     // Agent configuration
  workspaceDir: string;    // Workspace directory
  agentDir: string;        // Agent directory
}

消息上下文

typescript
interface PluginHookMessageContext {
  sessionKey: string;      // Session key
  channel: string;         // Source channel
  senderId: string;        // Sender identifier
  direction: "received" | "sending" | "sent";  // Message direction
}

工具上下文

typescript
interface PluginHookToolContext {
  runId: string;           // Agent run ID
  toolName: string;        // Tool being called
  // before: includes args
  // after: includes result
}

会话上下文

typescript
interface PluginHookSessionContext {
  sessionKey: string;      // Session key
  channel: string;         // Channel
}

执行模型

Hook 执行的关键特性:

特性说明
并行执行同一事件的多个 handler 并行运行
错误隔离单个 handler 抛出不影响其他 handler
优先级排序数字越小越先执行
Fire-and-forget大部分 hook 不等待结果

Gateway Hooks

Source: src/gateway/hooks.ts, src/gateway/hooks-mapping.ts

Gateway 层有自己的 Hooks 映射,将配置文件中的 hook 定义映射到运行时:

typescript
// src/gateway/hooks-mapping.ts (simplified)
// Maps config-defined hooks to runtime registrations
// Supports file-based hook definitions
// Validates hook event names and handler paths

小结

  • 13 种 Hook 事件覆盖 Gateway、Session、Agent、Message、Tool 五个生命周期
  • Hook 通过 priority 排序,并行执行错误隔离
  • 四种上下文类型提供事件相关的数据
  • 插件通过 api.registerHook() 注册,支持动态添加
  • Gateway 层额外支持基于配置文件的 Hook 定义

下一章:CLI 概述

OpenClaw 源码学习教程