first commit

This commit is contained in:
H
2026-04-03 13:01:19 +08:00
commit 538eced414
2575 changed files with 645911 additions and 0 deletions

View File

@@ -0,0 +1,441 @@
# Claude Code 架构总览
本文件说明:介绍 Claude Code 的整体架构设计、技术栈、核心设计模式。
## 1. 项目背景
Claude Code 是 Anthropic 官方开发的 CLI命令行界面工具旨在为开发者提供一个在终端环境中与 Claude 交互的途径,完成各种软件工程任务。
### 核心定位
- **终端优先**:专为命令行环境设计,使用 InkReact for CLIs渲染 Terminal UI
- **软件工程助手**专注于代码编写、文件操作、Git 管理、任务执行等开发任务
- **安全可控**:提供细粒度的权限控制,用户可精确控制工具访问范围
### 源码泄露事件
2026 年 3 月 31 日,通过 npm source map 泄露了大量 Claude Code 源码,引起了安全研究社区的关注。这次泄露使外界得以深入了解 Claude Code 的内部实现机制。
## 2. 技术栈详解
### 2.1 运行时环境Bun
Claude Code 使用 [Bun](https://bun.sh/) 作为 JavaScript/TypeScript 运行时:
```typescript
// 使用 bun:bundle feature flag 进行条件编译
import { feature } from 'bun:bundle'
// Dead code elimination 示例
const REPLTool = feature('REPL_MODE')
? require('./tools/REPLTool/REPLTool.js').REPLTool
: null
```
**Bun 的优势**
- 启动速度快
- 内置 bundler 功能支持条件导入Dead code elimination
- 原生支持 TypeScript
- 高效的 I/O 操作
### 2.2 语言TypeScript
全项目使用 TypeScript 开发,具有:
- 完整的类型系统
- 严格的参数校验(基于 Zod v4
- 模块化的接口设计
### 2.3 终端 UIReact + Ink
Claude Code 使用 [Ink](https://github.com/vadimdemedes/ink) 库来实现 React 风格的终端界面:
```typescript
// Ink 组件示例
import { Box, Text } from 'ink'
const MyComponent = () => (
<Box>
<Text>Hello, Terminal!</Text>
</Box>
)
```
**UI 组件特点**
- 支持颜色、布局、边框等终端视觉效果
- 兼容 React 生态系统hooks、context
- 用于渲染消息、进度条、选择器等 UI 元素
### 2.4 CLI 框架Commander.js
使用 Commander.js 处理命令行参数和子命令:
```typescript
import { Command } from '@commander-js/extra-typings'
const program = new Command()
program
.name('claude')
.description('Anthropic 的 CLI 工具')
.version('1.0.0')
```
### 2.5 参数校验Zod v4
使用 Zod v4 进行运行时参数校验:
```typescript
import { z } from 'zod/v4'
const inputSchema = z.object({
file_path: z.string(),
offset: z.number().int().nonnegative().optional(),
limit: z.number().int().positive().optional(),
})
```
### 2.6 代码搜索ripgrep
内置集成了 ripgrep (`rg`) 用于高效的代码搜索:
```typescript
// 在 GrepTool 等工具中使用
import { execFile } from 'child_process'
execFile('rg', ['--json', pattern, directory], callback)
```
## 3. 核心架构设计
### 3.1 整体架构图
```
┌─────────────────────────────────────────────────────────────┐
│ main.tsx │
│ (CLI 入口点) │
└─────────────────────┬───────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ QueryEngine │
│ (查询引擎核心) │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ - submitMessage(): 处理用户输入 │ │
│ │ - query(): 执行 API 调用循环 │ │
│ │ - 流式响应处理 │ │
│ │ - 工具调用编排 │ │
│ └──────────────────────────────────────────────────────┘ │
└─────────────────────┬───────────────────────────────────────────┘
┌─────────────┼─────────────┐
▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Tools │ │ Commands │ │ Context │
│ (工具系统) │ │ (命令系统) │ │ (上下文系统) │
└─────────────┘ └─────────────┘ └─────────────┘
```
### 3.2 工具系统架构
工具系统是 Claude Code 最核心的扩展机制:
```
┌─────────────────────────────────────────────────────────────┐
│ Tool.ts │
│ (工具基类定义) │
│ - inputSchema: Zod 输入校验 │
│ - call(): 工具执行入口 │
│ - checkPermissions(): 权限检查 │
│ - render*: UI 渲染方法 │
└─────────────────────────────────────────────────────────────┘
┌────────────────────┼────────────────────┐
▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ BashTool │ │ FileReadTool │ │ AgentTool │
│ (Shell命令) │ │ (文件读取) │ │ (子Agent) │
└─────────────┘ └─────────────┘ └─────────────┘
│ │ │
└────────────────────┼────────────────────┘
┌───────────────────────────────────┐
│ ToolRegistry (tools.ts) │
│ - getAllBaseTools(): 获取所有工具 │
│ - getTools(): 按权限过滤工具 │
│ - assembleToolPool(): 合并 MCP │
└───────────────────────────────────┘
```
### 3.3 命令系统架构
命令系统支持三种类型的命令:
```typescript
type CommandType =
| 'prompt' // 展开为提示发送给模型
| 'local' // 本地执行,返回文本结果
| 'local-jsx' // 本地执行,渲染 Ink UI
```
**命令注册流程**
1.`commands.ts` 中定义命令
2. 使用条件编译控制命令可见性
3. 通过 `getCommands()` 获取可用命令列表
### 3.4 查询管道架构
```
用户输入 ──► processUserInput() ──► query() ──► API 调用
│ │
│ ▼
│ 工具执行循环
│ │
│ ┌─────────┼─────────┐
│ ▼ ▼ ▼
│ Tool 1 Tool 2 Tool N
│ │ │ │
│ └─────────┼─────────┘
│ ▼
│ 结果处理 ◄──────┐
│ │ │
│ ▼ │
└──────► 结果返回 ───────────┘
```
## 4. 关键设计模式
### 4.1 工厂模式 (Factory Pattern)
使用 `buildTool()` 工厂函数创建工具实例:
```typescript
export function buildTool<D extends AnyToolDef>(def: D): BuiltTool<D> {
return {
...TOOL_DEFAULTS, // 填充默认实现
userFacingName: () => def.name,
...def,
} as BuiltTool<D>
}
```
### 4.2 策略模式 (Strategy Pattern)
权限检查使用策略模式:
```typescript
async checkPermissions(
input: z.infer<Input>,
context: ToolUseContext,
): Promise<PermissionResult> {
// 根据权限模式选择不同的检查策略
switch (context.mode) {
case 'auto': return autoCheck(input, context)
case 'bypass': return allowAll(input)
case 'default': return defaultCheck(input, context)
}
}
```
### 4.3 装饰器模式 (Decorator Pattern)
`backfillObservableInput()` 允许在工具执行前修改输入:
```typescript
backfillObservableInput?(input: Record<string, unknown>): void {
// 在观察者看到输入之前修改它
// 必须幂等
}
```
### 4.4 生成器模式 (Generator Pattern)
查询管道使用 AsyncGenerator 实现流式处理:
```typescript
async *query(params: QueryParams): AsyncGenerator<
| StreamEvent
| RequestStartEvent
| Message
| TombstoneMessage
| ToolUseSummaryMessage,
Terminal
> {
// 流式 yield 消息
}
```
## 5. 状态管理
### 5.1 全局状态 (AppState)
```typescript
interface AppState {
toolPermissionContext: ToolPermissionContext
fastMode: boolean
fileHistory: FileHistoryState
mcp: MCPState
// ...其他状态
}
```
### 5.2 会话状态
- **Session ID**:唯一标识每次会话
- **Message 列表**:维护对话历史
- **Token 使用**:追踪 API 调用成本
- **文件缓存**readFileState 缓存已读文件内容
## 6. 安全机制
### 6.1 权限模式 (Permission Modes)
| 模式 | 描述 |
|------|------|
| `default` | 执行危险操作前询问用户 |
| `auto` | 基于规则自动允许/拒绝 |
| `bypass` | 允许所有操作(仅供可信环境) |
| `plan` | 计划模式,限制更严格 |
### 6.2 工具沙箱
BashTool 支持使用沙箱执行命令:
```typescript
const shouldUseSandbox = await shouldUseSandbox(command)
if (shouldUseSandbox) {
// 使用沙箱执行
} else {
// 直接执行
}
```
## 7. 扩展机制
### 7.1 MCP (Model Context Protocol)
支持通过 MCP 协议扩展工具:
```typescript
interface MCPServerConnection {
name: string
type: 'stdio' | 'http'
command?: string
args?: string[]
env?: Record<string, string>
}
```
### 7.2 插件系统
```typescript
// 插件加载
const plugins = await loadAllPluginsCacheOnly()
// 插件命令注册
export function getPluginCommands(): Promise<Command[]>
```
### 7.3 技能系统 (Skills)
技能是保存在本地目录中的可执行脚本:
```typescript
// 技能目录结构
~/.claude/skills/
skill-name/
skill.md #
script.sh #
```
## 8. 性能优化
### 8.1 记忆化 (Memoization)
使用 lodash 的 `memoize` 缓存昂贵计算:
```typescript
export const getGitStatus = memoize(async (): Promise<string | null> => {
// Git 状态获取(只计算一次)
})
```
### 8.2 条件编译 (Dead Code Elimination)
通过 Bun 的 `feature()` 实现条件编译:
```typescript
const SleepTool = feature('PROACTIVE') || feature('KAIROS')
? require('./tools/SleepTool/SleepTool.js').SleepTool
: null
```
### 8.3 自动压缩 (Auto-compact)
当上下文接近 Token 限制时自动压缩历史:
```typescript
const { compactionResult } = await deps.autocompact(
messagesForQuery,
toolUseContext,
{ systemPrompt, userContext, systemContext, toolUseContext },
querySource,
tracking,
snipTokensFreed,
)
```
## 9. 源码目录结构
```
claude-code/
├── src/
│ ├── main.tsx # CLI 入口
│ ├── QueryEngine.ts # 查询引擎
│ ├── Tool.ts # 工具基类
│ ├── tools.ts # 工具注册表
│ ├── commands.ts # 命令注册
│ ├── context.ts # 上下文收集
│ ├── cost-tracker.ts # 成本追踪
│ ├── query.ts # 查询管道
│ │
│ ├── tools/ # 工具实现
│ │ ├── BashTool/ # Shell 命令执行
│ │ ├── FileReadTool/ # 文件读取
│ │ ├── FileEditTool/ # 文件编辑
│ │ ├── FileWriteTool/ # 文件写入
│ │ ├── GlobTool/ # 文件模式匹配
│ │ ├── GrepTool/ # 代码搜索
│ │ ├── AgentTool/ # 子 Agent
│ │ ├── WebFetchTool/ # 网页获取
│ │ ├── WebSearchTool/ # 网络搜索
│ │ ├── Task*/ # 任务管理系列
│ │ └── ...
│ │
│ ├── services/ # 服务层
│ │ ├── api/ # API 调用
│ │ ├── mcp/ # MCP 协议
│ │ ├── compact/ # 上下文压缩
│ │ └── analytics/ # 分析服务
│ │
│ ├── state/ # 状态管理
│ │ ├── AppState.ts
│ │ └── store.ts
│ │
│ └── utils/ # 工具函数
│ ├── permissions/ # 权限系统
│ ├── model/ # 模型配置
│ └── ...
├── package.json
└── tsconfig.json
```
## 10. 总结
Claude Code 的架构设计体现了以下原则:
1. **模块化**:清晰的分层和模块划分
2. **可扩展性**:工具系统、命令系统、插件系统三位一体
3. **类型安全**TypeScript + Zod 双重保障
4. **性能优先**:记忆化、条件编译、流式处理
5. **安全可控**:细粒度的权限控制系统
这套架构使得 Claude Code 能够有效地在终端环境中执行复杂的软件工程任务,同时保持高度的可配置性和安全性。