Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Claude Code 源码分析 - 项目总览

项目概述

Claude Code 是 Anthropic 官方推出的 CLI 工具,允许用户通过终端与 Claude AI 进行交互式对话,执行软件工程任务。项目使用 TypeScript 编写,基于 React Ink 构建终端 UI,采用 Bun 作为运行时和打包工具。

技术栈

技术用途
TypeScript主要开发语言
React + Ink终端 UI 框架(深度定制 Fork)
Bun运行时 & 打包工具
Zod运行时类型校验
Yoga LayoutFlexbox 布局引擎(纯 TS 简化移植)
OpenTelemetry可观测性/遥测
OAuth 2.0认证体系
WebSocket / SSE实时通信
MCP (Model Context Protocol)工具扩展协议

源码统计

  • 总文件数: 1884 个 TypeScript/TSX 文件
  • 模块目录数: 35 个顶层模块
  • 根级文件数: 18 个核心入口文件

整体架构拓扑

以下所有连线均基于源码 import 语句验证。实线 = 直接 import,虚线 = 间接依赖(通过 hooks 或 type-only import)。

graph TB
    subgraph Entry["🚀 入口层"]
        CLI["CLI 入口<br/><small>entrypoints/cli</small>"]
        SDK["SDK 入口<br/><small>entrypoints/sdk</small>"]
        MCP_E["MCP Server<br/><small>entrypoints/mcp</small>"]
    end

    subgraph Orchestrator["🎯 编排层"]
        Main["main.tsx<br/><small>4683 行 · 应用主入口<br/>初始化 · 工具注册 · 路由</small>"]
    end

    subgraph Bootstrap["⚡ 启动层"]
        BS["bootstrap/state<br/><small>全局状态 · 配置加载 · 认证</small>"]
    end

    subgraph UI["🖥️ 终端 UI 层"]
        REPL["REPL.tsx<br/><small>5005 行 · 主交互屏幕</small>"]
        Resume["ResumeConversation<br/><small>会话恢复</small>"]
        Doctor["Doctor<br/><small>系统诊断</small>"]
        Components["components/<br/><small>389 React 组件文件</small>"]
        INK["ink/<br/><small>定制 Ink 引擎<br/>Yoga 布局 · 事件系统<br/>终端协议栈</small>"]
    end

    subgraph Core["🧠 AI 交互核心"]
        QueryTS["query.ts<br/><small>1729 行 · 查询主循环</small>"]
        QueryDir["query/<br/><small>config · deps · tokenBudget<br/>stopHooks · transitions</small>"]
        Services["services/<br/><small>API 调用 · 流式处理<br/>消息压缩 · 分析</small>"]
    end

    subgraph ToolChain["🔧 工具链"]
        Tools["tools/<br/><small>40 个 AI 工具<br/>buildTool 工厂</small>"]
        Skills["skills/<br/><small>技能系统</small>"]
        Plugins["plugins/<br/><small>插件系统</small>"]
    end

    subgraph HookSys["🪝 钩子层"]
        ReactHooks["hooks/<br/><small>104 React Hooks</small>"]
        ExecHooks["utils/hooks/<br/><small>钩子执行引擎<br/>28 种生命周期事件</small>"]
    end

    subgraph Infra["🏗️ 基础设施"]
        State["state/<br/><small>AppState 状态管理</small>"]
        Context["context/<br/><small>上下文构建</small>"]
        Schemas["schemas/<br/><small>Zod 验证</small>"]
        Utils["utils/<br/><small>564 工具文件<br/>31 子目录</small>"]
        NativeTS["native-ts/<br/><small>yoga-layout<br/>file-index · 色差</small>"]
    end

    subgraph Connect["🌐 连接层"]
        Bridge["bridge/<br/><small>IDE 桥接</small>"]
        Remote["remote/<br/><small>远程会话</small>"]
        Server["server/<br/><small>HTTP/WS</small>"]
        Coord["coordinator/<br/><small>多实例协调</small>"]
    end

    subgraph Extra["✨ 增强功能"]
        KB["keybindings/<br/><small>17 上下文</small>"]
        Vim["vim/<br/><small>Vim 模式</small>"]
        Voice["voice/<br/><small>语音交互</small>"]
        Memdir["memdir/<br/><small>自动记忆</small>"]
        Tasks["tasks/<br/><small>后台任务</small>"]
    end

    %% 入口 → 编排
    CLI --> Main
    SDK --> Main
    MCP_E --> Main

    %% 编排层依赖(main.tsx 直接 import)
    Main --> BS
    Main --> Services
    Main --> Tools
    Main --> Skills
    Main --> Plugins
    Main --> Bridge
    Main --> Server
    Main --> Coord
    Main --> Remote

    %% 启动层 → 屏幕(screens 均 import bootstrap/state)
    BS --> REPL
    BS --> Resume
    BS --> Doctor

    %% REPL 直接 import(源码验证)
    REPL --> QueryTS
    REPL --> Components
    REPL --> ReactHooks
    REPL --> State
    REPL --> KB
    REPL --> Tasks
    REPL -.->|type only| Remote
    REPL -.->|type only| Server

    %% 组件 → 渲染引擎
    Components --> INK

    %% 查询核心(query.ts 直接 import)
    QueryTS --> QueryDir
    QueryTS --> Services
    QueryTS --> Tools
    QueryTS --> ExecHooks

    %% 查询子模块(query/stopHooks.ts 直接 import)
    QueryDir --> Services
    QueryDir --> Memdir
    QueryDir --> KB

    %% 钩子层
    ReactHooks --> ExecHooks
    ReactHooks -.->|间接访问| Bridge
    ReactHooks -.->|间接访问| Vim
    ReactHooks -.->|间接访问| Voice

    %% 基础设施
    INK --> NativeTS
    Services --> Utils
    Tools --> Utils
    ExecHooks --> Utils

    style Entry fill:#4a9eff,stroke:#2d7cd6,color:#fff
    style Orchestrator fill:#e056fd,stroke:#be2edd,color:#fff
    style Bootstrap fill:#ff9f43,stroke:#d68536,color:#fff
    style UI fill:#a55eea,stroke:#8344c4,color:#fff
    style Core fill:#ee5a24,stroke:#c44a1e,color:#fff
    style ToolChain fill:#6ab04c,stroke:#58964a,color:#fff
    style HookSys fill:#22a6b3,stroke:#1b8a94,color:#fff
    style Infra fill:#778ca3,stroke:#5f7186,color:#fff
    style Connect fill:#0fb9b1,stroke:#0c9690,color:#fff
    style Extra fill:#f7b731,stroke:#c99528,color:#fff

架构图连线依据

连线源码依据
CLI/SDK/MCP → main.tsx三个入口点均通过 main.tsx 启动应用
main.tsx → bootstrap/main.tsx:87from './bootstrap/state.js'
main.tsx → services/main.tsx — 多处 import analytics, api, mcp, policyLimits
main.tsx → tools/main.tsx:45-46 — SyntheticOutputTool, AgentTool
main.tsx → skills/main.tsx — 直接 import skills/
main.tsx → plugins/main.tsx — 直接 import plugins/
main.tsx → bridge/main.tsx — 直接 import bridge/
main.tsx → server/main.tsx — 直接 import server/
main.tsx → coordinator/main.tsx — 直接 import coordinator/
matsx → remote/main.tsx — 直接 import remote/
bootstrap → screensREPL.tsx:32, Resume.tsx:6, Doctor.tsx:10 — 均 import bootstrap/state
REPL → query.tsscreens/REPL.tsx:146import { query } from '../query.js'
REPL → components/screens/REPL.tsx — 14 处 import(VirtualMessageList, PromptInput 等)
REPL → hooks/screens/REPL.tsx — 21 处 import(useSearchInput, useTerminalSize 等)
REPL → state/screens/REPL.tsx:170import { useAppState } from '../state/AppState.js'
REPL → keybindings/screens/REPL.tsx — KeybindingProviderSetup, useShortcutDisplay
REPL → tasks/screens/REPL.tsx:44-45 — InProcessTeammateTask, LocalAgentTask
REPL -.- remote/screens/REPL.tsx:279import type { RemoteSessionConfig } (type-only)
REPL -.- server/screens/REPL.tsx:62import type { DirectConnectConfig } (type-only)
components → ink/组件使用 ink/ 提供的 Box, Text 等基础组件渲染
query.ts → query/query.ts — import stopHooks, config, deps, transitions, tokenBudget
query.ts → services/query.ts:7-95 — api/withRetry, compact, toolUseSummary, analytics, tools
query.ts → tools/query.ts:91import { SLEEP_TOOL_NAME } from './tools/SleepTool/prompt.js'
query.ts → utils/hooks/query.ts:92-93 — postSamplingHooks, executeStopFailureHooks
query/ → services/query/deps.ts — api/claude, compact/autoCompact, compact/microCompact
query/ → memdir/query/stopHooks.tsimport { isExtractModeActive } from '../memdir/paths.js'
query/ → keybindings/query/stopHooks.tsimport { getShortcutDisplay }
hooks/ → utils/hooks/hooks/useSkillImprovementSurvey.ts, hooks/toolPermission/PermissionContext.ts
hooks/ -.- bridge/hooks/useReplBridge.tsx import bridge/
hooks/ -.- vim/hooks/useVimInput.ts import vim/
hooks/ -.- voice/hooks/useVoiceIntegration.tsx import voice/
ink/ → native-ts/ink/reconciler.ts, ink/ink.tsx — import yoga-layout
services/tools/utils → utils/多处 import utils/ 下的工具函数

REPL 不直接 import 的模块:bridge/、vim/、voice/、memdir/、skills/、coordinator/。这些模块通过 hooks/ 间接访问,或由 main.tsx 在启动时编排。


核心数据流

sequenceDiagram
    participant U as 用户终端
    participant R as REPL.tsx
    participant Q as query.ts
    participant S as services/api
    participant A as Claude API
    participant T as tools/
    participant H as utils/hooks/

    U->>R: 输入文本/命令
    R->>R: 解析命令 (/ 开头?)

    R->>Q: import { query } 直接调用

    loop 查询主循环
        Q->>Q: microcompact 消息压缩
        Q->>Q: autocompact 检查
        Q->>S: callModel() 流式请求
        S->>A: HTTP Stream
        A-->>S: 流式响应 (文本/工具调用)
        S-->>Q: yield 响应块

        alt 文本响应
            Q-->>R: yield 文本块
            R-->>U: 渲染到终端 (ink/)
        else 工具调用
            Q->>H: executePostSamplingHooks()
            Q->>T: runTools() 执行工具
            T-->>Q: 工具结果
            Q->>Q: 追加结果到消息
        end

        Q->>Q: checkTokenBudget()
        Note over Q: 连续2次 delta < 500 且续传≥3 → 停止
    end

    Q->>H: 执行停止钩子 (stopHooks.ts)
    Note over H: 记忆提取 · 自动推理 · 提示建议
    Q-->>R: 查询完成
    R->>R: 会话持久化 (utils/sessionStorage)

工具执行流程

flowchart LR
    A["AI 请求<br/>工具调用"] --> B{"权限检查<br/><small>hooks/useCanUseTool</small>"}
    B -->|自动允许| D["执行工具<br/><small>services/tools/<br/>toolOrchestration</small>"]
    B -->|需确认| C["显示权限对话框<br/><small>components/permissions/</small>"]
    C -->|允许| D
    C -->|拒绝| E["返回拒绝结果"]
    D --> F["收集结果"]
    F --> G["更新文件状态缓存<br/><small>utils/fileStateCache</small>"]
    G --> H["追加到消息"]
    H --> I["继续查询循环"]

    style A fill:#4a9eff,color:#fff
    style B fill:#f7b731,color:#fff
    style D fill:#20bf6b,color:#fff
    style E fill:#ee5a24,color:#fff

模块依赖关系(基于 import 验证)

graph LR
    subgraph 编排
        M[main.tsx]
    end

    subgraph 核心
        B[bootstrap]
        SC[screens/REPL]
        Q[query.ts]
        SV[services]
    end

    subgraph 工具链
        TL[tools]
        SK[skills]
        PL[plugins]
    end

    subgraph 钩子
        RH[hooks]
        EH[utils/hooks]
    end

    subgraph 渲染
        CP[components]
        IK[ink]
        NT[native-ts]
    end

    subgraph 基础
        ST[state]
        UT[utils]
    end

    subgraph 连接
        BR[bridge]
        RM[remote]
        SRV[server]
        CO[coordinator]
    end

    M --> B
    M --> SV
    M --> TL
    M --> SK
    M --> PL
    M --> BR
    M --> SRV
    M --> CO
    M --> RM

    B --> SC
    SC --> Q
    SC --> CP
    SC --> RH
    SC --> ST

    Q --> SV
    Q --> TL
    Q --> EH

    CP --> IK
    IK --> NT

    RH --> EH
    RH -.-> BR
    RH -.-> RM

    SV --> UT
    TL --> UT
    EH --> UT

    style M fill:#e056fd,color:#fff
    style Q fill:#ee5a24,color:#fff
    style SC fill:#a55eea,color:#fff
    style UT fill:#778ca3,color:#fff

启动流程

flowchart TB
    A["bun run cli.tsx"] --> B["解析 CLI 参数"]
    B --> C["main.tsx 初始化"]
    C --> D["bootstrap/state<br/><small>加载 settings.json · CLAUDE.md</small>"]
    D --> E["认证检查<br/><small>OAuth / API Key</small>"]
    E --> F["注册工具 & 加载插件<br/><small>tools/ · skills/ · plugins/</small>"]
    F --> G["初始化连接层<br/><small>bridge/ · server/ · coordinator/</small>"]
    G --> H{"入口模式?"}

    H -->|交互式| I["启动 REPL"]
    H -->|--print / -p| J["单次查询"]
    H -->|SDK| K["返回 Agent 实例"]
    H -->|MCP| L["启动 MCP Server"]

    I --> M["渲染终端 UI<br/><small>components/ → ink/ 引擎</small>"]
    M --> N["等待用户输入"]

    style A fill:#4a9eff,color:#fff
    style C fill:#e056fd,color:#fff
    style H fill:#f7b731,color:#fff
    style I fill:#a55eea,color:#fff
    style M fill:#20bf6b,color:#fff

模块目录树

src/
├── main.tsx                    # 应用主入口 · 编排器 (4683 行)
├── Tool.ts                     # 工具工厂 buildTool() (792 行)
├── Task.ts                     # 任务类型定义 (125 行)
├── query.ts                    # 查询主循环 (1729 行)
├── QueryEngine.ts              # 查询引擎封装 (1295 行)
│
├── entrypoints/                # 入口点(CLI/SDK/MCP)
├── bootstrap/                  # 应用启动 & 全局状态
├── cli/                        # CLI 传输层 & 处理器
├── commands/                   # 86 个斜杠命令子目录 + 15 个根级命令文件
├── screens/                    # 主要 UI 屏幕(REPL/Doctor/Resume)
├── components/                 # 389 个 React UI 组件文件(31 子目录)
├── ink/                        # Ink 终端渲染引擎(深度定制 Fork)
│
├── query/                      # 查询配置/依赖注入/Token预算/停止钩子
├── services/                   # 服务层(20 子目录 + 16 根级文件 · API/分析/压缩)
├── tools/                      # 40 个 AI 工具实现
├── skills/                     # 技能系统(bundled + custom)
├── plugins/                    # 插件系统
├── hooks/                      # 104 React UI Hooks
│
├── state/                      # 应用状态管理
├── context/                    # 上下文收集(git/系统/用户)
├── constants/                  # 常量定义
├── types/                      # 全局类型定义
├── schemas/                    # Zod Schema 定义
│
├── bridge/                     # Web/IDE 桥接通信
├── coordinator/                # 多实例协调器
├── remote/                     # 远程会话管理
├── server/                     # HTTP/WebSocket 服务器
│
├── keybindings/                # 快捷键系统(17 上下文)
├── vim/                        # Vim 模式支持
├── voice/                      # 语音uddy/                      # Buddy 彩蛋(6 文件)
│
├── utils/                      # 工具函数库(564 文件 · 31 子目录)
├── native-ts/                  # 纯 TS 原生实现(yoga/file-index/色差)
├── memdir/                     # 自动记忆系统(8 文件)
├── migrations/                 # 配置迁移(11 迁移文件)
├── tasks/                      # 后台任务管理(5 种任务类型 + 根级辅助文件)
├── outputStyles/               # 输出样式加载
├── upstreamproxy/              # 上游代理
└── assistant/                  # 会话历史管理