Claude Code 源码技术文档

1. 概述
1.1 简介
Claude Code 是 Anthropic 公司开发的 AI 编程助手命令行工具(CLI),代号 “Tengu”。它基于 Anthropic Claude 大语言模型,提供智能代码生成、代码审查、终端命令执行、文件操作、MCP(Model Context Protocol)服务集成等能力。项目支持交互式 REPL 模式、SDK 无头模式、远程控制模式(Bridge)以及 MCP Server 模式等多种运行方式。
1.2 基本特性
多入口架构
CLI 交互模式、SDK 无头模式、MCP Server 模式、远程控制(Bridge)模式
丰富的工具集
30+ 内置工具,涵盖文件读写、Bash/PowerShell 执行、代码搜索、Web 搜索、Agent 调度等
多 Agent 协作
支持子 Agent(Subagent)、进程内队友(In-process Teammate)、Agent Swarm 等多 Agent 架构
自定义扩展
支持 Skills(技能)、Hooks(钩子)、Plugins(插件)、MCP Server 等扩展机制
权限系统
细粒度的工具权限控制,支持规则匹配、自动模式、旁路模式等
会话管理
会话持久化、历史记录、会话恢复、会话压缩(Compact)
成本追踪
实时 API 调用成本统计、Token 用量监控
远程控制
通过 Bridge 模式将本地机器暴露为远程开发环境
1.3 技术栈
|
|
|
|
|---|---|---|
| 运行时 |
|
bun:bundle 的 feature() 进行构建时死代码消除 |
| 语言 |
|
|
| UI 框架 |
|
|
| AI SDK |
|
|
| MCP SDK |
|
|
| 遥测 |
|
|
| 功能开关 |
|
|
| 序列化 |
|
|
| 样式 |
|
|
| 工具库 |
|
|
2. 架构设计
2.1 整体架构
┌─────────────────────────────────────────────────────────────┐ │ 入口层 (Entrypoints) │ │ cli.tsx │ init.ts │ mcp.ts │ ├─────────────────────────────────────────────────────────────┤ │ 核心引擎层 │ │ QueryEngine │ Tool │ Task │ commands │ context │ ├─────────────────────────────────────────────────────────────┤ │ 工具层 (Tools) │ │ 30+ 内置工具 │ AgentTool │ BashTool │ FileEditTool │ ... │ ├─────────────────────────────────────────────────────────────┤ │ 服务层 (Services) │ │ API │ Analytics │ MCP │ Compact │ LSP │ OAuth │ Plugins │ ├─────────────────────────────────────────────────────────────┤ │ UI 渲染层 (Ink + React) │ │ Components │ Hooks │ Context │ Ink Terminal Engine │ ├─────────────────────────────────────────────────────────────┤ │ 基础设施层 (Utils) │ │ Config │ Auth │ Permissions │ Shell │ Git │ FS │ Network │ └─────────────────────────────────────────────────────────────┘
2.2 目录结构
src/
├── entrypoints/ # 程序入口
│ ├── cli.tsx # CLI 主入口(交互式 REPL)
│ ├── init.ts # 初始化入口
│ └── mcp.ts # MCP Server 入口
├── bootstrap/ # 启动引导
│ └── state.ts # 全局状态管理(会话、遥测、配置)
├── QueryEngine.ts # 查询引擎(核心对话循环)
├── Tool.ts # 工具接口定义
├── Task.ts # 任务系统定义
├── commands.ts # 命令注册与加载
├── context.ts # 上下文构建(系统提示、用户上下文)
├── commands/ # 斜杠命令(60+)
├── tools/ # 工具实现(30+)
├── components/ # React UI 组件
├── hooks/ # React Hooks(50+)
├── bridge/ # 远程控制模块
├── services/ # 服务层
├── ink/ # 自研终端渲染引擎
├── cli/ # CLI 辅助
├── buddy/ # Companion 宠物系统
├── constants/ # 常量定义
├── utils/ # 工具函数(200+)
└── vendor/ # 第三方原生模块
3. 核心组件
3.1 QueryEngine(查询引擎)
QueryEngine.ts 是项目的核心查询引擎,负责管理整个对话生命周期。
主要功能:
- 会话状态管理
维护消息列表、文件缓存、用量统计等 - 消息处理流程
用户输入 → 系统提示构建 → API 调用 → 工具执行 → 结果处理 - 多轮对话支持
通过 submitMessage()方法支持多轮对话,状态跨轮次持久化 - SDK 流式输出
通过 AsyncGenerator<SDKMessage>实现流式消息输出 - 权限追踪
包装 canUseTool函数追踪权限拒绝记录 - 系统提示构建
集成 CLAUDE.md、用户上下文、Git 状态等信息
3.2 Tool 系统
Tool.ts 定义了统一的工具接口,每个工具包含以下方法:
interfaceTool { call(params: any): Promise<any>; prompt(): string; checkPermissions(params: any): Promise<boolean>; validateInput(params: any): boolean; isConcurrencySafe(): boolean; isReadOnly(): boolean; isDestructive(): boolean; interruptBehavior(): 'cancel' | 'block'; shouldDefer?: boolean; alwaysLoad?: boolean; }
3.3 Bridge(远程控制)
bridge/ 模块实现远程控制功能:
会话轮询
通过 runBridgeLoop() 持续轮询服务器获取工作任务
多会话管理
支持同时运行多个工作会话
心跳机制
定期发送心跳保持会话活跃
JWT 令牌管理
自动刷新会话令牌,处理过期重连
Git Worktree 集成
每个会话可使用独立的 Git Worktree
容量管理
支持配置最大并发会话数
3.4 Ink 终端引擎
ink/ 是自研的终端 UI 渲染引擎(基于 React Ink 思想):
- 布局引擎
基于 Yoga 的 Flexbox 布局(layout/engine.ts) - 终端 I/O
ANSI 转义序列解析器(termio/) - 事件系统
点击事件、输入事件、焦点事件分发 - 渲染器
虚拟 DOM 差异化渲染到终端屏幕 - 选择功能
文本选择和复制支持
4. API 参考
4.1 QueryEngine API
ASYNC submitMessage(prompt: string)
提交用户消息并执行查询,返回流式消息生成器
参数
|
|
|
|
|---|---|---|
prompt |
string |
|
返回值
async *submitMessage(prompt: string): AsyncGenerator<SDKMessage, void, unknown> { // 流式产生 SDK 消息}
示例
constengine = newQueryEngine(config);forawait (constmessageofengine.submitMessage("帮我创建一个 React 组件")) { if (message.type === 'content') { console.log(message.content); } }
METHOD canUseTool(toolName: string)
检查是否可以使用指定的工具
参数
|
|
|
|
|---|---|---|
toolName |
string |
|
返回值
interfacePermissionResult { allowed: boolean; reason?: string; }
示例
constresult = awaitengine.canUseTool('BashTool');if (result.allowed) { console.log('可以使用 BashTool'); } else { console.log('无法使用: ' + result.reason); }
4.2 Tool API
ASYNC Tool.call(params: any)
执行工具并返回结果
参数
|
|
|
|
|---|---|---|
params |
any |
|
返回值
interfaceToolResult { success: boolean; data?: any; error?: string; }
示例
constfileReadTool = newFileReadTool();constresult = awaitfileReadTool.call({ file_path: '/path/to/file.txt'});if (result.success) { console.log(result.data); }
4.3 Bridge API
ASYNC runBridgeLoop()
启动 Bridge 主循环,持续轮询服务器获取工作任务
返回值
interfaceBridgeSession { sessionId: string; status: 'active' | 'idle' | 'error'; lastHeartbeat: Date; }
示例
constbridge = newBridgeClient(config);awaitbridge.runBridgeLoop();
5. 工具系统
5.1 内置工具列表
|
|
|
|
|---|---|---|
| BashTool |
|
|
| PowerShellTool |
|
|
| FileReadTool |
|
|
| FileWriteTool |
|
|
| FileEditTool |
|
|
| GlobTool |
|
|
| GrepTool |
|
|
| WebSearchTool |
|
|
| WebFetchTool |
|
|
| AgentTool |
|
|
| TodoWriteTool |
|
|
| TaskCreateTool |
|
|
| MCPTool |
|
|
| SkillTool |
|
|
| NotebookEditTool |
|
|
| LSPTool |
|
|
| EnterPlanModeTool |
|
|
| SendMessageTool |
|
|
| TeamCreateTool |
|
|
| ScheduleCronTool |
|
|
5.2 工具使用示例
文件读取
constresult = awaitRead({ file_path: 'e:\\任钢管理\\任钢工作\\claudecode\\src\\QueryEngine.ts', limit: 100, offset: 1});
文件写入
constresult = awaitWrite({ file_path: 'e:\\任钢管理\\任钢工作\\claudecode\\test.txt', content: 'Hello, World!'});
文件编辑
constresult = awaitSearchReplace({ file_path: 'e:\\任钢管理\\任钢工作\\claudecode\\test.txt', old_str: 'Hello, World!', new_str: 'Hello, Claude Code!'});
命令执行
constresult = awaitRunCommand({ command: 'npm install', blocking: true, requires_approval: false});
6. 命令系统
6.1 斜杠命令分类
commands/ 目录包含所有斜杠命令,主要分为:
配置类
/config、/model、/theme、/color、/effort、/fast
会话类
/compact、/clear、/resume、/session、/exit
代码操作类
/review、/commit、/diff、/branch、/init
扩展类
/mcp、/plugin、/skills、/hooks
信息类
/cost、/usage、/stats、/status、/doctor
权限类
/permissions、/plan
远程类
/bridge、/desktop、/mobile、/ide
特色功能
/voice(语音)、/vim(Vim 模式)、/tasks(任务管理)
6.2 常用命令示例
CMD /review
代码审查命令,用于审查代码质量
示例
/review src/QueryEngine.ts
CMD /commit
Git 提交命令,自动生成提交信息
示例
/commit "添加新的功能"
CMD /diff
查看代码差异
示例
/diff src/QueryEngine.ts
CMD /cost
查看 API 调用成本统计
示例
/cost
7. 工作流程
7.1 CLI 启动与查询流程
用户执行 claude 命令
快速路径检查
--version
→ 输出版本号,退出 --dump-system-prompt
→ 输出系统提示,退出 --claude-in-chrome-mcp
→ Chrome MCP 模式 remote-control/bridge
→ Bridge 模式 daemon
→ Daemon 模式 ps/logs/attach/kill
→ 后台会话管理
加载 main.js
init()
初始化 -
启用配置系统 -
设置优雅关闭 -
初始化遥测 -
配置网络代理/mTLS -
API 预连接 -
初始化 LSP 管理器 -
渲染 REPL UI(Ink + React) -
AppStateProvider -
StatsProvider -
FpsMetricsProvider -
REPL 组件树 -
等待用户输入
用户提交消息
processUserInput()
处理输入 -
斜杠命令解析 -
附件处理 -
上下文构建 query()
执行查询
7.2 消息处理流程
接收用户输入
构建系统提示
-
加载 CLAUDE.md -
添加用户上下文 -
集成 Git 状态 -
添加工具描述
调用 Claude API
解析工具调用请求
执行工具
-
权限检查 -
输入验证 -
工具执行 -
结果返回
返回结果给用户
更新会话状态
7.3 Bridge 远程控制流程
启动 Bridge 客户端
认证并获取 JWT 令牌
进入主循环
-
轮询服务器获取工作任务 -
创建独立会话 -
执行工作任务 -
返回执行结果 -
发送心跳保持连接
处理令牌刷新和重连
清理会话资源
8. 代码示例
8.1 创建自定义工具
import { Tool } from './Tool';class CustomTool implements Tool {readonly name = 'CustomTool';async call(params: any): Promise<any> {// 工具执行逻辑return { success: true, data: 'Hello from CustomTool!' };}prompt(): string {return 'CustomTool: 自定义工具示例';}async checkPermissions(params: any): Promise<boolean> {return true;}validateInput(params: any): boolean {return true;}isConcurrencySafe(): boolean {return true;}isReadOnly(): boolean {return true;}isDestructive(): boolean {return false;}interruptBehavior(): 'cancel' | 'block' {return 'block';}}export default CustomTool;
8.2 创建自定义命令
import { Command } from '../Command';const customCommand: Command = {name: 'custom',description: '自定义命令示例',usage: '/custom [options]',options: [{name: 'verbose',alias: 'v',description: '详细输出',type: 'boolean'}],async execute(args: any, context: CommandContext) {if (args.verbose) {console.log('详细模式已启用');}console.log('自定义命令执行成功!');}};export default customCommand;
8.3 使用 QueryEngine
import { QueryEngine } from './QueryEngine';import { Config } from './config';const config = new Config({apiKey: 'your-api-key',model: 'claude-3-opus-20240229'});const engine = new QueryEngine(config);// 提交消息并处理流式响应(async () => {for await (const message of engine.submitMessage("帮我创建一个 React 组件")) {switch (message.type) {case 'content':console.log(message.content);break;case 'tool_call':console.log('调用工具:', message.tool);break;case 'tool_result':console.log('工具结果:', message.result);break;}}})();
8.4 使用 Bridge 客户端
import { BridgeClient } from './bridge/bridgeApi';import { BridgeConfig } from './bridge/bridgeConfig';const config: BridgeConfig = {serverUrl: 'https://bridge.example.com',apiKey: 'your-api-key',maxSessions: 5};const bridge = new BridgeClient(config);// 启动 Bridge 主循环await bridge.runBridgeLoop();
8.5 Feature Flag 使用
import { feature } from 'bun:bundle';// 条件编译:仅在启用 PROACTIVE 功能时加载const proactive = feature('PROACTIVE') || feature('KAIROS')? await import('./commands/proactive.js'): null;if (proactive) {// 使用 proactive 功能proactive.execute();}
8.6 Signal 模式使用
import { createSignal } from './utils/signal';// 创建信号const sessionSwitched = createSignal<[id: string]>();// 订阅信号sessionSwitched.on((sessionId) => {console.log('会话已切换:', sessionId);});// 发射信号sessionSwitched.emit('session-123');
8.7 Memoize 缓存使用
import { memoize } from 'lodash-es';// 缓存昂贵的计算const getSystemContext = memoize(async () => {// 耗时的上下文构建逻辑return await buildSystemContext();});// 第一次调用会执行计算const context1 = await getSystemContext();// 后续调用会返回缓存结果const context2 = await getSystemContext();
文档说明
本文档基于 Claude Code 项目的源代码和技术实现文档编写,涵盖了项目的核心架构、API 参考、工具系统、命令系统和工作流程。如需了解更多详细信息,请参考源代码和相关文档。

夜雨聆风