Skip to content

总体架构

Claude Code 采用 6 层分层架构,从底层运行时到顶层用户交互,每一层职责明确。

分层概览

┌─────────────────────────────────────────────────────────────────┐
│  Layer 6: UI 交互层 (Ink / React / Components / Hooks)          │
├─────────────────────────────────────────────────────────────────┤
│  Layer 5: 命令层 (commands/ — 70+ 斜杠命令 + 技能)             │
├─────────────────────────────────────────────────────────────────┤
│  Layer 4: 工具层 (tools/ — 40+ 内置工具 + MCP 扩展)             │
├─────────────────────────────────────────────────────────────────┤
│  Layer 3: 查询引擎层 (QueryEngine + queryLoop + TokenBudget)    │
├─────────────────────────────────────────────────────────────────┤
│  Layer 2: 服务层 (services/ — compact/analytics/mcp/lsp/oauth)  │
├─────────────────────────────────────────────────────────────────┤
│  Layer 1: 基础设施层 (state/bridge/entrypoints/utils/constants) │
└─────────────────────────────────────────────────────────────────┘

Layer 1: 基础设施层

最底层提供运行时基础:

模块文件数职责
state/6全局 AppState 存储,DeepImmutable 包装,80+ 字段
bridge/31与 claude.ai 的远程通信(轮询/WebSocket/SSE)
entrypoints/6CLI 入口、初始化、MCP 服务器入口
constants/21系统提示词、API 限制、错误码、OAuth 配置
utils/300+文件操作、Shell、Git、加密、模型、权限等
types/8全局类型定义

Layer 2: 服务层

独立的后台服务模块,各自管理自己的生命周期:

服务目录核心功能
compact/11 文件3 级会话压缩(微压缩→自动压缩→会话记忆)
analytics/9 文件Datadog + 1P OpenTelemetry 双通道遥测
mcp/23 文件MCP 协议客户端/服务器、工具转换、6 层配置合并
lsp/7 文件语言服务器协议集成(诊断、补全)
oauth/5 文件OAuth 2.0 + PKCE 认证流程
tools/4 文件工具执行引擎(StreamingToolExecutor,并发度10)
PromptSuggestion/下一轮提示预测 + 推测执行
SessionMemory/会话记忆管理,Markdown 文件维护

Layer 3: 查询引擎层

AI 交互的核心逻辑:

QueryEngine.submitMessage()
  └── queryLoop() — 无限 while 循环
       ├── Step 1:  prefetchBudget (预计算 token 预算)
       ├── Step 2:  snipMessages (截断超长工具输出)
       ├── Step 3:  microcompact (工具结果级压缩)
       ├── Step 4:  collapseMessages (上下文折叠)
       ├── Step 5:  autocompact (全会话自动压缩)
       ├── Step 6:  blockingCompact (阻塞压缩)
       ├── Step 7:  computeTokenBudget (最终 token 预算)
       ├── Step 8:  API call (流式请求 Claude API)
       ├── Step 9:  streamToolUses (并发工具执行)
       ├── Step 10: backfillResults (回填工具结果)
       ├── Step 11: errorRecovery (4 级错误恢复)
       └── Step 12: stopHooks (停止钩子检查)

Layer 4: 工具层

40+ 个工具的统一抽象:

typescript
interface Tool<Input, Output> {
  name: string
  description(input: Input, options: {
    isNonInteractiveSession: boolean
    toolPermissionContext: ToolPermissionContext
    tools: Tools
  }): Promise<string>
  inputSchema: Input
  call(args: Input, context: ToolUseContext, canUseTool: CanUseToolFn, parentMessage: Message): Promise<ToolResult<Output>>
  checkPermissions(input: Input, context: ToolPermissionContext): Promise<PermissionResult>
  isReadOnly(input: Input): boolean
  isDestructive?(input?: Input): boolean
  isConcurrencySafe(input: Input): boolean
}

工具分类:

  • 文件操作: FileReadTool, FileEditTool, FileWriteTool
  • 执行: BashTool, PowerShellTool, REPLTool
  • 搜索: GlobTool, GrepTool, WebSearchTool, ToolSearchTool
  • AI 代理: AgentTool (最复杂,14 个辅助模块)
  • MCP: MCPTool, ListMcpResourcesTool, ReadMcpResourceTool, McpAuthTool
  • 任务: TaskCreateTool, TaskGetTool, TaskListTool, TaskUpdateTool, TaskStopTool, TaskOutputTool
  • 其他: WebFetchTool, NotebookEditTool, TodoWriteTool, SleepTool, SkillTool...

Layer 5: 命令层

120+ 个斜杠命令通过 commands.ts 路由:

typescript
// Command 是联合类型,非 4 种而是 3 种
type Command = CommandBase &
  (PromptCommand | LocalCommand | LocalJSXCommand)

命令过滤系统:

  • REMOTE_SAFE_COMMANDS — 远程模式下可用
  • BRIDGE_SAFE_COMMANDS — Bridge 模式下可用
  • INTERNAL_ONLY_COMMANDS — 仅 Anthropic 内部可用

Layer 6: UI 交互层

基于自定义 Ink 渲染器的终端 UI 系统:

ink.tsx (核心引擎, ~900 行)
  ├── reconciler.ts (React 19 协调器)
  ├── dom.ts (虚拟 DOM)
  ├── renderer.ts (渲染管线)
  ├── screen.ts (屏幕缓冲)
  ├── yoga.ts (Yoga 布局引擎)
  ├── events/ (10 文件, 事件系统)
  ├── termio/ (9 文件, 终端协议)
  └── layout/ (布局适配器)

数据流架构

用户输入 → AI 响应流

用户输入 (PromptInput.tsx)

handlePromptSubmit() — 输入预处理

QueryEngine.submitMessage() — 构建消息

queryLoop() — 无限循环 {
    tokenBudget.compute() — 预算计算
    → API.createMessage() — 调用 Claude
    → streamToolUses() — 执行工具
    → backfill results — 回填结果
    → 检查 stop_reason
}

Messages.tsx — 渲染消息

VirtualMessageList — 虚拟滚动显示

工具执行流

API 返回 tool_use block

StreamingToolExecutor.execute()  (并发度 max=10)

tool.checkPermissions() — 权限检查
    ↓ (需要授权)
PermissionRequest UI — 用户确认
    ↓ (已授权)
tool.call(args, context, canUseTool, parentMessage)  — 执行工具

Promise<ToolResult<Output>> — 工具结果

tool_result 注入消息队列 — 下一轮循环

状态更新流

setState(updater) — 状态变更

Store.notify() — 通知订阅者

useSyncExternalStore() — React 组件同步

Ink reconciler — 重新协调

Yoga layout — 布局计算

Screen buffer diff — 差异渲染

Terminal ANSI output — 终端写入

模块依赖图

entrypoints/cli.tsx
  ├── entrypoints/init.ts → 5 阶段初始化
  │     ├── services/analytics → 遥测
  │     ├── services/mcp → MCP 客户端
  │     ├── utils/settings → 配置加载
  │     └── utils/auth → 认证
  ├── screens/REPL.tsx → 主界面
  │     ├── QueryEngine.ts → AI 查询
  │     │     ├── query.ts → 查询循环
  │     │     │     ├── services/compact → 压缩
  │     │     │     ├── services/tools → 工具执行
  │     │     │     └── query/tokenBudget → 预算
  │     │     └── Tool.ts → 工具接口
  │     ├── commands.ts → 命令路由
  │     │     ├── commands/*/ → 90+ 命令目录
  │     │     ├── skills/ → 技能系统
  │     │     └── plugins/ → 插件系统
  │     ├── state/AppState.tsx → 全局状态
  │     └── components/ → UI 组件树
  │           ├── App.tsx → 根组件
  │           ├── FullscreenLayout → 布局
  │           ├── VirtualMessageList → 虚拟列表
  │           └── PromptInput/ → 输入框
  └── bridge/ → 远程通信 (可选)
        ├── bridgeMain.ts → 主循环
        ├── bridgeMessaging.ts → 消息路由
        └── replBridgeTransport.ts → 传输层

构建架构

Claude Code 使用 Bun 作为构建工具和运行时,核心构建特点:

feature() 编译时消除

typescript
// 构建时根据编译目标,对应代码被完全消除
if (feature('VOICE_MODE')) {
  // 整个分支在非 VOICE_MODE 构建中被 tree-shake
  await import('./voice/voiceEngine')
}

延迟导入 + 动态 import

typescript
// 大多数模块使用 lazy dynamic import 减少启动时间
const { QueryEngine } = await import('./QueryEngine')

React Compiler Runtime

typescript
// 构建产物中自动注入 memo 化代码
import { c as _c } from "react/compiler-runtime"
// 消除手写 useMemo / useCallback 的需要