← 返回
未分类 中文

Hook Examples

Provides code examples demonstrating uses of various OpenClaw hooks to intercept, modify, validate, or block operations at different execution stages.
提供示例代码,演示OpenClaw钩子在各执行阶段拦截、修改、验证或阻止操作的方法。
hanxiao-bot hanxiao-bot 来源
未分类 clawhub v1.0.0 1 版本 100000 Key: 无需
★ 0
Stars
📥 354
下载
💾 1
安装
1
版本
#latest

概述

Hook Examples - OpenClaw Hook Usage Examples

Overview

OpenClaw supports 16+ Hook types that can intercept and modify behavior at various stages.

Available Hooks

HookTimingCan Block?
--------------------------
before_model_resolveBefore model resolution
before_prompt_buildBefore prompt building
before_tool_callBefore tool call
after_tool_callAfter tool call
message_sendingBefore message sending✅ cancel
message_sentAfter message sent
subagent_spawningBefore subagent spawn
subagent_endedAfter subagent ended

Example 1: Tool Audit Log

Record all tool calls to a file:

api.registerHook("before_tool_call", async ({ event, ctx }) => {
  const log = {
    time: new Date().toISOString(),
    tool: event.tool.name,
    params: event.tool.params,
    session: ctx.sessionKey
  };
  // Write to log file
  console.log("[TOOL_AUDIT]", JSON.stringify(log));
  return {}; // Don't block, continue execution
});

Example 2: Dangerous Tool Interception

Block dangerous tools in non-elevated sessions:

api.registerHook("before_tool_call", async ({ event, ctx }) => {
  const dangerous = ["gateway", "cron", "nodes"];
  if (dangerous.includes(event.tool.name) && !ctx.session.elevated) {
    return { 
      block: true, 
      reason: `Tool '${event.tool.name}' requires elevated permissions` 
    };
  }
  return {};
});

Example 3: Parameter Validation

Validate dangerous commands in exec tool:

api.registerHook("before_tool_call", async ({ event, ctx }) => {
  if (event.tool.name === "exec") {
    const cmd = event.tool.params.command || "";
    const dangerous = ["rm -rf", "dd if=", "mkfs", ":(){:|:&}:"];
    for (const d of dangerous) {
      if (cmd.includes(d)) {
        return { 
          block: true, 
          reason: `Dangerous command pattern detected: ${d}` 
        };
      }
    }
  }
  return {};
});

Example 4: Dynamic Model Switching

Switch models based on task type:

api.registerHook("before_model_resolve", async ({ event, ctx }) => {
  const msg = event.messages?.[0]?.content || "";
  if (msg.includes("write code") || msg.includes("debug")) {
    return { 
      model: "ollama/deepseek-r1:70b",
      provider: "ollama"
    };
  }
  if (msg.includes("document") || msg.includes("summary")) {
    return { 
      model: "ollama/qwen3:14b",
      provider: "ollama"
    };
  }
  return {};
});

Example 5: Subagent Result Routing

Custom subagent result delivery:

api.registerHook("subagent_ended", async ({ event, ctx }) => {
  // Do extra processing here
  console.log("[SUBAGENT_ENDED]", event.result);
  return {}; 
});

Registration

Register in the plugin's register(api):

export default definePluginEntry({
  id: "my-hook-plugin",
  name: "My Hook Plugin",
  register(api) {
    api.registerHook("before_tool_call", myHandler);
  }
});

Notes

  • Returning { block: true } from a hook blocks the operation
  • before_model_resolve can return { model, provider } to override
  • Hooks are synchronous; avoid long-running operations
  • Multiple hooks execute in priority order

版本历史

共 1 个版本

  • v1.0.0 当前
    2026-05-07 08:44 安全 安全

安全检测

腾讯云安全 (Keen)

安全,无风险
查看报告

腾讯云安全 (Sanbu)

安全,无风险
查看报告

🔗 相关推荐

ai-agent

Find Skills

guipi888
场景驱动+关键词双模式技能发现工具。当用户用自然语言描述场景/需求(如"我想做一个海报""帮我分析股票"),或明确说"安装技能/find skills/找个skill"时,自动从官方内置、本地已安装、SkillHub、虾评、GitHub、C
★ 1,473 📥 535,856
ai-agent

Self-Improving + Proactive Agent

ivangdavila
自我反思+自我批评+自我学习+自组织记忆。智能体评估自身工作、发现错误并持续改进。
★ 1,398 📥 323,054
dev-programming

Error Recovery

hanxiao-bot
错误恢复 - 优雅处理失败的策略
★ 0 📥 567