Harness 与 Agent 工程 · 运行控制与长任务 · 2026-04-24

800行代码实现 Open Claw 的 Tool、消息总线、子Agent管理架构

探索Open Claw框架的轻量化设计哲学,800行代码实现三大核心模块,展现工程确定性的优雅解法。

核心内容:

  1. Tool系统的极简抽象与直接对接API设计
  2. 消息总线与子Agent管理的显式控制流实现
  3. 薄抽象层带来的调试优势与扩展潜力

这篇文章记录对 Open Claw 中 Tool、消息总线和子 Agent 管理架构的研究学习,以及一个最小可运行实现。本文想说明的技术观点是对于 Tool 调用、消息分发、子 Agent 管理这三类 Agent 系统里的核心组件,优先采用薄抽象、显式控制流和贴近模型 API 的实现方式,往往比引入多层中间件更容易获得工程上的确定性。系统边界更清晰,运行路径更容易追踪,问题更容易定位,也更适合作为后续扩展 Memory、调度和持久化能力的基础。

引言 这是一个基于 Anthropic Claude API 的 Agent 框架,用 TypeScript 编写,运行在单进程 Node.js 环境中。本文记录其中四个核心模块的实现:工具系统(Tool layer)、消息总线(MessageBus)、子 Agent 管理(SubagentManager)、REPL 主循环。不涉及上层 Bot 接入层、持久化、Context / Memory 系统。

框架不依赖 LangChain 或其他 Agent 框架,直接基于 Anthropic SDK 构建。选择这条路的原因很简单:中间层越薄,调试越容易,对 API 行为的控制越精确。

基础设施:Tool 抽象与 ToolRegistry

▐Tool 抽象类

一个工具由四个要素组成:name、description、input_schema、execute。

export abstract class Tool { abstract readonly name: string; abstract readonly description: string; abstract readonly input_schema: AnthropicTool["input_schema"]; abstract execute(args: Record<string, unknown>): Promise<unknown>; toSchema(): AnthropicTool { return { name: this.name, description: this.description, input_schema: this.input_schema, }; }}

input_schema 的类型直接取自 @anthropic-ai/sdk 的 Tool 类型定义。toSchema() 将实例转换为 Anthropic API 要求的 function calling schema。没有中间层转换,SDK 类型就是唯一的 schema 定义。

这里有一个刻意的取舍:schema 使用运行时普通对象定义,而非 Zod 等库。好处是零额外依赖、直接对齐 SDK 类型。代价是没有运行时参数校验——LLM 传入的参数如果类型不对,只能靠 execute 内部的 as 断言和实际调用时的错误来兜底。对于当前规模,这个取舍可以接受。

▐ToolRegistry

注册表本身是一个 Map<string, Tool>:

export class ToolRegistry { private tools = new Map<string, Tool>(); register(tool: Tool) { this.tools.set(tool.name, tool); } async execute(name: string, args: Record<string, unknown>) { const tool = this.tools.get(name); if (!tool) throw new Error(`Tool "${name}" not found`); return tool.execute(args); } getToolDefinition(): AnthropicTool[] { return Array.from(this.tools.values()).map((tool) => tool.toSchema()); } exclude(names: string[]): ToolRegistry { const excludeSet = new Set(names); const filtered = new ToolRegistry(); for (const [name, tool] of this.tools) { if (!excludeSet.has(name)) { filtered.register(tool); } } return filtered; }}

exclude() 是为子 Agent 设计的。子 Agent 不应该持有 spawn(避免递归创建子 Agent)、message(避免直接向用户发消息)等工具,所以需要从主 Agent 的工具集中排除特定工具,生成一个受限子集。exclude() 返回新的 ToolRegistry 实例,不修改原注册表。

内置工具一览

▐文件操作

ReadFileTool — 读取文件内容,动态 import("node:fs/promises") 加载模块。

WriteFileTool — 写入文件。写入前调用 mkdir(dirname(path), { recursive: true }) 自动创建父目录,避免因目录不存在而失败。

EditFileTool — 精确文本替换。核心逻辑:

const occurrences = content.split(oldText).length - 1;if (occurrences === 0) { return `Error: old_text not found in ${filePath}`;}if (occurrences > 1) { return `Warning: old_text found ${occurrences} times in ${filePath}. Please provide a more unique text snippet. No changes made.`;}const updated = content.replace(oldText, newText);

强制唯一匹配:出现 0 次报错,超过 1 次拒绝写入并要求提供更精确的文本片段。这个设计是为了防止 LLM 给出模糊的替换目标,导致意外修改多处代码。

ListDirTool — 列出目录内容,对每个条目做 stat,用 [folder] 和 [file] 前缀区分类型。

▐命令执行

ExecTool — 执行 shell 命令。三层防护:

第一层,危险命令正则黑名单:

const DANGEROUS_PATTERNS: RegExp[] = [ /rm\s+(-[a-zA-Z]*f[a-zA-Z]*\s+)?(-[a-zA-Z]*r[a-zA-Z]*\s+)?\/($|\s)/, /rm\s+-[a-zA-Z]*rf?\s+~($|\/|\s)/, /mkfs\b/, /dd\s+if=/, /:\(\)\s*\{\s*:\|:\s*&\s*\}\s*;/, // fork bomb />\s*\/dev\/[sh]d[a-z]/, // 写入裸设备 /chmod\s+-R\s+777\s+\//,];

覆盖 rm -rf /、fork bomb、写裸设备等高危模式。需要说明的是,正则黑名单是最低限度的防线,不能替代沙箱隔离。

第二层,资源限制:默认30 秒超时,2MB maxBuffer。超时后进程被 kill,返回超时提示。

第三层,输出截断。超过 10,000 字符时取首尾各 5,000 字符,中间用截断标记连接:

function truncateOutput(text: string): string { if (text.length <= MAX_OUTPUT_LENGTH) return text; const half = Math.floor(MAX_OUTPUT_LENGTH / 2); return ( text.slice(0, half) + `\n\n--- truncated (${text.length} chars total) ---\n\n` + text.slice(-half) );}

保留首尾而非只取前 N 字符,是因为命令输出的末尾通常包含最有价值的信息(错误信息、统计摘要等)。

▐Web 能力

WebSearchTool — 封装 Brave Search API,返回结构化搜索结果。参数 count 可选,默认 5 条,上限 10 条。

WebFetchTool — 抓取 URL 内容。针对 HTML 页面内置了纯正则实现的 htmlToText 转换:

function htmlToText(html: string): string { return html .replace(/<script[\s\S]*?<\/script>/gi, "") .replace(/<style[\s\S]*?<\/style>/gi, "") .replace(/<(br|\/p|\/div|\/li|\/tr|\/h[1-6])[^>]*>/gi, "\n") .replace(/<[^>]+>/g, "") // HTML 实体解码... .replace(/[ \t]+/g, " ") .replace(/\n{3,}/g, "\n\n") .trim();}

没有使用 DOM 解析库(如 cheerio、jsdom),纯正则处理。对于大多数常规网页足够用,但对复杂嵌套结构可能丢失语义。内容超过 20,000 字符时截断。

▐通信与调度

MessageTool — 出站方向的消息通道。通过构造时注入的 sendCallback 向外部发送消息:

export class MessageTool extends Tool { constructor(private sendCallback: SendCallback) { super(); } async execute(args: Record<string, unknown>): Promise<string> { const content = args.content as string; const channel = (args.channel as string) ?? "repl"; const chatId = (args.chat_id as string) ?? "default"; await this.sendCallback({ channel, chatId, content }); return `Message sent to ${channel}:${chatId}`; }}

REPL 场景下sendCallback 就是 console.log;Bot 场景下替换为向 Telegram、Discord 等平台发送消息的函数。工具本身不关心消息最终去向。

CronTool + CronService — 定时任务管理,分为服务层和工具层。

CronService 基于 setInterval 实现,支持两种定时方式:every_seconds(直接转换为毫秒间隔)和 cron_expr(解析 cron 表达式为近似间隔)。

cron 表达式的解析是简化版本:

private parseCronInterval(expr: string): number { const parts = expr.trim().split(/\s+/); if (parts.length !== 5) return 60_000; const [minute, hour] = parts; /…
— 以上为试看内容(约 40%),开通会员后阅读全文 —

原文出处:https://www.53ai.com/news/Openclaw/2026042469048.html