Claude Code 完整源码泄露:51万行 TypeScript,1900个文件,所有核心秘密大起底
🔥 泄露震撼
凌晨,我正在改代码,突然看到一条消息:
“Claude Code 源码泄露了!51万行 TypeScript,1900个文件,全部曝光!”
我的第一反应:“这不可能吧?”
但当我真的看到那些代码时,我震惊了——这不是简单的”泄露”,
这是一次开源级别的逆向工程大赏。
3月31日,一个注定载入 AI 编程工具史册的日子。
📊 代码规模到底有多大?
说实话,你可能不信,我们做个简单对比:
|
|
|
|
|---|---|---|
| Claude Code(泄露) | 512,000+ | 1,900+ |
|
|
|
|
|
|
|
|
|
|
|
|
⚡ 关键点: Claude Code 的代码规模相当于 10 个 Vue.js + 5 个 React。这不仅是”大”,这是巨型工程。
你可能会问:这么多代码,到底在干什么?
🏗️ 第一部分:系统架构总览
1.1 技术栈(全是现代的)
Claude Code 用的是纯现代技术栈:
- 前端渲染:React + Ink(终端 UI 框架)
- CLI 框架:Commander.js
- 类型系统:TypeScript(全覆盖)
- 运行时:Bun(超快 JavaScript 运行时)
- AI 模型:Claude Opus 4.6 / Sonnet 4.6 / Haiku 4.5
1.2 目录结构(核心模块)
src/ (~1,900 文件, 512,000+ 行)
├── main.tsx # 入口(CLI + React/Ink 渲染)
├── QueryEngine.ts # LLM 查询引擎(~46K 行!)
├── query.ts # 主查询循环(~1,729 行)
├── commands/# 斜杠命令(100+ 个)
├── tools/# 工具实现(38+ 个)
├── services/# 外部服务集成
│ ├── mcp/# MCP 协议
│ ├── compact/# 上下文压缩
│ └── extractMemories/# 记忆提取
├── coordinator/# 多智能体协调器
├── plugins/# 插件系统
├── skills/# 技能系统
├── vim/# Vim 模式(完整状态机)
└── buddy/# 伴侣精灵(彩蛋)
⚡ 关键点: QueryEngine.ts 有 46,000 行代码。
这不是”文件”,这是一个独立的子系统。Claude Code 的复杂性远超想象。
🔄 第二部分:核心数据流(这是”魔法”的真相)
我看了半天,终于看懂了:Claude Code 的核心是一个精密的工具调用循环。
用户输入(终端/IDE/远程)
↓
main.tsx → Commander.js 解析
↓
REPL.tsx(主交互循环)
↓
QueryEngine.submitMessage() ← 会话生命周期管理
↓
┌────────────────────────────────────────────────┐
│ 消息准备阶段 │
│ ├── applyToolResultBudget()(结果大小限制) │
│ ├── snipCompact()(片段压缩) │
│ ├── microCompact()(微压缩) │
│ ├── contextCollapse()(上下文折叠) │
│ └── autoCompact()(自动压缩) │
│ │
│ API 调用阶段 │
│ ├── withRetry()(重试包装器) │
│ │ ├── 429/529: 指数退避 + fast mode 回退 │
│ │ ├── 401/403: 刷新 OAuth/凭证 │
│ │ └── 连续 529: 模型回退 │
│ ├── queryModelWithStreaming()(流式调用) │
│ └── 错误扣留(PTL/媒体/输出超限) │
│ │
│ 工具执行阶段 │
│ ├── StreamingToolExecutor(并行流式执行) │
│ │ └── 读工具并行,写工具串行 │
│ ├── 权限检查 → 规则/分类器/用户确认 │
│ ├── Pre/Post Tool Hooks │
│ └── tool_result 反馈给 Claude │
│ │
│ 后处理阶段 │
│ ├── Stop Hooks 评估 │
│ ├── Token Budget 检查 │
│ └── needsFollowUp? → 循环继续 │
└────────────────────────────────────────────────┘
↓
结果返回 → UI 渲染 → 用户
↓(后台)
├── extractMemories()(记忆提取智能体)
└── sessionMemory()(会话笔记更新)
⚡ 关键点: 你看到的”智能”是7层精密机制协同工作的结果:
消息压缩 → API 调用 → 并行工具执行 → 权限检查 → Hook 系统 → 结果反馈 → 记忆提取。
说实话,我看这个流程图看了3遍才看懂。
🧠 第三部分:System Prompt 完整揭秘
3.1 系统提示词组装流程
你可能不知道:Claude Code 的系统提示词不是一段文本,而是17个动态段按顺序组装的。
1. 身份与安全指令
2. 系统规则
3. 任务执行指南
4. 安全操作指南
5. 工具使用指南
6. 语气风格
7. 输出效率
═══ 缓存分界线 ═══
8. 会话特定指南
9. 持久记忆
10. Ant 模型覆盖
11. 环境信息
12. 语言偏好
13. 输出样式
14. MCP 服务器指令
15. 临时目录
16. 结果清理
17. 工具结果总结
⚡ 关键点: 前7段是静态内容(可跨用户/组织缓存),后10段是动态内容(每个会话/用户不同)。
这个设计让 Claude Code 在保持灵活性的同时,最大化 Prompt Cache 命中率。
3.2 完整 Prompt 原文:身份定义
You are an interactive agent that helps users with software engineering tasks.
Use the instructions below and the tools available to you to assist the user.
IMPORTANT: Assist with authorized security testing, defensive security, CTF
challenges, and educational contexts. Refuse requests for destructive techniques,
DoS attacks, mass targeting, supply chain compromise, or detection evasion for
malicious purposes.
3.3 完整 Prompt 原文:任务执行指南(核心)
这段 Prompt 看似简单,但藏着核心哲学:
# Doing tasks
- The user will primarily request you toperform software engineering tasks. These
may include solving bugs, adding new functionality, refactoring code, explaining
code, and more.
- You are highly capable and often allow users to complete ambitious tasks that
would otherwise be too complex or take too long.
- In general, donot propose changes to code you haven't read.
- Don't add features, refactor code, or make "improvements" beyond what was asked.
- If an approach fails, diagnose why before switching tactics—read the error, check
your assumptions, try a focused fix. Don't retry the identical action blindly.
⚡ 关键点: 这段 Prompt 的核心哲学是:
“不要过度设计,不要盲目重试,先诊断再行动”。
这是 Claude Code “智能修复”能力的关键。
3.4 Anthropic 内部用户的额外指令
这个细节让我很震惊:内部用户和外部用户的 Prompt 不一样。
- If you notice the user's request is based on a misconception, or spot a bug
adjacent to what they asked about, say so. You're a collaborator, not just an
executor—users benefit from your judgment, not just your compliance.
- Default to writing no comments. Only add one when the WHY is non-obvious.
- Before reporting a task complete, verify it actually works: run the test, execute
the script, check the output.
- Report outcomes faithfully: if tests fail, say so with the relevant output.
Never claim "all tests pass" when output shows failures.
⚡ 关键点: 内部版强调**“验证而非声称”和“指出用户的错误”。
这暴露了 Anthropic 内部的真实态度:更看重真实性**而非”讨好用户”。
🛠️ 第四部分:所有工具(Tool)完整揭秘
Claude Code 内置了38+个工具,以下是核心工具的 Prompt 原文:
4.1 Bash Tool(Shell 命令执行)
Executes a given bash command and returns its output.
IMPORTANT: Avoid using this tool to run `find`, `grep`, `cat`, `head`, `tail`, `sed`,
`awk`, or `echo` commands. Instead, use the appropriate dedicated tool:
- Filesearch: UseGlob (NOT find or ls)
- Content search: Use Grep (NOT grep or rg)
- Read files: UseRead (NOT cat/head/tail)
- Edit files: UseEdit (NOT sed/awk)
- Write files: Use Write (NOT echo >/cat <<EOF)
⚡ 关键点: Claude Code 强制使用专用工具而非 Bash。
这不仅是为了效率,更是为了可审查性——专用工具有更好的日志和权限控制。
4.2 Edit Tool(文件编辑)
Performs exact string replacements infiles.
Usage:
- You must use your `Read` tool at least once before editing.
- When editing textfrom Read tool output, ensure you preserve the exact indentation.
- The edit will FAIL if `old_string` is not unique inthefile.
4.3 Agent Tool(子智能体生成)
Launch anew agent to handle complex, multi-step tasks autonomously.
When NOT to use the Agent tool:
- If you want toreada specific file path, use the Read tool orthe Glob tool
- If you are searching for code withina specific file, use Read
- Other tasks that are not related tothe agent descriptions above
4.4 内置智能体类型
这个设计让我眼前一亮:4个智能体分工协作。
|
|
|
|
|
|---|---|---|---|
| general-purpose |
|
|
|
| Explore |
|
|
|
| Plan |
|
|
|
| verification |
|
|
|
🔁 第五部分:Tool-Call Loop 自修复核心机制(这是”魔法”的真相)
这是 Claude Code 最核心的技术突破:自动修复 bug 的能力。
5.1 核心原理
说实话,这个设计太简单了,但太精妙了:
Claude 生成 tool_use
↓
工具执行(成功或失败)
↓
tool_result 返回给 Claude(含 is_error 标志)
↓
Claude 在下一轮看到错误信息
↓
分析原因 → 尝试新策略
↓
再次调用工具 → 循环继续
关键设计: 错误和成功使用完全相同的消息格式。唯一区别是 is_error: true:
// 成功 tool_result
{
"type":"tool_result",
"tool_use_id":"call_abc",
"content":"文件内容...",
"is_error":false
}
// 失败 tool_result
{
"type":"tool_result",
"tool_use_id":"call_abc",
"content":"Error: File not found",
"is_error":true
}
5.2 四层错误恢复策略
说实话,这个设计太精妙了:
第 1 层:Prompt-Too-Long 恢复
PTL 错误 → 策略1:上下文折叠排空
→ 策略2:反应式压缩(总结历史)
→ 策略3:向用户报告错误
第 2 层:输出 Token 超限恢复
超限错误 → 策略1: 从 8K 升级到 64K
→ 策略2: 恢复消息 "Output token limit hit. Resume directly..."
→ 策略3: 最多 3 次后放弃
第 3 层:模型过载回退
连续 529 错误(3次) → 切换到 fallbackModel
→ 丢弃失败尝试的结果
→ 用备用模型重试
第 4 层:工具错误自然恢复
工具执行出错 → 错误消息作为 tool_result 反馈
→ Claude 分析错误原因
→ 调整策略(读取文件/换方法/修改参数)
→ 再次尝试
⚡ 关键点: Claude Code 的”智能修复”不是单一技术,而是4层防护网:PTL 恢复 → 输出超限恢复 → 模型过载回退 → 工具错误自然恢复。每一层都有明确的策略和回退机制。
🧩 第六部分:多智能体(Multi-Agent)系统
这个设计让我眼前一亮:4个智能体分工协作。
6.1 智能体工作流
Research → Synthesis → Implementation → Verification
典型流程:
- Explore Agent
(只读搜索)→ 收集信息 - Plan Agent
(架构规划)→ 设计方案 - General-purpose Agent
(实现)→ 编写代码 - Verification Agent
(破坏性测试)→ 验证功能
6.2 Verification Agent 的独特设计
这个设计简直是”魔鬼测试”:
You are a verification specialist. Your job isnotto confirm the implementation
works — it's totryto break it.
=== RECOGNIZE YOUR OWN RATIONALIZATIONS ===
- "The code looks correct based on my reading" — reading isnot verification. Run it.
- "The implementer's tests already pass" — the implementer is an LLM. Verify independently.
- "This is probably fine" — probably isnot verified. Run it.
⚡ 关键点: Verification Agent 的核心设计是**“对抗性思维”**——不是”确认代码工作”,而是”试图破坏代码”。这比传统的”测试通过”思维更严格。
🗜️ 第七部分:上下文压缩(Compact)与记忆系统
7.1 自动压缩触发
这个设计让我很惊讶:它会自动压缩上下文。
AUTOCOMPACT_BUFFER_TOKENS = 13,000
WARNING_THRESHOLD_BUFFER_TOKENS = 20,000
MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES = 3(熔断器)
7.2 Compact 压缩提示词(核心)
Your task isto create a detailed summary of the conversation so far, paying close
attention to the user's explicit requests and your previous actions.
Your summary should include:
1. Primary Request and Intent
2. Key Technical Concepts
3. Files and Code Sections(with code snippets and why important)
4. Errors and fixes(how fixed, user feedback)
5. Problem Solving
6. All user messages(non tool-result)
7. Pending Tasks
8. Current Work(precise description of most recent work)
9. OptionalNextStep(with direct quotes from conversation)
7.3 会话记忆系统(10个段)
# Session Title
# Current State
# Task specification
# Files and Functions
# Workflow
# Errors & Corrections
# Codebase and System Documentation
# Learnings
# Key results
# Worklog
⚡ 关键点: Claude Code 的记忆系统分两层:Compact(压缩)保留关键信息,Session Memory(会话记忆)结构化笔记。
🔐 第八部分:权限系统与自动模式分类器
8.1 权限决策管道
这个权限系统是多层防护网:
工具调用请求
↓
Step 1: 规则检查
├── 整个工具被拒绝? → deny
├── 工具特定检查? → deny/ask
├── 安全检查(.git, .claude, shell configs)? → 必须提示
└── always-allowed 规则匹配? → auto-allow
↓
Step 2: 模式转换
├── dontAsk 模式 → deny
├── auto 模式 → 运行分类器
└── plan + autoModeActive → 运行分类器
↓
Step 3: 分类器(如果需要)
├── 安全允许列表? → 跳过分类器,直接允许
└── 两阶段 XML 分类器:
├── Stage 1(fast): max_tokens=64, instant yes/no
└── Stage 2(thinking): max_tokens=4096, chain-of-thought
↓
Step 4: 交互处理(如果 behavior === 'ask')
├── 交互式: 竞速 4 个源(hooks / 分类器 / bridge / 用户UI)
└── Coordinator: 顺序 hooks → 分类器 → 对话框
⚡ 关键点: 权限系统是多层防护网:规则 → 分类器 → 用户确认。关键是两阶段分类器:第一阶段快速判断(64 tokens),第二阶段深度分析(4096 tokens)。这既保证了速度,又保证了准确性。
🎯 第九部分:斜杠命令(Slash Commands)完整列表
说实话,这个命令数量让我震惊:100+个斜杠命令!
核心命令列表
Git 与版本控制
/commit
– 创建 git commit /pr
– 创建 pull request /branch
– 分支管理 /diff
– 查看差异
对话管理
/clear
– 清空对话 /resume
– 恢复上次对话 /compact
– 手动触发压缩
模型与推理
/model
– 切换模型 /fast
– 快速模式 /thinking
– 思考模式
系统与诊断
/doctor
– 诊断系统问题 /status
– 查看状态 /cost
– 查看成本
🔌 第十部分:MCP/LSP/Plugin/Skill 子系统
10.1 MCP 集成
这个设计让我很惊喜:支持多种传输类型。
MCP 服务器作用域:
-local: .mcp.json(项目目录)
-user:~/.claude/.mcp.json
-project: .claude/.mcp.json
-dynamic: 运行时添加
-enterprise: 企业管理配置
10.2 LSP 集成
- LSPServerManager: 按文件扩展名路由到 LSP 服务器实例
- LSPClient: vscode-jsonrpc 协议通信
- 诊断自动附加到对话(无需显式工具调用)
- MAX_DIAGNOSTICS_PER_FILE = 10
10.3 Skill 系统
这个系统让我很兴奋:技能可以动态扩展。
来源:
1. 内置技能(src/skills/bundled/): remember, verify, debug, stuck, simplify...
2. 用户技能: ~/.claude/skills/*.md
3. 项目技能: .claude/skills/*.md
4. MCP 技能: 通过 MCP 服务器提供
🚀 第十一部分:IDE Bridge 与远程会话
11.1 Bridge 系统
这个设计让我眼前一亮:支持 IDE 集成。
传输层:
-V1: 轮询(Polling)
-V2: SSE(Server-Sent Events)
-HybridTransport: V2 → V1 自动回退
控制协议:
-initialize: 初始化能力
-set_model: 动态模型切换
-set_permission_mode: 权限模式切换
-interrupt: 中断(Ctrl+C)
11.2 远程会话
RemoteSessionManager:
- WebSocket 订阅 + HTTP POST 消息
- 权限请求/响应处理
- 重连: 5 次尝试
🎨 第十二部分:其他功能模块
12.1 Vim 模式
甚至连 Vim 模式都完整实现了,支持:
-
INSERT / NORMAL 模式 -
操作符: d(delete), c(change), y(yank) -
动作: hjkl, wbWBE, 0^$ -
文本对象: w/W (word), 引号, 括号
12.2 输出样式系统
来源:
- .claude/output-styles/*.md(项目级,覆盖用户级)
- ~/.claude/output-styles/*.md(用户级)
12.3 自主工作模式(KAIROS/Proactive)
这个模式让我很兴奋:可以自动工作。
# Autonomous work
You arerunning autonomously. You will receive `<tick>` prompts that keep you alive
between turns.
## Bias toward action
- Read files, search code, run tests — allwithout asking.
- Make code changes. Commitwhen you reach a good stopping point.
- If unsure between two approaches, pick oneand go.
🔍 总结:Claude Code 如何做到自动修复问题
看完这51万行代码,我终于明白了:Claude Code 的”智能修复”能力不是单一技术,而是10层机制协同运作的结果。
1. 反馈循环(最核心)
工具执行结果(成功或失败)都作为 tool_result 返回给 Claude,Claude 在下一轮能看到完整的错误信息并调整策略。
2. 精心设计的 System Prompt
**“诊断原因再行动”**而非”盲目重试”的指导原则贯穿整个系统提示词。
3. 四层错误恢复
PTL 恢复 → 输出超限恢复 → 模型过载回退 → 工具错误自然恢复。
4. 防错设计
FileEditTool 的**“必须先读取”、“唯一性检查”、“并发安全”**等机制从源头减少错误。
5. 错误记忆保持
Compact 压缩中显式保留 “Errors and fixes” 段,Session Memory 中有 “Errors & Corrections” 段。
6. 对抗性验证
Verification Agent 专门设计为**“试图破坏实现”**而非”确认它工作”,包含详细的反合理化指令。
7. 多智能体分工
Explore(搜索)→ Plan(规划)→ Implementation(实现)→ Verification(验证) 的分工让每个环节更专注。
8. 权限安全网
分类器 + 沙箱 + Hook 系统形成多层防护,防止危险操作。
9. 上下文管理
自动压缩 + 微压缩 + 上下文折叠确保长会话不会因上下文溢出而失败。
10. Prompt Cache 优化
静态/动态分界线 + Fork 共享缓存 + 工具描述稳定化,让系统在性能和功能之间取得平衡。
⚡ 核心关键点总结
⚡ 关键点 1:
Claude Code 的代码规模相当于 10 个 Vue.js + 5 个 React。
这是巨型工程。
⚡ 关键点 2:
你看到的”智能”是7层精密机制协同工作的结果。
⚡ 关键点 3:
系统提示词分静态段(可缓存)和动态段(每会话不同)。
这个设计最大化 Prompt Cache 命中率。
⚡ 关键点 4:
Claude Code 强制使用专用工具而非 Bash。
这是为了可审查性。
⚡ 关键点 5:
内部版 Prompt 强调**“验证而非声称”和“指出用户的错误”**。
这暴露了 Anthropic 内部的真实态度。
⚡ 关键点 6:
Claude Code 的”智能修复”不是单一技术,而是4层防护网。
⚡ 关键点 7:
Verification Agent 的核心设计是**“对抗性思维”**——不是”确认代码工作”,而是”试图破坏代码”。
⚡ 关键点 8:
权限系统是多层防护网:规则 → 分类器 → 用户确认。
关键是两阶段分类器。
⚡ 关键点 9:
Claude Code 的记忆系统分两层:Compact(压缩)保留关键信息,Session Memory(会话记忆)结构化笔记。
⚡ 关键点 10:
Claude Code 的”智能”是10层机制协同运作的结果。
🎯 对开发者的启示
1. 工具设计哲学
专用工具 > 通用工具。专用工具有更好的日志、权限控制和可审查性。
2. 错误处理哲学
诊断原因 > 盲目重试。每次错误都是学习机会,不要浪费。
3. 系统提示词设计
静态内容 + 动态内容分离,最大化缓存命中率。
4. 多智能体设计
分工明确 > 全能智能体。Explore → Plan → Implement → Verify 的流水线更可靠。
5. 验证思维
对抗性验证 > 确认性测试。试图破坏代码比确认它工作更有效。
💬 互动时间
你觉得 Claude Code 最让你震惊的是哪个部分?
A. 51万行代码的规模 😱
B. 10层修复机制的精密设计 🎯
C. 完整的 Vim 模式 😮
D. 对抗性验证的设计哲学 🔥
(在评论区告诉我你的选择!)
夜雨聆风