Claude Code 架构剖析
Claude Code 本质上是一个 Tool-use 驱动的 Agent Loop。核心流程:
while (task_not_complete) {
response = await claude.messages.create({
model: "claude-sonnet-4-20250514",
messages: conversation_history,
tools: available_tools,
system: system_prompt
});
if (response.stop_reason === "tool_use") {
for (const tool_call of response.content) {
result = await execute_tool(tool_call);
conversation_history.push({
role: "user",
content: [{ type: "tool_result", tool_use_id, content: result }]
});
}
}
}
关键点:
- Tool Definition:每个工具用 JSON Schema 描述输入参数,Claude 根据 schema 生成符合格式的调用
- Stop Reason:
tool_use表示需要执行工具,end_turn表示完成 - Context Accumulation:每轮 tool result 都追加到 conversation history,形成完整的执行轨迹
上下文管理机制
Claude Code 面临的核心挑战:如何在有限的 context window 中塞下足够的信息?
// 典型的上下文构成 System Prompt: ~2K tokens ├── Agent Instructions ├── Tool Definitions (10+ tools) └── Project Context (AGENTS.md, etc.) Conversation History: 动态增长 ├── User Messages ├── Assistant Responses └── Tool Results (代码文件内容、命令输出...) Available Budget: 200K - (system + history)
Claude Code 的策略:
- Lazy Loading:不预加载整个代码库,按需读取文件
- Prompt Caching:System prompt 和工具定义使用 cache_control 减少重复计算
- Truncation:大文件输出截断(如 2000 行 / 50KB 限制)
- Selective Context:通过 .claudeignore 排除无关文件
// Anthropic Prompt Caching 示例
{
"system": [
{
"type": "text",
"text": "You are Claude Code...",
"cache_control": { "type": "ephemeral" }
}
]
}
OpenClaw 源码分析
OpenClaw 是一个更完整的 Agent 运行时,架构比 Claude Code 复杂得多:
openclaw/ ├── dist/ # 编译后的 JS │ ├── entry.js # CLI 入口 │ ├── gateway-cli-*.js # Gateway 服务 │ ├── agent-*.js # Agent 核心 │ ├── skills-*.js # Skills 加载器 │ └── loader-*.js # 动态加载器 ├── skills/ # 内置 Skills (54 个) │ ├── discord/ │ ├── slack/ │ ├── coding-agent/ │ └── ... └── extensions/ # 插件目录
Sessions Spawn 机制
OpenClaw 支持多 Agent 协调,核心是 sessions_spawn:
// 主 Agent 可以 spawn 子 Agent
{
"action": "sessions_spawn",
"label": "code-review-agent",
"task": "Review PR #123 and post comments",
"model": "anthropic/claude-sonnet-4",
"thinking": "low"
}
Spawn 机制的实现要点:
- Session Isolation:每个 subagent 有独立的 conversation history
- Context Injection:通过 Subagent Context 注入任务描述
- Channel Routing:结果可以路由回原 channel 或直接返回给 parent agent
// Subagent 上下文注入示例
## Subagent Context
You are a **subagent** spawned by the main agent for a specific task.
- Label: ${label}
- Task: ${task}
- Requester session: ${parent_session}
- Your session: ${subagent_session}
Skills 加载机制
OpenClaw 的 Skills 系统采用 Progressive Disclosure 设计:
Level 1: Metadata (always loaded)
name + description (~100 tokens)
↓ 触发条件匹配
Level 2: SKILL.md body (on trigger)
完整指令 (<5K words)
↓ 需要详细信息
Level 3: Bundled Resources (on demand)
scripts/, references/, assets/
Skill 目录结构:
skill-name/ ├── SKILL.md # 必须,包含 YAML frontmatter ├── scripts/ # 可选,可执行脚本 ├── references/ # 可选,参考文档 └── assets/ # 可选,模板资源
SKILL.md frontmatter 是关键:
---
name: coding-agent
description: Run Codex CLI, Claude Code, OpenCode via background process
metadata:
openclaw:
emoji: "🧩"
requires:
anyBins: ["claude", "codex", "opencode", "pi"]
---
Skills 加载时只读 metadata,body 在触发后才加载。这是 context window 管理的核心策略。
Tool 注册与路由
OpenClaw 的工具通过 extensionAPI 注册:
// 工具定义结构
{
name: "browser",
description: "Control web browser via OpenClaw's browser control server",
parameters: {
type: "object",
properties: {
action: {
type: "string",
enum: ["status", "start", "stop", "snapshot", "screenshot", "act"]
},
// ...
}
}
}
// 工具执行路由
async function executeTool(name: string, params: object) {
const handler = toolRegistry.get(name);
return handler.execute(params, context);
}
实战:扩展开发
写一个 OpenClaw Skill
# 初始化 Skill python scripts/init_skill.py my-tool --path skills/custom --resources scripts,references # 生成结构 skills/custom/my-tool/ ├── SKILL.md ├── scripts/ └── references/
SKILL.md 写作要点:
- Description 是触发器:写清楚什么场景应该使用这个 skill
- Body 要精简:控制在 500 行以内
- 分层加载:详细内容放 references/,按需读取
---
name: xml-rpc-publisher
description: Publish content to WordPress via XML-RPC. Use when posting articles, updating pages, or managing WordPress content programmatically.
---
# WordPress XML-RPC Publisher
## Quick Start
```python
import xmlrpc.client
wp = xmlrpc.client.ServerProxy("https://blog.example.com/xmlrpc.php")
wp.wp.editPost(1, "user", "pass", post_id, {"post_content": content})
```
## Methods Reference
See [references/methods.md](references/methods.md) for complete API.
多 Agent 工作流编排
OpenClaw 的 subagent 机制适合并行任务:
// 并行 PR Review
const prs = [123, 124, 125];
for (const pr of prs) {
await sessions_spawn({
label: `pr-review-${pr}`,
task: `Review PR #${pr}, focus on security issues`,
model: "anthropic/claude-sonnet-4"
});
}
// 主 agent 继续其他工作,subagent 完成后自动报告
性能与限制
Token 消耗分析
| 组件 | 典型消耗 | 优化策略 |
|---|---|---|
| System Prompt | 2-5K | Prompt Caching |
| Tool Definitions | 3-8K | 动态加载,按需注入 |
| Skill Metadata | ~100/skill | 只加载 name+description |
| File Content | 变化大 | Truncation, offset/limit |
| Command Output | 变化大 | Truncation, grep 预处理 |
长上下文处理
// OpenClaw 的 Read 工具支持分页
{
"action": "read",
"path": "large-file.ts",
"offset": 1, // 起始行
"limit": 100 // 读取行数
}
// 对于大文件,分批读取比一次性加载更高效
// 200K context 听起来很大,但塞满的速度比你想象的快
并发任务管理
// background exec + process 管理
const { sessionId } = await exec({
command: "pnpm test",
background: true,
pty: true
});
// 轮询检查
while (true) {
const { running } = await process({ action: "poll", sessionId });
if (!running) break;
await sleep(5000);
}
// 获取输出
const { log } = await process({ action: "log", sessionId });
对比分析
vs Cursor Agent Mode
| 维度 | Claude Code / OpenClaw | Cursor |
|---|---|---|
| 运行环境 | CLI / 独立进程 | VSCode 扩展 |
| 上下文来源 | 显式 Tool 调用 | IDE 集成 + 自动索引 |
| 多模型 | 灵活切换 | 内置模型选择 |
| 可编程性 | 高(Skills, Hooks) | 低(GUI 为主) |
| CI/CD 集成 | 原生支持 | 需要额外配置 |
Cursor 的优势在于 IDE 深度集成和 零配置体验。Claude Code 的优势在于 Unix 哲学和 可组合性。
vs Aider
| 维度 | Claude Code / OpenClaw | Aider |
|---|---|---|
| 语言 | TypeScript | Python |
| Git 集成 | 可选 | 核心依赖 |
| Repo Map | 按需读取 | 预建索引 |
| Edit 格式 | Tool-based | Unified Diff / Whole File |
| 多模型 | Anthropic 为主 | 广泛支持 |
Aider 的 /map 命令预构建代码库索引,对大型项目有优势。Claude Code 更依赖模型的按需探索能力。
# Aider 的典型用法 aider --model claude-3-5-sonnet-20241022 /add src/ /architect "重构认证模块" # Claude Code 的典型用法 claude "重构 src/auth/ 中的认证模块" # 模型自己决定读取哪些文件
关键设计取舍
显式 vs 隐式上下文
- Claude Code:模型显式调用 Read 工具获取文件内容
- Cursor:IDE 自动提供当前文件、选中代码等上下文
- Aider:/add 显式添加,但 repo map 自动可用
显式调用更透明可控,但需要更多 round trip。隐式注入更流畅,但可能浪费 token。
Agent 自主性 vs 人类控制
// Claude Code 的 --dangerously-skip-permissions
// 跳过所有确认,完全自主执行
// OpenClaw 的 exec 策略
{
"security": "full", // 完全信任
"security": "allowlist", // 白名单命令
"security": "deny" // 禁止执行
}
更高的自主性意味着更快的执行,但风险也更大。生产环境建议使用 allowlist 策略。
总结
Claude Code 和 OpenClaw 代表了 CLI-first AI 编程工具的发展方向:
- Tool-use 是核心:通过结构化的工具调用实现 Agent 能力
- Context 管理是关键:Progressive Disclosure、Lazy Loading、Caching
- 可组合性是优势:Unix 管道、CI/CD 集成、多 Agent 协调
选择哪个工具取决于你的工作流:
- 需要 IDE 集成 → Cursor
- 需要 CLI 自动化 → Claude Code
- 需要多渠道 + 复杂编排 → OpenClaw
- 需要广泛模型支持 → Aider