Claude Code 架构总览
本文档基于
@anthropic-ai/claude-codev2.1.88 反编译源码分析整理。
目录
项目概述
Claude Code 是 Anthropic 发布的 AI 编程助手 CLI 工具,核心是一个生产级 ReAct Agent 循环。其架构在标准 LLM 工具调用循环之上,叠加了以下生产级能力:
| 能力 | 实现 |
|---|---|
| 权限管控 | 多层权限规则 + 交互式确认 |
| 流式执行 | AsyncGenerator + 并发工具调度 |
| 上下文压缩 | autoCompact / snipCompact / contextCollapse |
| 子 Agent | 进程内 / fork 进程 / 远程 Agent |
| 会话持久化 | JSONL append-only 磁盘日志 |
| MCP 协议 | Model Context Protocol 服务器集成 |
| 遥测 | OpenTelemetry + 双端汇报 |
| 特性开关 | Bun 编译期 feature() DCE |
整体分层架构
┌─────────────────────────────────────────────────────────────────────┐
│ 入口层 (Entry) │
│ cli.tsx ──> main.tsx ──> REPL.tsx (交互式) │
│ └──> QueryEngine.ts (无头/SDK 模式) │
└──────────────────────────────┬──────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────────┐
│ 查询引擎层 (Query) │
│ submitMessage(prompt) ──> AsyncGenerator<SDKMessage> │
│ ├── fetchSystemPromptParts() 组装系统提示 │
│ ├── processUserInput() 处理 /斜杠命令 │
│ ├── query() 主 Agent 循环 │
│ │ ├── StreamingToolExecutor 并发工具执行 │
│ │ ├── autoCompact() 上下文压缩 │
│ │ └── runTools() 工具编排 │
│ └── yield SDKMessage 流式输出给消费者 │
└──────────────────────────────┬──────────────────────────────────────┘
│
┌────────────────┼────────────────┐
▼ ▼ ▼
┌──────────────────┐ ┌─────────────────┐ ┌──────────────────┐
│ 工具系统层 │ │ 服务层 │ │ 状态管理层 │
│ │ │ │ │ │
│ Tool Interface │ │ api/claude.ts │ │ AppState Store │
│ ├─ call() │ │ compact/ │ │ ├─ permissions │
│ ├─ validate() │ │ mcp/ │ │ ├─ fileHistory │
│ ├─ checkPerms() │ │ analytics/ │ │ ├─ agents │
│ └─ render() │ │ tools/executor │ │ └─ fastMode │
│ │ │ settingsSync/ │ │ │
│ 40+ 内置工具: │ │ oauth/ │ │ React Context │
│ BashTool 等 │ │ plugins/ │ │ useAppState() │
└──────────────────┘ └─────────────────┘ └──────────────────┘
│ │
▼ ▼
┌──────────────────┐ ┌─────────────────┐
│ 任务系统层 │ │ 桥接层 │
│ │ │ │
│ LocalShellTask │ │ bridgeMain.ts │
│ LocalAgentTask │ │ bridgeApi.ts │
│ RemoteAgentTask │ │ workSecret.ts │
│ DreamTask │ │ sessionRunner │
└──────────────────┘ └─────────────────┘
入口层
文件结构
| 文件 | 职责 |
|---|---|
src/entrypoints/cli.tsx |
CLI 引导入口,处理版本查询、子命令分发 |
src/main.tsx |
主程序体(~4683 行),Commander 参数解析、初始化链 |
src/entrypoints/init.ts |
单例初始化:配置、遥测、OAuth、策略加载 |
src/entrypoints/sdk/ |
Agent SDK 模式入口 |
src/entrypoints/mcp.ts |
MCP 服务器入口 |
启动流程
cli.tsx
│
├── --version 快路径 → 直接输出退出
├── MCP 子命令 → mcp.ts
├── daemon 子命令 → daemon/main.js (feature-gated)
├── bridge 子命令 → bridge/bridgeMain.ts
├── tmux/worktree 子命令 → 特殊模式
└── 默认路径 → main.tsx
│
└── init() → 配置加载 → 策略 → 遥测 → OAuth
│
├── 交互式 REPL → renderAndRun()
└── 无头模式 → launchRepl() / QueryEngine
查询引擎层
这是整个系统的核心,包含两个主要文件:
src/query.ts --- 主 Agent 循环
这是代码库中最大的单文件(~785KB),实现了完整的 ReAct Agent 循环:
- 流式 API 调用 :通过
services/api/claude.ts向 Anthropic API 发起流式请求 - 工具执行调度 :
StreamingToolExecutor实现并发安全的工具执行 - 上下文管理 :监控 token 用量,在接近上限时触发
autoCompact - Hook 系统:PreToolUse / PostToolUse 钩子,支持外部程序介入工具调用
- 技能预取 :
skillPrefetch预加载可能需要的技能
src/QueryEngine.ts --- SDK/无头模式引擎
面向 SDK 场景的生命周期管理器:
processUserInput()--- 解析输入和斜杠命令fetchSystemPromptParts()--- 组装系统提示(含 CLAUDE.md 内存)query()--- 调用核心循环submitMessage()--- 流式 AsyncGenerator 接口
工具系统层
详见 tools.md。
工具接口
每个工具通过 buildTool() 工厂函数创建,实现以下接口:
typescript
interface Tool<Input, Output, Progress> {
// 生命周期
validateInput(input: unknown): ValidationResult
checkPermissions(context: ToolUseContext): PermissionResult
call(input: Input, context: ToolUseContext): AsyncGenerator<Progress, Output>
// 能力标志
isEnabled(): boolean
isConcurrencySafe(): boolean
isReadOnly(): boolean
isDestructive(): boolean
interruptBehavior(): 'cancel' | 'block'
// UI 渲染 (React/Ink)
renderToolUseMessage(input: Input): ReactNode
renderToolResultMessage(output: Output): ReactNode
renderToolUseProgressMessage(progress: Progress): ReactNode
// AI 端
prompt(): string
description(): string
}
工具分类
| 类别 | 工具 |
|---|---|
| 文件操作 | FileReadTool, FileEditTool, FileWriteTool, NotebookEditTool |
| 搜索发现 | GlobTool, GrepTool, ToolSearchTool |
| 代码执行 | BashTool, PowerShellTool |
| Web/网络 | WebFetchTool, WebSearchTool |
| Agent/任务 | AgentTool, SendMessageTool, TaskCreate/Update/Get/List/Stop |
| 团队协作 | TeamCreateTool, TeamDeleteTool |
| MCP 协议 | MCPTool, ListMcpResourcesTool, ReadMcpResourceTool |
| 规划工作流 | EnterPlanModeTool, ExitPlanModeTool, TodoWriteTool |
| 系统工具 | ConfigTool, SkillTool, ScheduleCronTool |
| 用户交互 | AskUserQuestionTool, BriefTool |
服务层
详见 services.md。
| 服务 | 路径 | 职责 |
|---|---|---|
| API 客户端 | services/api/ |
Claude API 流式调用、重试、错误分类 |
| 上下文压缩 | services/compact/ |
autoCompact、snipCompact、contextCollapse |
| MCP 管理 | services/mcp/ |
MCP 服务器连接生命周期、认证 |
| 遥测 | services/analytics/ |
OpenTelemetry + GrowthBook |
| 工具执行器 | services/tools/ |
StreamingToolExecutor、toolOrchestration |
| 插件加载 | services/plugins/ |
插件生命周期管理 |
| 设置同步 | services/settingsSync/ |
跨设备配置同步 |
| OAuth | services/oauth/ |
身份认证流程 |
| 策略限制 | services/policyLimits/ |
策略与使用限制 |
| 远程配置 | services/remoteManagedSettings/ |
服务端托管的运行时设置 |
状态管理层
AppState Store
使用 Zustand 风格的 Store + React Context 模式:
typescript
interface AppState {
toolPermissionContext: {
mode: PermissionMode // 'default' | 'plan' | 'bypass'
additionalWorkingDirectories: string[]
alwaysAllowRules: Rule[] // 自动批准规则
alwaysDenyRules: Rule[] // 自动拒绝规则
alwaysAskRules: Rule[] // 强制询问规则
isBypassPermissionsModeAvailable: boolean
}
fileHistory: FileHistoryState // 文件操作快照(支持撤销)
attribution: AttributionState // commit 归因追踪
verbose: boolean
mainLoopModel: string // 当前使用的模型
fastMode: FastModeState
speculation: SpeculationState
}
React 集成
AppStateProvider--- 创建 Store,挂载到 React ContextuseAppState(selector)--- 选择器订阅,避免不必要重渲染useSetAppState()--- immer 风格的更新函数
任务系统层
任务(Task)是对长时间运行操作的抽象:
| 任务类型 | 文件 | 特点 |
|---|---|---|
local_bash |
LocalShellTask/ |
本地 Shell 命令,后台执行 |
local_agent |
LocalAgentTask/ |
本地子 Agent,共享进程 |
remote_agent |
RemoteAgentTask/ |
通过桥接层的远程 Agent |
in_process |
InProcessTeammateTask/ |
进程内 Teammate,共享状态 |
dream |
DreamTask/ |
后台思考,不占用对话轮次 |
workflow |
(feature-gated) | 工作流脚本执行 |
任务 ID 命名规则 :<prefix><8位字符>
b= bash 任务a= agent 任务r= 远程 agentt= teammate
桥接层
连接 Claude Desktop / Web UI 与 CLI:
Claude Desktop / Web UI Claude Code CLI
════════════════════════ ═════════════════
┌───────────────────┐ ┌──────────────────┐
│ Bridge Client │ ←─ HTTP ──→ │ bridgeMain.ts │
└───────────────────┘ │ Session Manager │
│ ├── spawn CLI │
PROTOCOL: │ ├── poll status │
├─ JWT 认证 │ ├── relay msgs │
├─ Work Secret 交换 │ └── capacityWake │
├─ Session 生命周期 │ │
│ ├── create │ Backoff 策略: │
│ ├── run │ ├─ conn: 2s→2m │
│ └─ stop │ └─ gen: 500ms→30s│
└─ Token 刷新调度 └──────────────────┘
关键设计模式
| 模式 | 位置 | 用途 |
|---|---|---|
| AsyncGenerator 流式 | QueryEngine, query() |
端到端流式传输,API 到消费者 |
| Builder + Factory | buildTool() |
工具安全默认值封装 |
| Branded Types | SystemPrompt, asSystemPrompt() |
防止 string/array 混淆 |
| Feature Flags + DCE | feature() from bun:bundle |
编译期死代码消除 |
| Discriminated Unions | Message 类型 |
类型安全的消息处理 |
| Observer + State Machine | StreamingToolExecutor |
工具执行生命周期追踪 |
| Snapshot State | FileHistoryState |
文件操作撤销/重做 |
| Ring Buffer | 错误日志 | 长会话的内存有界存储 |
| Fire-and-Forget Write | recordTranscript() |
非阻塞持久化(顺序保证) |
| Lazy Schema | lazySchema() |
延迟 Zod schema 求值 |
| Context Isolation | AsyncLocalStorage |
共享进程中的 per-Agent 上下文 |
特性开关系统
编译期(Bun):
feature('FLAG_NAME') ──→ true → 代码保留在 bundle 中
──→ false → 死代码消除
运行期:
process.env.USER_TYPE === 'ant' → Anthropic 内部功能
GrowthBook feature flags → A/B 实验,运行时动态修改
主要特性开关:
| Flag | 功能 |
|---|---|
COORDINATOR_MODE |
多 Agent 协调器模式 |
HISTORY_SNIP |
激进历史裁剪 |
CONTEXT_COLLAPSE |
上下文重构压缩 |
DAEMON |
后台 daemon 进程 |
KAIROS |
推送通知、自主 Agent 模式 |
VOICE_MODE |
语音输入/输出 |
WEB_BROWSER_TOOL |
浏览器自动化工具 |
EXPERIMENTAL_SKILL_SEARCH |
技能发现系统 |
WORKFLOW_SCRIPTS |
工作流脚本执行 |
PROACTIVE |
主动行为模式 |