乐于分享
好东西不私藏

OpenClaw源码分析(临时文章)

本文最后更新于2026-03-11,某些文章具有时效性,若有错误或已失效,请在下方留言或联系老夜

OpenClaw源码分析(临时文章)

OpenClaw 源码分析

模块化 · 可插拔 · 面向 agent 的网关 · 全通道集成

一、整体架构概览

OpenClaw 的 src 采用分层、插件化设计,核心原则:

  • WebSocket 控制平面
    :Gateway 作为中央枢纽
  • ACP (Agent Client Protocol)
    :标准化 agent ↔ gateway 通信
  • 插件化通道系统
    :可扩展的消息平台集成
  • 统一工具系统
    :沙箱执行 + API 抽象

二、核心目录结构

2.1 src/entry.ts – 入口点

  • 环境初始化 (env, profile, 过滤警告)
  • 抑制 Node.js 实验性警告
  • CLI 参数解析、快速路径 (–version/–help)
  • 进程自动重启 & 桥接
// 关键流程检查主模块入口 → 启用编译缓存 → 处理 experimentalWarning → 解析 profile → 快速路径 → 调用 cli/run-main

2.2 src/index.ts – 主模块导出

  • loadConfig, loadSessionStore
     – 配置加载
  • runExec, runCommandWithTimeout
     – 执行器
  • monitorWebChannel, getReplyFromConfig
     – 通道工具
  • normalizeE164, toWhatsappJid
     – 格式化工具

三、Gateway 核心系统

3.1 目录结构

gateway/call.ts (26KB) – 客户端调用、认证构建client.ts (18KB) – GatewayClient (重连/心跳/事件)server-channels.ts (16KB) – 通道管理 (status, probe, login)server-chat.ts (19KB) – 会话核心 (send, start, reset, abort)server-http.ts (25KB) – HTTP 路由 (dashboard, webhook, CORS)method-scopes.ts (5.3KB) – 权限范围 (chat:*, config:read, tools:invoke…)

认证模式

  • Token / Password / Device Token (本地回退)

方法范围 (OperatorScope)

type OperatorScope = 'chat:*' | 'agent:*' | 'config:read' | 'config:write' | 'gateway:*' | 'tools:invoke' | 'channels:*'

四、ACP (Agent Client Protocol)

src/acp/

  • control-plane/
     – Session 生命周期管理
  • runtime/
     – 注册表、错误处理
  • server.ts
     – ACP Gateway Agent (NDJSON 流)
  • translator.ts
     – 消息转换 & 流控制
// serveAcpGateway 核心步骤1. 连接 Gateway (WebSocket)2. 创建 AcpGatewayAgent3. 处理 Gateway 事件4. NDJSON 通信 (stdin/stdout)

五、Agents 系统

5.1 agents/ 核心模块

  • auth-profiles/
     – 多认证配置、OAuth、故障切换、配额
  • tools/
     – 统一工具集 (见下表)
  • sandbox/
     – Docker 沙箱执行
  • skills/
     – 技能系统
  • acp-spawn.ts
     – pi-agent 进程生成 (ACP隧道/直连)

内置工具 (部分)

工具
功能
大小
browser-tool.ts
CDP 浏览器控制
21KB
message-tool.ts
发送消息
27KB
nodes-tool.ts
设备节点 (camera, screen, canvas)
33KB
image-tool.ts
图像处理
18KB
cron-tool.ts
Cron 任务
20KB
discord-actions.ts
Discord API
19KB
gateway-tool.ts
Gateway 控制
8.8KB

六、Channels 系统

6.1 dock.ts – 通道抽象层

type ChannelDock = {  id: ChannelId;  capabilities: ChannelCapabilities;   // text, media, reactions...  commands?: ChannelCommandAdapter;  config?: ChannelConfigAdapter;  groups?: ChannelGroupAdapter;  mentions?: ChannelMentionAdapter;  threading?: ChannelThreadingAdapter;  streaming?: ChannelDockStreaming;}

内置通道插件

telegram, discord, slack, whatsapp, signal, imessage, googlechat, line …

注册顺序: CHAT_CHANNEL_ORDER

七、CLI 系统

cli/program.ts – Commander 定义run-main.ts – 主循环gateway-cli/ agent-cli/ channels-cli/ daemon-cli/ nodes-cli/profile.ts – 配置管理

命令示例: gatewayagentchannelsmessagesecretsonboard

八、配置系统

  • config.ts
     – 主配置加载
  • sessions.ts
     – session 存储
  • env.ts
     – 环境变量 (OPENCLAW_*)
  • gitops.ts
     – GitOps 支持

优先级: CLI 参数 > 环境变量 > 配置文件 (~/.openclaw/openclaw.json) > 默认值

九、安全 & Secret 管理

secrets/ – Secret 引用

type SecretInput =   | { _secretRef: string }   // 引用文件  | { _env: string }         // 环境变量  | string                    // 明文(不推荐)

解析: resolveSecretRefValues() 从文件/环境读取。

十、基础设施

  • infra/
     – format-time, net, tls, binaries, device-identity, ports
  • process/
     – exec, supervisor, child-process-bridge

十一、数据流架构

11.1 消息流

用户消息 (Telegram/WhatsApp等)  ↓ 通道插件解析  ↓ Gateway (chat.send)  ↓ Router 选择 session  ↓ ACP 翻译 → Agent  ↓ Agent 生成响应  ↓ ACP 翻译 ← Agent  ↓ Gateway (chat.reply)  ↓ 通道插件发送  ↓ 用户收到

11.2 工具调用流

Agent 请求工具  ↓ ACP (tool_call)  ↓ Gateway (tools.invoke)  ↓ 工具系统 (沙箱/直连)  ↓ 执行结果  ↓ Gateway (tool_result)  ↓ ACP 翻译  ↓ Agent 接收

十二、关键技术特性

12.1 WebSocket 协议 (NDJSON)

type GatewayMessage =  | { type: "hello" }  | { type: "hello_ok" }  | { type: "call", method: string, params: unknown }  | { type: "call_ok", result: unknown }  | { type: "call_error", error: Error }  | { type: "event", name: string, payload: unknown }

12.2 流式响应 BlockStreaming

{ minChars?: 1500, idleMs?: 1000 }

12.3 Docker 沙箱

  • 只读 workspace 挂载
  • 网络隔离 + 资源限制 + 超时

12.4 设备节点能力 (nodes-tool.ts)

camera.snap(), screen.record(), canvas.*, location.get(), notifications, system.run (macOS)

十三、状态管理

Session 结构

{  id: string;  title?: string;  config: SessionConfig;  messages: Message[];  createdAt: number;  updatedAt: number;}

操作: createSession, patchSession, pruneSession, loadSession (sessions/utils.ts 28KB)

配置热重载: gateway/config-reload.ts 基于 chokidar 差异更新。

十四、测试架构

  • *.test.ts
     – 单元测试
  • *.e2e.test.ts
     – 端到端
  • *.live.test.ts
     – 真实连接 (需要环境变量)
  • test-helpers/ + vitest.config.*.ts

十五、关键设计模式

  • 插件模式
     – ChannelPlugin 接口 (start/stop)
  • 适配器模式
     – ChannelCommandAdapter / ChannelConfigAdapter 等
  • 策略模式
     – 认证策略 (LastGood、轮询、冷却)
  • 观察者模式
     – gateway.on(‘event’, …) session.created 等

十六、性能优化

  • 编译缓存 (Node.js v23+ compile cache)
  • 动态 import 懒加载
  • 块流 (blockStreaming) 减少延迟

十七、总结

✅ 清晰分层 – 入口、Gateway、Agent、通道、配置、CLI 分离

✅ 插件化扩展 – 通道和工具可动态加载

✅ 标准化 ACP – 统一 agent 通信协议

✅ 安全沙箱 – 工具执行隔离,secret 管理

✅ 灵活配置 – 多优先级、GitOps、热重载


本站文章均为手工撰写未经允许谢绝转载:夜雨聆风 » OpenClaw源码分析(临时文章)

猜你喜欢

  • 暂无文章

评论 抢沙发

8 + 9 =