架构设计文档¶
本文档面向开发者,介绍 OpenClaw-Py 的整体架构、核心组件和设计决策。
1. 总览¶
OpenClaw-Py (PyClaw) 是一个多通道 AI 网关,将 AI Agent 连接到 26+ 消息平台。当前版本 v5.0 (Production Scale & Ecosystem Alignment),6125 个测试用例。
核心设计目标:
- 通道无关:Agent 逻辑与通道解耦,新通道只需实现
ChannelPlugin接口 - Provider 无关:统一的流式接口屏蔽 LLM 差异
- 可扩展:通过 Python entry_points 和 SKILL.md 注入能力
- 跨平台:TypeScript 客户端在桌面、移动端、Web 复用同一套代码
系统架构图¶
flowchart TB
subgraph Clients["客户端"]
UI["TypeScript Client<br/>(Web/Desktop/Mobile)"]
CLI["CLI (Typer)"]
ACP["ACP Bridge"]
end
subgraph Gateway["Gateway (FastAPI)"]
WS["WebSocket v3"]
HTTP["HTTP API"]
RPC["RPC Handlers"]
OAI["OpenAI Compat"]
end
subgraph Runtime["Agent Runtime"]
Runner["Runner Loop"]
Harness["Agent Harness<br/>(E+T+C+S+L+V)"]
MultiAgent["Multi-Agent<br/>Orchestration"]
Collaboration["Collaboration<br/>Modes"]
end
subgraph Tools["工具层"]
BuiltIn["内置工具"]
MCP["MCP Tools"]
Skills["Skills"]
MetaTools["Meta-Tools"]
end
subgraph LLM["LLM Providers"]
OpenAI["OpenAI"]
Anthropic["Anthropic"]
Google["Google"]
Ollama["Ollama"]
end
UI --> WS
CLI --> WS
ACP --> HTTP
WS --> RPC
HTTP --> OAI
RPC --> Runner
OAI --> Runner
Runner --> Harness
Runner --> MultiAgent
Runner --> Collaboration
Runner --> Tools
BuiltIn --> Runner
MCP --> Runner
Skills --> Runner
MetaTools --> Runner
Runner --> LLM 数据流图¶
sequenceDiagram
participant User as 用户
participant Channel as 通道
participant Gateway as Gateway
participant Agent as Agent Runtime
participant LLM as LLM Provider
participant Tools as 工具
User->>Channel: 发送消息
Channel->>Gateway: on_message callback
Gateway->>Agent: chat.send RPC
Agent->>Agent: 追加到会话
Agent->>Agent: 构建系统提示
loop 推理循环
Agent->>LLM: stream(messages, tools)
LLM-->>Agent: text delta / tool_call
alt 工具调用
Agent->>Tools: execute(tool, args)
Tools-->>Agent: result
Agent->>Agent: 追加工具结果
end
end
Agent-->>Gateway: chat.done event
Gateway-->>Channel: send_reply
Channel-->>User: 回复消息 2. 核心组件¶
2.1 Gateway Server¶
src/pyclaw/gateway/server.py
- FastAPI 应用,暴露 WebSocket (
/ws) 和 HTTP 端点 - WebSocket 采用 JSON 帧协议 v3,支持请求/响应/事件三种帧类型
- 方法分发:按
method字段路由到methods/下的处理函数 - 支持多客户端并发连接
- 启动时加载插件 (
_load_plugins) 和配置监控 (_start_config_watcher)
class GatewayServer:
def register_handler(self, method: str, handler: MethodHandler) -> None: ...
async def _dispatch(self, method: str, params: dict, conn: GatewayConnection) -> Any: ...
2.2 Agent Runtime¶
src/pyclaw/agents/runner.py
核心执行循环:
while not done:
response = await llm.stream(messages, tools)
for chunk in response:
if chunk.is_tool_call:
result = await tool_registry.execute(chunk.tool, chunk.args)
messages.append(tool_result(result))
elif chunk.is_text:
yield chunk.text
if no_tool_calls:
done = True
设计特点:
- 多 Provider 统一流式:
stream.py将 OpenAI / Anthropic / Gemini / Ollama 的流式 API 归一化为相同的 chunk 格式 - 工具执行沙箱:通过
tool_policy.py控制危险操作审批 - 会话持久化:JSONL DAG 格式,支持分支和压缩
- 会话锁:
session_lock.py防止并发修改 - 会话检查点:
session_checkpoint.py+session_recovery.py支持断点恢复 - 子 Agent:
subagents/管理 spawn / steer / kill 生命周期
Agent Runtime 核心模块¶
| 模块 | 文件 | 功能 |
|---|---|---|
| Runner | runner.py | 核心执行循环 |
| Stream | stream.py | 多 Provider 统一流式接口 |
| Session | session.py | JSONL DAG 会话存储 |
| System Prompt | system_prompt.py | 系统提示构建 |
| Tokens | tokens.py | Token 计数与估算 |
| Planner | planner.py | 任务规划器 |
| Auto Reply | auto_reply.py | 自动回复引擎 |
| Intent | intent.py | 意图识别 |
| Interrupt | interrupt.py | 中断处理 |
| Progress | progress.py | 进度追踪 |
| TTS | tts_extended.py | 语音合成扩展 |
| Link Understanding | link_understanding.py | 链接理解 |
| Model Catalog | model_catalog.py | LLM 模型目录 |
| Model Fallback | model_fallback.py | 模型降级策略 |
| Compaction Policy | compaction_policy.py | 压缩策略配置 |
2.3 Agent Models (模型适配)¶
src/pyclaw/agents/models/
支持多种 LLM Provider 的后端适配:
| 模块 | 功能 |
|---|---|
azure_openai.py | Azure OpenAI 适配 |
bedrock.py | AWS Bedrock 适配 |
cn_providers.py | 国内模型适配 (通义千问/文心一言/DeepSeek 等) |
extra_providers.py | 其他 Provider 扩展 |
2.4 Agent Harness Architecture (v5.0)¶
src/pyclaw/agents/harness/ — 8611 行 Python 代码,25 个模块
基于形式化定义 H = (E, T, C, S, L, V) 实现的六组件生产级 Agent 运行时。
┌──────────────────────────────────────────────────────────────┐
│ ExecutionLoop │
│ observe → think → act → (loop detect) → next step / stop │
├──────────────────────────────────────────────────────────────┤
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │
│ │ ToolRegistry │ │ContextManager│ │ StateStore │ │
│ │ • Metadata │ │ • Injection │ │ • Working (memory) │ │
│ │ • Schema Val │ │ • Compress │ │ • Session (SQLite) │ │
│ │ • RBAC │ │ • Budget │ │ • Persistent (FILE) │ │
│ │ • Rate Limit │ │ • Cache Mkrs │ │ • Checkpoint │ │
│ └──────────────┘ └──────────────┘ └──────────────────────┘ │
│ ┌──────────────┐ ┌──────────────────────┐ │
│ │ Lifecycle │ │ Evaluation │ │
│ │ Hooks │ │ • Component Eval │ │
│ │ • Permission │ │ • Trajectory Eval │ │
│ │ • Audit │ │ • LLM-as-Judge │ │
│ │ • Danger Blk │ └──────────────────────┘ │
│ └──────────────┘ │
└──────────────────────────────────────────────────────────────┘
六组件详解¶
| 组件 | 模块 | 核心功能 |
|---|---|---|
| E - Execution | loop.py, detector.py, declarative.py | observe-think-act 循环、循环检测 (滑动窗口相似度)、声明式计划接管 |
| T - Tool System | tool_registry.py, tool_metadata.py, tool_catalog.py, mcp_bridge.py, meta_tools.py, schema_utils.py, tool_schema.py | 9 项元信息注册、JSON Schema 校验、Agent 白名单 RBAC、速率限制、审计日志、Meta-Tool 统一入口 |
| C - Context | context_manager.py, compressor.py, budget.py, cache_markers.py | 混合注入模式、分层压缩 (近 N 轮 + 历史摘要 + 关键事实)、4 级降级、双缓存标记 |
| S - State | state_store.py, execution_log.py, checkpoint.py | 三层存储 (Working/Session/Persistent)、不可变日志追加、多级检查点回放 |
| L - Lifecycle | hooks.py, policy.py, integration.py | 6 类 HookPoint (任务/步骤/工具/状态/模型)、5 内置 Hook、RBAC 策略引擎 |
| V - Validation | evaluation.py, trajectory.py, llm_judge.py | 4 层评测体系、5 种轨迹问题检测、混合评测策略 (确定性 + LLM Judge) |
Phase 8: Tool Schema Optimization (Meta-Tools)¶
meta_tools.py— 4 个 Meta-Tool 统一入口 (invoke_skill,extend_capability,query_registry,dispatch_subtask)schema_utils.py— Token 估算与 Schema 优化- 16 个核心工具 + Meta-Tool 扩展模式,保持 Schema 稳定以提升缓存命中率
2.5 Multi-Agent System¶
src/pyclaw/agents/multiagent/ — 26 个模块
编排层 (orchestration/)¶
| 模块 | 功能 |
|---|---|
shared_state.py | SharedStateStore + 冲突检测 + 版本跟踪 |
communication.py | AgentCommunicationBus (发布/订阅 + 点对点) |
conflict.py | ConflictResolver (LWW/MERGE/HUMAN 三种策略) |
orchestrator.py | MultiAgentOrchestrator (并行/顺序分发 + 故障隔离) |
引擎层 (engines/)¶
| 引擎 | 文件 | 功能 |
|---|---|---|
| Centralized | centralized.py | 集中式编排 |
| DAG Scheduler | dag_scheduler.py | DAG 依赖调度 |
| Dynamic Decompose | dynamic_decompose.py | 动态任务分解 |
| Fork Swarm | fork_swarm.py | 分叉群模式 |
| Hybrid | hybrid.py | 混合模式 |
| Pipeline | pipeline.py | 流水线模式 |
任务分解 (decomposer/)¶
| 模块 | 功能 |
|---|---|
base.py | 分解器基类 |
heuristic.py | 启发式分解 |
llm.py | LLM 驱动的分解 |
基础设施¶
| 模块 | 功能 |
|---|---|
engine.py | 引擎 ABC + 工厂模式 |
types.py | 共享类型定义 |
manifest.py | Agent Manifest 管理 |
capability.py | 能力声明与匹配 |
polling.py | Agent 轮询管理 |
storage.py | Agent 状态持久化 |
registry/ | Agent 注册表 (singleton/thread_safe 实现) |
orchestrator_tools.py | 编排器工具集 |
2.6 Collaboration System¶
src/pyclaw/agents/collaboration/
Agent 协作模式系统,支持多种协作策略:
| 模块 | 功能 |
|---|---|
engine.py | 协作引擎核心 |
selector.py | Agent 选择器 |
tools.py | 协作工具集 |
types.py | 协作类型定义 |
协作模式 (modes/)¶
| 模式 | 功能 |
|---|---|
coordinator_worker.py | 协调器-工作者模式 |
custom_agent.py | 自定义 Agent 模式 |
dynamic_decompose.py | 动态分解协作 |
fork_swarm.py | 分叉群协作 |
协作基础设施¶
| 子模块 | 功能 |
|---|---|
context/sharing.py | 协作上下文共享 |
permission/tool_manager.py | 工具权限管理 |
storage/agent_registry.py | Agent 注册与存储 |
2.7 PACS (Provider Auth Credential Store)¶
src/pyclaw/agents/pacs/
Provider 认证凭据统一管理系统:
| 模块 | 功能 |
|---|---|
bus.py | 凭据消息总线 |
capability.py | 能力声明 |
config.py | 凭据配置 |
compat.py | 向后兼容适配 |
2.8 Built-in Agents¶
src/pyclaw/agents/builtin_agents/
预置 Agent 类型:
| Agent | 功能 |
|---|---|
explore_agent.py | 代码探索 Agent |
general_purpose_agent.py | 通用 Agent |
plan_agent.py | 规划 Agent |
2.9 Channels¶
src/pyclaw/channels/
25 个消息通道,每个通道是一个独立目录,包含 channel.py 实现 ChannelPlugin 基类:
class ChannelPlugin(ABC):
async def start(self) -> None: ...
async def stop(self) -> None: ...
async def send_reply(self, reply: ChannelReply) -> None: ...
def on_message(self, callback) -> None: ...
当前支持的通道:
| 通道 | 目录 |
|---|---|
| Telegram | telegram/ |
| Discord | discord/ |
| Slack | slack/ |
whatsapp/ | |
| DingTalk | dingtalk/ |
| Feishu | feishu/ |
| WeChat QQ | qq/ |
| LINE | line/ |
| Signal | signal/ |
| Matrix | matrix/ |
| iMessage | imessage/ |
| BlueBubbles | bluebubbles/ |
| Google Chat | googlechat/ |
| MS Teams | msteams/ |
| Mattermost | mattermost/ |
| Nextcloud | nextcloud/ |
| IRC | irc/ |
| Twitch | twitch/ |
| Nostr | nostr/ |
| Zalo | zalo/ |
| Zalo User | zalouser/ |
| Synology | synology/ |
| Tlon | tlon/ |
| Voice Call | voice_call/ |
Plugin SDK (plugin_sdk/)¶
定义了 20 个 Protocol 接口:
| Protocol | 用途 |
|---|---|
ConfigAdapter | 配置 schema + 验证 |
AuthAdapter | 认证 |
OutboundAdapter | 消息发送 |
ActionsAdapter | 反应、置顶 |
StreamingAdapter | 草稿/流式消息 |
HeartbeatAdapter | 连接心跳 |
DirectoryAdapter | 用户目录 |
| ... | 共 20 个 |
运行时通过 detect_capabilities(plugin) 探测通道支持哪些能力。
通道插件 (plugins/) 增强通道功能:onboarding、outbound、actions、normalize。
2.10 Memory System¶
src/pyclaw/memory/
完整的记忆管理系统,支持上下文压缩、对话持久化、长期记忆和智能检索:
┌─────────────────────────────────────────────────────────────┐
│ MemoryManager (统一接口) │
├─────────────────────────────────────────────────────────────┤
│ ┌────────────────┐ ┌────────────────┐ ┌───────────────┐ │
│ │ Compaction │ │ Persistence │ │ Long-term │ │
│ │ 上下文压缩 │ │ 对话持久化 │ │ 长期记忆 │ │
│ │ ContextChecker│ │ DialogStore │ │ MEMORY.md │ │
│ │ Summarizer │ │ DailyLog │ │ │ │
│ │ ToolCompactor │ │ LongTermMemory│ │ │ │
│ └───────┬────────┘ └───────┬────────┘ └───────┬───────┘ │
│ │ │ │ │
│ ┌───────▼───────────────────▼───────────────────▼───────┐ │
│ │ MemoryStore (存储层) │ │
│ │ ┌─────────────┐ ┌─────────────┐ │ │
│ │ │ SQLite FTS5 │ │ LanceDB │ │ │
│ │ │ (关键词搜索) │ │ (向量搜索) │ │ │
│ │ └──────┬──────┘ └──────┬──────┘ │ │
│ │ └──────────┬───────────────┘ │ │
│ │ ┌─────▼─────┐ │ │
│ │ │ Hybrid │ MMR + 时间衰减 │ │
│ │ │ Ranker │ │ │
│ │ └───────────┘ │ │
│ └────────────────────────────────────────────────────────┘ │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Hooks (Agent 集成) │ │
│ │ pre_reasoning: 自动检查上下文并触发压缩 │ │
│ └────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
核心组件¶
| 模块 | 功能 |
|---|---|
manager.py | 统一记忆管理接口,整合所有子模块 |
store.py | SQLite + FTS5 存储,支持全文检索 |
lancedb_backend.py | LanceDB 向量存储,语义搜索 |
hybrid.py | 混合检索:关键词 + 向量融合 |
mmr.py | MMR 重排序,减少冗余结果 |
temporal_decay.py | 时间衰减,近期记忆权重更高 |
上下文压缩 (compaction/)¶
| 模块 | 功能 |
|---|---|
context_checker.py | 检查上下文长度,判断是否需要压缩 |
summarizer.py | 使用 LLM 生成结构化摘要 |
tool_compactor.py | 压缩长工具输出,保留关键信息 |
持久化 (persistence/)¶
| 模块 | 功能 |
|---|---|
dialog_store.py | JSONL 格式对话记录,支持按日期存储 |
daily_log.py | 每日摘要日志管理 |
long_term.py | 长期记忆管理 (MEMORY.md) |
2.11 配置系统¶
src/pyclaw/config/
- Pydantic v2 schema (
schema.py):强类型配置模型,30+ 配置节 - JSON5 格式:支持注释和尾逗号
- 环境变量替换 (
env_substitution.py):${VAR}/${VAR:-default}语法 - $include 分拆 (
includes.py):大配置文件可拆分为多个 JSON5 - 版本迁移 (
migrations.py):v1 → v2 → v3 自动迁移 - 热重载 (
runtime_overrides.py):后台轮询检测文件变更,触发回调 - 原子写入 (
backup.py):先写临时文件再原子重命名,保留备份
2.12 MCP 客户端¶
src/pyclaw/mcp/
实现 MCP (Model Context Protocol) 客户端,连接外部工具服务器:
- stdio transport:启动子进程,通过 stdin/stdout 通信
- HTTP transport:通过 HTTP 连接远程 MCP 服务器
- 工具注册表:将发现的工具映射为 Agent 可用的 tool schema
- 配置格式兼容 Claude Desktop 和 Cursor
2.13 ACP (Agent Communication Protocol)¶
src/pyclaw/acp/
Agent 间通信协议桥接层:
| 模块 | 功能 |
|---|---|
acpx_runtime.py | ACPX 运行时 |
client.py | ACP 客户端 |
control_plane.py | 控制平面 |
event_mapper.py | 事件映射 |
2.14 其他核心模块¶
| 模块 | 路径 | 功能 |
|---|---|---|
| Browser | browser/ | 浏览器自动化 (agent_tools, bridge_server, navigation_guard, relay) |
| CLI | cli/ | Typer CLI 命令系统 |
| Constants | constants/ | 环境变量、运行时、存储常量定义 |
| Cron | cron/ | 定时任务调度 (scheduler, advanced, history) |
| Daemon | daemon/ | 守护进程管理 (systemd, launchd, schtasks, service) |
| Hooks | hooks/ | 外部事件钩子系统 (loader, registry, types) |
| Infra | infra/ | 基础设施 (archive, bonjour, delivery, exec_approvals) |
| Local Models | local_models/ | 本地模型管理 (chat_model, manager, schema) |
| Logging | logging/ | 日志系统 (config, redact, subsystem, advanced) |
| Markdown | markdown/ | Markdown 渲染 (IR, fences, channel_formats, render) |
| Media | media/ | 媒体处理 (audio, images, fetch, mime) |
| Node Host | node_host/ | Node.js 进程托管 (invoke, runner) |
| Pairing | pairing/ | 设备配对 (challenge, setup_code, store) |
| Plugins | plugins/ | 扩展系统 (extensions, loader, onboarding) |
| Process | process/ | 进程管理 (supervisor, command_queue) |
| Routing | routing/ | 消息路由 (bindings, dispatch, session_key) |
| Secrets | secrets/ | 密钥管理 (audit, plan, apply, resolve) |
| Security | security/ | 安全策略 |
| Shared | shared/ | 共享工具函数 |
| Social | social/ | Agent 社交网络 (clawdchat, moltbook, registry) |
| Terminal | terminal/ | 终端输出 (ansi, palette, table) |
| Token Aware | token_aware/ | Token 感知引擎 (anatomy, cerebrum, commands, buglog) |
| Wizard | wizard/ | 设置向导会话 |
| Auto Reply | auto_reply/ | 自动回复 (commands_core, commands_model, commands_registry, block_streaming) |
2.15 UI (TypeScript 客户端)¶
apps/ 目录下的跨平台 UI:
| 应用 | 技术 | 路由 |
|---|---|---|
web/ | Next.js 15 | /[locale]/chat, /[locale]/agents 等 |
desktop/ | Tauri 2.x | 原生桌面应用 |
mobile/ | Expo (React Native) | 移动应用 |
3. 数据流¶
3.1 用户消息 → Agent 回复¶
User (Web/Desktop/Mobile/CLI/Channel)
│
▼
Gateway.chat.send(sessionId, message)
│
▼
AgentRunner.run(session, message)
│
├─ append user message to session
│
├─ build system prompt (AGENTS.md + skills + context)
│
├─ Harness: check budget → inject context → run hooks
│
├─ LLM.stream(messages, tools)
│ │
│ ├─ text delta → push chat.delta event
│ │
│ └─ tool_call → ToolRegistry.execute()
│ │
│ ├─ built-in tool
│ ├─ MCP tool (stdio/HTTP)
│ ├─ Meta-Tool (invoke_skill, dispatch_subtask)
│ └─ approval gate (if exec/patch)
│
├─ Harness: log execution → evaluate trajectory → checkpoint
│
├─ append assistant message to session
│
└─ push chat.done event
3.2 通道消息路由¶
Channel (Telegram/Discord/...)
│
▼
ChannelPlugin.on_message(callback)
│
▼
ChannelManager → Routing (7-tier priority)
│
▼
AgentRunner.run(...) ← 选定的 Agent
│
▼
Channel.send_reply(response)
路由优先级:
- 会话绑定 (session → agent)
- 线程绑定 (thread → agent)
- 通道绑定 (channel → agent)
- 群组绑定 (chat_id → agent)
- 用户绑定 (sender → agent)
- 全局绑定 (pattern match)
- 默认 Agent
4. 安全模型¶
4.1 命令执行审批¶
Agent 请求执行命令
│
▼
ToolGuards.check_policy(command)
│
├─ allow_list → 直接执行
├─ deny_list → 拒绝
└─ approval_required → 推送审批请求到 UI/CLI
│
▼
用户审批/拒绝
4.2 工作区沙箱¶
- 工具操作限制在配置的工作区目录内
- 文件路径规范化防止目录遍历
- 环境变量过滤敏感信息
4.3 网络安全¶
- SSRF 防护:阻止对内网 IP / DNS 重绑定的请求
- Secret 扫描:检测配置中的明文密钥并警告 (
pyclaw secrets audit) - Gateway 绑定:默认绑定
127.0.0.1,防止未授权访问 - TLS 指纹:验证远程连接的证书
5. 配置层次结构¶
配置文件采用 JSON5 格式,支持注释、尾逗号和环境变量引用。
graph TD
subgraph Config["pyclaw.json 配置结构"]
Models["models<br/>LLM Provider 与模型"]
Agents["agents<br/>Agent 默认设置"]
Channels["channels<br/>消息通道"]
Tools["tools<br/>工具与 MCP"]
Session["session<br/>会话管理"]
Gateway["gateway<br/>网关设置"]
Cron["cron<br/>定时任务"]
Memory["memory<br/>记忆系统"]
UI["ui<br/>界面设置"]
end
subgraph Providers["models.providers"]
P1["openai"]
P2["anthropic"]
P3["google"]
P4["ollama"]
P5["自定义 Provider"]
end
subgraph ChannelList["channels"]
C1["telegram"]
C2["discord"]
C3["slack"]
C4["dingtalk"]
C5["其他 21 个..."]
end
subgraph ToolsConfig["tools"]
T1["exec (命令执行)"]
T2["mcpServers"]
T3["restrictToWorkspace"]
end
Models --> Providers
Channels --> ChannelList
Tools --> ToolsConfig 配置优先级¶
flowchart LR
A["环境变量<br/>PYCLAW_*"] --> B["配置文件<br/>~/.pyclaw/pyclaw.json"]
B --> C["$include 分拆文件"]
C --> D["默认值"]
style A fill:#f9f,stroke:#333
style B fill:#bbf,stroke:#333
style C fill:#bfb,stroke:#333
style D fill:#ddd,stroke:#333 优先级说明:
- 环境变量:最高优先级,如
OPENAI_API_KEY覆盖配置中的值 - 配置文件:主配置
pyclaw.json - $include 分拆:通过
$include引入的子配置文件 - 默认值:代码中定义的安全默认值
环境变量替换¶
配置中可使用 ${VAR} 或 ${VAR:-default} 语法引用环境变量:
{
models: {
providers: {
openai: { apiKey: "${OPENAI_API_KEY}" },
anthropic: { apiKey: "${ANTHROPIC_API_KEY:-}" },
},
},
}
6. 扩展机制¶
6.1 Plugin (entry_points)¶
通过 Python entry_points 机制自动发现第三方插件:
# 第三方包的 pyproject.toml
[project.entry-points."pyclaw.plugins"]
my_plugin = "my_package.plugin:MyPlugin"
Gateway 启动时自动加载所有已安装的插件。
6.2 SKILL.md¶
Agent 能力注入:
技能在 Agent 系统提示中被注入,可通过 ClawHub marketplace 安装。
6.3 Hook 系统¶
事件钩子 (HOOK.md):
支持 before_send / after_send / on_error 等生命周期钩子。
7. 设计决策¶
| 决策 | 选择 | 理由 |
|---|---|---|
| Web 框架 | FastAPI | 原生 async,WebSocket 支持好 |
| CLI 框架 | Typer + Rich | 类型安全 + 丰富输出 |
| 配置格式 | JSON5 | 支持注释,兼容 JSON |
| 会话存储 | JSONL (文件) | 无需数据库,便于调试 |
| 向量引擎 | LanceDB | 零配置,嵌入式 |
| UI 框架 | Next.js / Tauri / Expo | TypeScript 跨平台 |
| LLM 流式 | 统一 chunk 格式 | 屏蔽 Provider 差异 |
| 进程管理 | asyncio subprocess | 与 async 架构一致 |
| 日志 | stdlib logging | 无额外依赖 |
| 类型系统 | Pydantic v2 | 验证 + 序列化 |
| 记忆存储 | SQLite + LanceDB | 混合检索,兼顾精确与语义 |
| 上下文压缩 | LLM 摘要 | 结构化摘要,保留关键上下文 |
| 对话持久化 | JSONL + 按日期分片 | 便于管理和归档 |
| 长期记忆 | Markdown 文件 | 人类可读,便于编辑 |
| Agent 运行时 | Harness 六组件 | 生产级可靠性,形式化验证 |
| Token 优化 | Meta-Tool + 双缓存 | 16 核心工具 + Skill 扩展 |
| 多 Agent 编排 | 发布/订阅 + 共享状态 | 解耦通信,灵活编排 |
8. 目录结构¶
src/pyclaw/
├── __init__.py
├── main.py # 入口
│
├── agents/ # Agent 运行时
│ ├── runner.py # 核心循环
│ ├── stream.py # 多 Provider 流式
│ ├── session.py # 会话存储
│ ├── system_prompt.py # 系统提示构建
│ ├── tokens.py # Token 计数
│ ├── planner.py # 任务规划器
│ ├── intent.py # 意图识别
│ ├── interrupt.py # 中断处理
│ ├── progress.py # 进度追踪
│ ├── definition.py # Agent 定义
│ ├── runtime.py # 运行时抽象
│ ├── compat.py # 兼容层
│ │
│ ├── harness/ # Agent Harness 六组件 (25 模块, 8611 行)
│ │ ├── loop.py # ExecutionLoop (E)
│ │ ├── detector.py # 循环检测
│ │ ├── declarative.py # 声明式计划
│ │ ├── tool_registry.py # Tool 注册表 (T)
│ │ ├── tool_metadata.py # 工具元信息
│ │ ├── tool_catalog.py # 核心工具目录
│ │ ├── tool_schema.py # JSON Schema 校验
│ │ ├── mcp_bridge.py # MCP → Harness 桥接
│ │ ├── meta_tools.py # Meta-Tool 统一入口 (Phase 8)
│ │ ├── schema_utils.py # Schema Token 优化 (Phase 8)
│ │ ├── context_manager.py # 上下文管理 (C)
│ │ ├── compressor.py # 分层压缩
│ │ ├── budget.py # Token Budget (4 级降级)
│ │ ├── cache_markers.py # 双缓存标记
│ │ ├── state_store.py # 三层状态存储 (S)
│ │ ├── execution_log.py # 不可变执行日志
│ │ ├── checkpoint.py # 多级检查点
│ │ ├── hooks.py # 6 类 Hook 点位 (L)
│ │ ├── policy.py # RBAC 策略引擎
│ │ ├── integration.py # HookedToolInvoker
│ │ ├── evaluation.py # 评测接口 (V)
│ │ ├── trajectory.py # 轨迹评测
│ │ ├── llm_judge.py # LLM Judge
│ │ └── types.py # 类型定义
│ │
│ ├── multiagent/ # 多 Agent 系统 (26 模块)
│ │ ├── engine.py # ABC + 工厂模式
│ │ ├── types.py # 共享类型
│ │ ├── manifest.py # Agent Manifest
│ │ ├── capability.py # 能力声明
│ │ ├── polling.py # 轮询管理
│ │ ├── storage.py # 状态持久化
│ │ ├── decomposer/ # 任务分解
│ │ ├── engines/ # 6 种编排引擎
│ │ ├── orchestration/ # 编排基础设施
│ │ │ ├── shared_state.py
│ │ │ ├── communication.py
│ │ │ ├── conflict.py
│ │ │ └── orchestrator.py
│ │ └── registry/ # Agent 注册表
│ │
│ ├── collaboration/ # Agent 协作系统
│ │ ├── engine.py # 协作引擎
│ │ ├── selector.py # Agent 选择
│ │ ├── tools.py # 协作工具
│ │ ├── context/ # 上下文共享
│ │ ├── modes/ # 4 种协作模式
│ │ ├── permission/ # 权限管理
│ │ └── storage/ # 注册存储
│ │
│ ├── models/ # LLM Provider 适配
│ │ ├── azure_openai.py
│ │ ├── bedrock.py
│ │ ├── cn_providers.py
│ │ └── extra_providers.py
│ │
│ ├── builtin_agents/ # 预置 Agent 类型
│ ├── pacs/ # Provider 凭据管理
│ ├── capabilities/ # 能力注册表
│ ├── auth/ # 认证模块
│ ├── auth_profiles/ # 认证配置文件
│ ├── context/ # 上下文引擎 (capability, compaction, compression)
│ ├── coordinator/ # 协调器模式
│ ├── sessions/ # 高级会话管理
│ ├── skills/ # SKILL.md 系统
│ ├── tools/ # 20+ 内置工具
│ ├── subagents/ # 子 Agent 管理
│ ├── embedded_runner/ # 嵌入式运行器
│ ├── transports/ # 传输层 (codex)
│ ├── export/ # 导出功能
│ ├── templates/ # 模板
│ └── utils/ # 异步桥接工具
│
├── gateway/ # Gateway 服务
│ ├── server.py # FastAPI + WebSocket
│ ├── openai_compat.py # OpenAI API 兼容层
│ ├── protocol/ # 帧定义
│ ├── methods/ # RPC 方法处理器
│ └── events.py # 事件广播
│
├── channels/ # 25 个消息通道
│ ├── base.py # ChannelPlugin 基类
│ ├── manager.py # 通道管理器
│ ├── plugin_sdk/ # 20 个 Protocol 接口
│ ├── plugins/ # 通道增强
│ └── <channel>/ # 各通道实现
│
├── memory/ # 记忆系统
│ ├── manager.py # 统一记忆管理器
│ ├── store.py # SQLite + FTS5 存储
│ ├── lancedb_backend.py # LanceDB 向量存储
│ ├── hybrid.py # 混合检索
│ ├── mmr.py # MMR 重排序
│ ├── temporal_decay.py # 时间衰减
│ ├── embeddings.py # 向量嵌入
│ ├── types.py # 类型定义
│ ├── compaction/ # 上下文压缩
│ ├── persistence/ # 持久化存储
│ ├── hooks/ # Agent 集成钩子
│ └── qmd/ # QMD 格式支持
│
├── config/ # 配置管理
├── mcp/ # MCP 客户端
├── acp/ # ACP 协议桥接
├── security/ # 安全策略
├── secrets/ # 密钥管理
├── hooks/ # 外部事件钩子
├── plugins/ # 扩展系统
├── routing/ # 消息路由
├── media/ # 媒体处理
├── markdown/ # Markdown 渲染
├── social/ # Agent 社交网络
├── infra/ # 基础设施
├── browser/ # 浏览器自动化
├── local_models/ # 本地模型管理
├── terminal/ # 终端输出
├── token_aware/ # Token 感知引擎
├── cron/ # 定时任务
├── daemon/ # 守护进程
├── process/ # 进程管理
├── pairing/ # 设备配对
├── wizard/ # 设置向导
├── logging/ # 日志系统
├── constants/ # 常量定义
├── node_host/ # Node.js 托管
├── auto_reply/ # 自动回复
├── shared/ # 共享工具
└── cli/ # CLI 命令
apps/ # TypeScript 客户端
├── web/ # Next.js 15 Web 应用
├── desktop/ # Tauri 2.x 桌面应用
└── mobile/ # Expo 移动应用
packages/ # 共享包
├── shared/ # 共享类型、API 客户端
└── ui/ # 共享 UI 组件
tests/ # 测试 (6125 用例)
├── pyclaw/ # 单元测试 (按模块组织)
├── integration/ # 集成测试
├── performance/ # 性能测试 (locust)
└── e2e_automation_test.py # E2E 自动化测试