概述

插件钩子是 OpenClaw 插件的进程内扩展点,用于拦截和修改 Agent 运行、工具调用、消息流、会话生命周期、子 Agent 路由、安装和 Gateway 启动等事件。

核心要点

钩子注册方式:

api.on("before_tool_call", async (event) => { ... }, { priority: 50 });
  • 处理器按 priority 降序执行,同优先级保持注册顺序
  • timeoutMs:可选的每钩子预算(超时后继续下一个处理器)

完整钩子目录(按分组):

Agent Turn(粗体=可决策):

  • before_model_resolve — 覆盖 Provider 或模型
  • agent_turn_prepare — 消费排队的插件 turn 注入
  • before_prompt_build — 添加动态上下文或系统提示文本
  • before_agent_run — 检查最终提示,可阻止运行
  • before_agent_reply — 用合成回复短路模型 turn
  • before_agent_finalize — 检查最终答案,请求额外模型 pass
  • agent_end — 观察最终消息、成功状态、运行时长

对话观察:

  • model_call_started / model_call_ended — Provider 调用元数据、时序、结果
  • llm_input / llm_output — 观察 Provider 输入/输出

工具:

  • before_tool_call — 重写参数、阻止执行或要求审批
  • after_tool_call — 观察工具结果、错误、时长
  • tool_result_persist — 重写工具结果产生的 assistant 消息

消息和交付:

  • inbound_claim — 在 Agent 路由前认领入站消息
  • message_received — 观察入站内容、发送者、线程
  • message_sending — 重写出站内容或取消交付
  • message_sent — 观察出站交付成功或失败

会话和压缩:

  • session_start / session_end — 会话生命周期边界
  • before_compaction / after_compaction — 压缩周期
  • before_reset — 会话重置事件

子 Agent:

  • subagent_spawning / subagent_delivery_target / subagent_spawned / subagent_ended

生命周期:

  • gateway_start / gateway_stop — 随 Gateway 启动/停止插件服务
  • cron_changed — Gateway cron 生命周期变化
  • before_install — 检查 skill 或插件安装,可阻止

before_tool_call 决策规则:

  • block: true — 终止,跳过低优先级处理器
  • block: false — 视为无决策
  • params — 重写工具参数
  • requireApproval — 暂停 Agent 运行,通过插件审批请求用户确认

需要对话访问权限的钩子(非 bundled 插件需配置):

{
  "plugins": {
    "entries": {
      "my-plugin": {
        "hooks": { "allowConversationAccess": true }
      }
    }
  }
}

适用于:before_model_resolve、before_agent_reply、llm_input、llm_output、before_agent_finalize、agent_end、before_agent_run

配置/使用

工具调用审批示例:

api.on("before_tool_call", async (event) => {
  if (event.toolName !== "web_search") return;
  return {
    requireApproval: {
      title: "Run web search",
      description: `Allow search query: ${String(event.params.query ?? "")}`,
      severity: "info",
      timeoutMs: 60_000,
      timeoutBehavior: "deny",
    },
  };
}, { priority: 50 });

运维配置钩子超时:

{
  "plugins": {
    "entries": {
      "my-plugin": {
        "hooks": {
          "timeoutMs": 30000,
          "timeouts": { "before_prompt_build": 90000 }
        }
      }
    }
  }
}

相关页面

  • concepts/plugin-building — 插件开发快速上手
  • concepts/plugin-architecture-internals — 内部机制深度参考
  • concepts/plugin-architecture — 插件能力模型