🔍 Claude Code 源码深度分析

基于 GitHub 开源项目 ChinaSiro/claude-code-sourcemap 的完整源码解析。
通过 source map 还原的 TypeScript 源码(v2.1.88),深入理解 Anthropic 官方 CLI 的架构设计、工具系统、多 Agent 协作等核心机制。

5,399
GitHub Stars ⭐
4,756
还原文件数
1,884
TypeScript 源文件
73.8 MB
项目大小
📑 目录导航

📊 项目概览

📦
项目信息
仓库:ChinaSiro/claude-code-sourcemap
创建时间:2026-03-31
还原版本:@anthropic-ai/claude-code v2.1.88
还原方式:提取 cli.js.map 中的 sourcesContent 字段
性质:非官方整理版,仅供研究使用
📂
核心目录结构
restored-src/src/
├── main.tsx # CLI 入口
├── tools/ # 30+ 工具实现
├── commands/ # 40+ 命令实现
├── services/ # API/MCP/分析
├── skills/ # 技能系统
├── coordinator/ # 多 Agent 协调
├── assistant/ # 助手模式 (KAIROS)
├── buddy/ # AI 伴侣 UI
├── voice/ # 语音交互
└── vim/ # Vim 模式
🔧
工具系统
30+ 工具:文件操作/Shell 执行/任务管理/MCP 集成/团队协作
代表工具:FileEditTool, BashTool, MCPTool, TaskCreateTool, AgentTool
🎯
技能系统
内置技能:updateConfig, keybindings, verify, debug, remember, simplify
特性门控:KAIROS/AGENT_TRIGGERS/BUILDING_CLAUDE_APPS
加载机制:注册制 + 按需加载

🔍 核心功能及其实现模式

从代码库理解到完整工作流的四大核心能力

🔍
理解代码库
工具:GrepTool, GlobTool, FileReadTool
实现:Tree-sitter AST 解析 + 语义搜索
优化:可折叠显示(搜索/读取命令)
✏️
编辑文件
工具:FileEditTool, FileWriteTool
实现:diff 匹配 + 多轮对话修正
安全:路径约束检查 + 权限规则
💻
运行终端命令
工具:BashTool, PowerShellTool
实现:6 层安全架构 + AST 解析
特性:后台执行/超时控制/输出持久化
🔄
处理完整工作流
工具:AgentTool, TaskCreateTool
实现:多 Agent 协作 + 任务编排
模式:Research→Implement→Verify

🔍 核心功能 1:理解代码库

📋 代码搜索工具链

工具 用途 实现 优化
GrepTool 内容搜索 ripgrep (rg) 封装 可折叠显示 + 结果截断
GlobTool 文件匹配 fast-glob 封装 通配符 + 排除规则
LSPTool 语言服务器 LSP 协议实现 符号跳转/定义查找
FileReadTool 文件读取 fs.readFile 封装 大文件分块 + 编码检测

🌳 Tree-sitter AST 解析

💡 为什么用 AST 而不是正则?
准确性:AST 能理解代码结构,避免正则表达式误判
语义理解:能区分字符串中的模式和真实代码
跨语言支持:同一套接口支持多种编程语言
安全性:能检测代码注入攻击(如命令替换)
// GrepTool 实现示例
export class GrepTool {
async call(args, context) {
// 1. 验证输入参数
const { pattern, path, include, exclude } = args;
// 2. 构建 ripgrep 命令
const rgArgs = [
'--json', // JSON 输出便于解析
'--max-count', '100', // 限制结果数量
'--context', '2', // 显示上下文
pattern,
path || '.'
];
// 3. 执行搜索
const result = await execRipgrep(rgArgs);
// 4. 格式化输出(可折叠)
return {
data: formatGrepResults(result),
isCollapsible: true // 标记为可折叠
};
}
}

📊 命令分类与可折叠显示

🔍 搜索命令
grep, find, rg, ag, ack, locate, which, whereis
特性:结果可折叠,默认显示摘要
📖 读取命令
cat, head, tail, less, more, wc, stat, file, jq, awk, cut
特性:大输出截断,支持分页
🔇 静默命令
mv, cp, rm, mkdir, chmod, touch, ln, cd, export
特性:成功时无输出,失败时报错

✏️ 核心功能 2:编辑文件

📋 FileEditTool 实现模式

// FileEditTool 输入参数
const inputSchema = z.strictObject({
path: z.string().describe('File path to edit'),
old_text: z.string().describe('Text to replace'),
new_text: z.string().describe('Replacement text'),
multiple_replaces: z.boolean().optional().describe('Allow multiple occurrences'),
})

🔄 多轮对话修正机制

FileEditTool 编辑流程 用户请求编辑文件 ↓ ┌─────────────────────────────────────┐ │ 1. 读取文件内容 │ │ - 检查文件存在性 │ │ - 检查读取权限 │ │ - 检测文件编码 │ └─────────────────────────────────────┘ ↓ ┌─────────────────────────────────────┐ │ 2. 查找匹配内容 │ │ - 精确匹配 old_text │ │ - 多处匹配 → 询问用户 │ │ - 无匹配 → 返回错误 │ └─────────────────────────────────────┘ ↓ ┌─────────────────────────────────────┐ │ 3. 应用修改 │ │ - 替换文本 │ │ - 生成 diff │ │ - 写回文件 │ └─────────────────────────────────────┘ ↓ ┌─────────────────────────────────────┐ │ 4. 验证与反馈 │ │ - 检查写入成功 │ │ - 返回 diff 结果 │ │ - 失败 → 提供修正建议 │ └─────────────────────────────────────┘ 多轮修正: 如果编辑失败(如 old_text 不匹配): 1. 返回错误信息和文件当前内容 2. AI 分析错误原因 3. 重新发起编辑请求 4. 直到成功或用户放弃

🛡️ 安全约束

💻 核心功能 3:运行终端命令

详见上文 BashTool 6 层安全架构解析

⚡ 执行特性
前台执行:等待命令完成,返回输出
后台执行:run_in_background=true,完成后通知
超时控制:默认 300s,最大 3600s
📤 输出管理
格式化:stdout/stderr 分离
截断:超过阈值自动截断
持久化:大输出存储到临时文件
🖼️ 图片检测
Base64 检测:识别图片输出
自动渲染:在 UI 中显示图片
适用场景:matplotlib, PIL 等

🔄 核心功能 4:处理完整工作流

🤖 多 Agent 协作模式

完整工作流:从需求到部署 用户:"帮我实现一个用户登录功能" ↓ ┌─────────────────────────────────────────────────────────┐ │ 阶段 1: Research(研究) │ │ - Agent 1: 分析现有代码结构 │ │ 工具:GlobTool, FileReadTool │ │ 输出:research-notes.md │ │ - Agent 2: 查找认证相关代码 │ │ 工具:GrepTool, LSPTool │ │ 输出:auth-analysis.md │ └─────────────────────────────────────────────────────────┘ ↓ ┌─────────────────────────────────────────────────────────┐ │ 阶段 2: Synthesis(协调器综合) │ │ - 阅读研究报告 │ │ - 制定实现规格 │ │ - 编写具体提示词 │ └─────────────────────────────────────────────────────────┘ ↓ ┌─────────────────────────────────────────────────────────┐ │ 阶段 3: Implementation(实现) │ │ - Agent 3: 实现登录 API │ │ 工具:FileEditTool, BashTool (测试) │ │ 输出:src/auth/login.ts + 测试通过 │ │ - Agent 4: 实现前端表单 │ │ 工具:FileEditTool │ │ 输出:src/components/LoginForm.tsx │ └─────────────────────────────────────────────────────────┘ ↓ ┌─────────────────────────────────────────────────────────┐ │ 阶段 4: Verification(验证) │ │ - Agent 5: 运行测试套件 │ │ 工具:BashTool (npm test) │ │ 输出:测试报告 + 覆盖率 │ │ - Agent 6: 代码审查 │ │ 工具:FileReadTool, SkillTool (/verify) │ │ 输出:代码审查报告 │ └─────────────────────────────────────────────────────────┘ ↓ ┌─────────────────────────────────────────────────────────┐ │ 阶段 5: Deployment(部署) │ │ - Agent 7: 提交代码 │ │ 工具:BashTool (git commit/push) │ │ 输出:commit hash + PR URL │ └─────────────────────────────────────────────────────────┘

📋 任务管理工具

工具 用途 关键参数
TaskCreateTool 创建子任务 description, prompt, subagent_type
TaskListTool 列出所有任务 status (pending/running/completed)
TaskOutputTool 获取任务输出 task_id, follow (实时跟踪)
TaskStopTool 停止任务 task_id, reason
SendMessageTool 继续任务 task_id, message (新指令)
💡 关键设计原则
并行是超能力:Research 阶段多 Agent 并行,Implementation 阶段单 Agent 写文件
Worker 看不到协调器对话:每个提示必须自包含所有上下文
Continue vs Spawn:根据上下文重叠度决策(高重叠→继续,低重叠→新建)
文件系统协作:通过文件传递上下文,避免单 Agent 上下文溢出

🏗️ 核心架构

从入口文件到启动流程的完整解析

📍 入口文件 main.tsx 启动流程

启动流程 ┌─────────────────────────────────────────────────────────┐ │ 1. 模块加载前优化 (Module Pre-loading Optimizations) │ │ - profileCheckpoint('main_tsx_entry') │ │ - startMdmRawRead() // MDM 配置并行读取 │ │ - startKeychainPrefetch() // Keychain 凭据预取 │ ├─────────────────────────────────────────────────────────┤ │ 2. 命令行解析 (CLI Argument Parsing) │ │ - 处理 cc:// 深链 URL │ │ - 处理 claude ssh/host │ │ - 处理 claude assistant │ │ - 处理 --print/-p 非交互模式 │ ├─────────────────────────────────────────────────────────┤ │ 3. 初始化 (Initialization) │ │ - eagerLoadSettings() // 加载设置 │ │ - init() // 核心初始化 │ │ - runMigrations() // 数据迁移 (版本 11) │ ├─────────────────────────────────────────────────────────┤ │ 4. 延迟预取 (Deferred Prefetches) │ │ - startDeferredPrefetches() │ │ - initUser(), getUserContext() │ │ - countFilesRoundedRg() // 文件计数 │ │ - settingsChangeDetector.initialize() │ └─────────────────────────────────────────────────────────┘
⚡ 性能优化亮点
并行预取:MDM 配置、Keychain 凭据、Git 状态并行读取,避免串行等待
懒加载:feature() 条件导入,按需加载功能模块
缓存预热:文件计数、模型能力、MCP 资源预取,提升首响速度
启动分析:profileCheckpoint/Report 全链路性能监控

🛠️ 工具系统深度解析

30+ 工具共享的基类设计与安全控制机制

📐 Tool.ts 核心类型定义

export type Tool<Input, Output, P> = {
// 基础信息
name: string
aliases?: string[]
searchHint?: string // ToolSearch 关键词
// 核心方法
call(
args: z.infer<Input>,
context: ToolUseContext,
canUseTool: CanUseToolFn,
parentMessage: AssistantMessage,
onProgress?: ToolCallProgress<P>
): Promise<ToolResult<Output>>
description(input, options): Promise<string>
// Schema 验证
inputSchema: Input
inputJSONSchema?: ToolInputJSONSchema
outputSchema?: z.ZodType<unknown>
// 安全控制
isConcurrencySafe(input): boolean
isReadOnly(input): boolean
isDestructive?(input): boolean
checkPermissions(input, context): Promise<PermissionResult>
validateInput?(input, context): Promise<ValidationResult>
// UI 渲染
renderToolUseMessage(input, options): React.ReactNode
renderToolResultMessage(content, progressMessages, options): React.ReactNode
renderToolUseProgressMessage?(progressMessages, options): React.ReactNode
// 高级功能
interruptBehavior?(): 'cancel' | 'block'
isSearchOrReadCommand?(input): {isSearch, isRead, isList}
toAutoClassifierInput(input): unknown // 安全分类器
}

🏭 buildTool 工厂函数

const TOOL_DEFAULTS = {
isEnabled: () => true,
isConcurrencySafe: () => false, // 默认不安全 (fail-closed)
isReadOnly: () => false, // 默认写操作
isDestructive: () => false, // 默认非破坏性
checkPermissions: (input) => ({behavior: 'allow', updatedInput: input}),
toAutoClassifierInput: () => '',
userFacingName: () => def.name,
}
export function buildTool<D>(def: D): BuiltTool<D> {
return {...TOOL_DEFAULTS, ...def}
}
🛡️ 安全设计原则
Fail-Closed:默认不安全、默认写操作、默认非破坏性 — 工具必须显式声明安全属性
类型安全:Zod Schema 验证输入输出,运行时类型检查
权限分离:checkPermissions 委托给权限系统,工具只关注业务逻辑
安全分类:toAutoClassifierInput 为自动模式分类器提供输入

🔧 30+ 工具分类

📁
文件操作类
FileReadTool, FileWriteTool, FileEditTool,
GlobTool, GrepTool, LSPTool,
NotebookEditTool
💻
Shell 执行类
BashTool, PowerShellTool,
REPLTool
📋
任务管理类
TaskCreateTool, TaskGetTool,
TaskListTool, TaskOutputTool,
TaskStopTool, TaskUpdateTool
🔌
MCP 集成类
MCPTool, ListMcpResourcesTool,
ReadMcpResourceTool, McpAuthTool
👥
团队协作类
TeamCreateTool, TeamDeleteTool,
AgentTool, SendMessageTool
🌐
其他工具
WebSearchTool, WebFetchTool,
SkillTool, ConfigTool,
TodoWriteTool, SleepTool

💻 BashTool 终端命令执行深度解析

6 层安全架构 + 20+ 危险模式检测 + Tree-sitter AST 解析

📋 BashTool 输入参数

const inputSchema = z.strictObject({
command: z.string().describe('The command to execute'),
timeout: z.number().optional().describe('Optional timeout in milliseconds'),
description: z.string().optional().describe('Clear description of what this command does'),
run_in_background: z.boolean().optional().describe('Run command in background'),
dangerouslyDisableSandbox: z.boolean().optional().describe('Override sandbox mode'),
})

🛡️ 6 层安全架构

BashTool 6 层安全防护 ┌──────────────────────────────────────────────────────────────┐ │ 用户命令请求 │ └─────────────────────────┬────────────────────────────────────┘ │ ▼ ┌──────────────────────────────────────────────────────────────┐ │ 第 1 层:命令分类 │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────────┐ │ │ │ 搜索命令 │ │ 读取命令 │ │ 写入/危险命令 │ │ │ │ grep,find │ │ cat,head │ │ rm,mv,git push │ │ │ └─────────────┘ └─────────────┘ └─────────────────────────┘ │ └─────────────────────────┬────────────────────────────────────┘ │ ▼ ┌──────────────────────────────────────────────────────────────┐ │ 第 2 层:安全检测 │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────────┐ │ │ │ 命令替换 │ │ 参数注入 │ │ Zsh 危险命令 │ │ │ │ $() ` ` │ │ IFS/Unicode │ │ zmodload/emulate │ │ │ └─────────────┘ └─────────────┘ └─────────────────────────┘ │ │ ↓ 危险 → 拒绝 │ └─────────────────────────┬────────────────────────────────────┘ │ ▼ ┌──────────────────────────────────────────────────────────────┐ │ 第 3 层:权限规则 │ │ ┌─────────────────────────────────────────────────────────┐ │ │ │ allow: ["git:*", "npm run:*"] │ │ │ │ deny: ["rm -rf /*", "curl | bash"] │ │ │ │ ask: [其他命令] │ │ └─────────────────────────┬────────────────────────────────────┘ │ ▼ ┌──────────────────────────────────────────────────────────────┐ │ 第 4 层:路径约束 │ │ ┌─────────────────────────────────────────────────────────┐ │ │ │ 检查危险路径:/、~、/* │ │ │ │ 验证输出重定向目标 │ │ │ │ 检查文件权限边界 │ │ └─────────────────────────┬────────────────────────────────────┘ │ ▼ ┌──────────────────────────────────────────────────────────────┐ │ 第 5 层:沙箱执行 │ │ ┌─────────────────────────────────────────────────────────┐ │ │ │ 隔离执行环境 | 限制文件系统访问 | 网络隔离(可选) │ │ └─────────────────────────┬────────────────────────────────────┘ │ ▼ ┌──────────────────────────────────────────────────────────────┐ │ 第 6 层:执行与输出 │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────────┐ │ │ │ 前台执行 │ │ 后台执行 │ │ 超时控制 │ │ │ └─────────────┘ └─────────────┘ └─────────────────────────┘ │ │ ┌─────────────────────────────────────────────────────────┐ │ │ │ 输出格式化 → 截断大输出 → 图片检测 → 持久化存储 │ │ └──────────────────────────────────────────────────────────────┘

🔍 20+ 危险模式检测

检测项 模式 风险
命令替换 $() ` ` 执行子命令
参数替换 ${} 变量注入
进程替换 <() >() 文件描述符攻击
Unicode 空白 \u00A0 \u200B 视觉欺骗攻击
IFS 注入 字段分隔符 命令分割攻击
Zsh 危险命令 zmodload, emulate 模块加载/代码执行
大括号展开 {a,b} {1..10} 参数爆炸攻击
反斜杠转义 \| \& 操作符绕过
💡 关键设计亮点
Tree-sitter AST 解析:精确解析 Bash 语法,避免正则表达式误判
通配符权限规则:"git:*"、"npm run:*"灵活匹配,支持前缀规则
安全环境变量:NODE_ENV/CI/DEBUG 等可跳过,自定义变量需审批
输出持久化:大输出自动存储到文件,避免上下文溢出
后台执行:支持长时间运行命令,不阻塞主线程

🎯 技能系统分析

注册制 + 特性门控的技能架构

📦 内置技能列表

export function initBundledSkills(): void {
registerUpdateConfigSkill() // 配置更新
registerKeybindingsSkill() // 快捷键
registerVerifySkill() // 代码验证
registerDebugSkill() // 调试
registerLoremIpsumSkill() // 占位文本
registerSkillifySkill() // 技能生成
registerRememberSkill() // 记忆
registerSimplifySkill() // 简化
registerBatchSkill() // 批量处理
registerStuckSkill() // 卡住求助
// 特性门控技能
if (feature('KAIROS')) registerDreamSkill()
if (feature('REVIEW_ARTIFACT')) registerHunterSkill()
if (feature('AGENT_TRIGGERS')) registerLoopSkill()
if (feature('BUILDING_CLAUDE_APPS')) registerClaudeApiSkill()
}
💡 设计特点
特性门控:feature() 函数控制功能开关,按需加载
注册制:统一 register 接口,集中管理
可扩展:新增技能只需添加 register 调用
懒加载:特性门控技能使用 require() 动态导入

🤖 协调器模式

多 Agent 协作的核心机制

🎯 核心概念

export function isCoordinatorMode(): boolean {
if (feature('COORDINATOR_MODE')) {
return isEnvTruthy(process.env.CLAUDE_CODE_COORDINATOR_MODE)
}
return false
}
export function getCoordinatorSystemPrompt(): string {
return `You are Claude Code, an AI assistant that orchestrates tasks across multiple workers.
## Your Role
- Direct workers to research, implement and verify
- Synthesize results and communicate with user
- Answer questions directly when possible
## Tools
- AgentTool — Spawn a new worker
- SendMessageTool — Continue an existing worker
- TaskStopTool — Stop a running worker
## Workflow
1. Research — Workers (parallel)
2. Synthesis — You (coordinator)
3. Implementation — Workers
4. Verification — Workers`
}

🔄 多 Agent 协作流程

多 Agent 协作流程 用户请求 ↓ 协调器分析任务 ↓ ┌───────────────────────────────────────┐ │ 并行启动多个 Worker (AgentTool) │ │ - Worker 1: Research │ │ - Worker 2: Research │ │ - Worker 3: Implementation │ └───────────────────────────────────────┘ ↓ Worker 独立执行 ↓ Worker 完成 → <task-notification> 消息 ↓ 协调器综合结果 → 回复用户 ↓ 继续 Worker (SendMessageTool) 或启动新 Worker

📝 Worker 提示设计原则

🎓 关键洞察
Worker 看不到协调器对话:这是最重要的设计原则!每个 Worker 提示必须是自包含的完整上下文。
不要写"根据你的研究":这会把理解责任推给 Worker。协调器必须自己综合研究结果,写出具体实现规格。
Continue vs Spawn 决策:根据上下文重叠度 — 高重叠用 SendMessageTool 继续,低重叠用 AgentTool 新建。

💡 对 OpenClaw 的启发

可借鉴的设计模式与改进方向

📊 现状对比

功能 OpenClaw Claude Code 差距
工具基类 无(独立实现) Tool.ts 统一接口 缺少统一接口
安全控制 工具级策略 isConcurrencySafe/isReadOnly/isDestructive 细粒度控制
UI 渲染 renderToolUseMessage 等 Terminal UI
进度追踪 renderToolUseProgressMessage 实时进度
技能加载 ClawHub 扫描 注册制 + 特性门控 按需加载
多 Agent sessions_spawn 协调器模式 任务自动分解

🔧 建议实现

// OpenClaw Tool 基类(建议)
abstract class BaseTool {
abstract name: string
abstract call(args, context): Promise<ToolResult>
// 安全控制(默认 fail-closed)
isConcurrencySafe(): boolean { return false }
isReadOnly(): boolean { return false }
isDestructive(): boolean { return false }
// UI 渲染(可选)
renderProgress?(progress): React.ReactNode
renderResult?(result): React.ReactNode
}
// OpenClaw 技能注册(建议)
function initBundledSkills(): void {
registerTokenOptimizerSkill() // Token 优化
registerPromptGuardSkill() // 安全防御
registerHealthcheckSkill() // 健康检查
registerWeatherSkill() // 天气查询
// 特性门控
if (feature('TTS')) registerTtsSkill()
if (feature('BROWSER')) registerBrowserSkill()
}

🤖 协调器模式借鉴

📋
任务自动分解
将大任务自动拆分为 Research/Implement/Verify 子任务, 并行启动多个子 Agent 执行
🧠
上下文管理
Worker 间共享上下文(scratchpad), 避免重复读取文件/重复研究
📊
结果综合
自动汇总多个 Worker 结果, 生成统一报告回复用户
📈
进度追踪
实时显示 Worker 状态(研究中/实现中/验证中), 用户可随时了解进展

📚 最佳实践总结

从 Claude Code 源码学到的核心原则

🛡️
安全优先 (Fail-Closed)
默认不安全、默认写操作、默认非破坏性 — 工具必须显式声明安全属性,宁可过度保护也不要冒险
🔒
类型安全 (Zod Schema)
输入输出使用 Zod Schema 验证, 运行时类型检查,避免类型错误
性能优化 (并行预取)
MDM/Keychain/Git 并行读取, 缓存预热提升首响速度
🎯
自包含提示 (Worker)
Worker 看不到协调器对话, 每个提示必须包含所有上下文
🔄
上下文决策 (Continue vs Spawn)
根据上下文重叠度决定继续或新建 — 高重叠→继续,低重叠→新建
🎛️
特性门控 (Feature Flag)
feature() 控制功能开关, 按需加载,避免不必要开销
🎓 核心洞察
1. 安全是设计出来的,不是附加的:Claude Code 的 fail-closed 默认值体现了"安全优先"的设计哲学。
2. 类型是文档也是保障:Zod Schema 既是运行时验证,也是自文档化的接口定义。
3. 性能是用户体验的一部分:并行预取、缓存预热、懒加载 — 每 1ms 都很重要。
4. 上下文是 Agent 协作的核心:Worker 看不到协调器对话,这是多 Agent 系统的关键设计约束。
5. 简单优于复杂:Continue vs Spawn 的决策逻辑简单明了 — 上下文重叠度决定一切。
← 返回 AI Agent 知识库首页