Files
aiagent/clode/architecture.md
renjianbo beff3fac8d fix: delete agent 500 error + dynamic personality + deployment guide
- Fix delete agent 500: clean up FK records (agent_llm_logs, permissions,
  schedules, executions, team_members) and unbind goals/tasks before delete
- Remove hardcoded personality templates in Android, replace with dynamic
  system prompt generation from name + description
- Set promptSectionsEnabled=false to bypass PromptComposer for personality
- Add Tencent Cloud Linux deployment guide (Docker Compose)
- Accumulated backend service updates, frontend UI fixes, Android app changes

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-06-29 01:17:21 +08:00

299 lines
13 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Claude Code 系统架构分析
## 1. 分层架构
```
┌─────────────────────────────────────────────────────────────┐
│ CLI Entry Layer (entrypoints/) │
│ cli.tsx → 命令行参数路由、MACRO 注入、启动配置 │
├─────────────────────────────────────────────────────────────┤
│ UI Layer (screens/ + components/ + ink/) │
│ REPL.tsx (900KB) 主导航 | 120+ React/Ink 组件 │
│ 终端渲染引擎ink.tsx (253KB)、screen.ts、output.ts │
├─────────────────────────────────────────────────────────────┤
│ State Layer (state/ + context/ + hooks/) │
│ AppStateStore 全局状态 | React Context (通知/模态/语音) │
│ 80+ React Hooks (useReplBridge 116KB 最大) │
├─────────────────────────────────────────────────────────────┤
│ Business Logic Layer │
│ ┌──────────┬──────────┬──────────┬──────────┬────────────┐ │
│ │ Query │ Tasks │ Bridge │ Memory │ Skills/ │ │
│ │ Engine │ System │ System │ System │ Plugins │ │
│ ├──────────┼──────────┼──────────┼──────────┼────────────┤ │
│ │ Commands │ Tools │ Hook │ Cron │ Voice │ │
│ │ (60+) │ (50+) │ System │ Scheduler│ System │ │
│ └──────────┴──────────┴──────────┴──────────┴────────────┘ │
├─────────────────────────────────────────────────────────────┤
│ Services Layer (services/) │
│ Claude API | MCP | OAuth | LSP | Analytics | Voice STT │
├─────────────────────────────────────────────────────────────┤
│ Infrastructure Layer (utils/) │
│ config | git | file | auth | session | telemetry | ssh │
│ sandbox | ripgrep | diff | editor | image | terminal │
└─────────────────────────────────────────────────────────────┘
```
## 2. 核心入口启动流程
```
终端输入: bun run dev
src/entry.ts
│ 注册 bun:bundle polyfill 插件
src/main.tsx
│ 启动 Ink 渲染器,挂载 <App> 组件
src/components/App.tsx
│ 加载配置、认证检查、预检
│ 根据参数选择渲染屏幕
├── 默认: <REPL> (src/screens/REPL.tsx, 900KB)
├── doctor: <Doctor>
├── resume: <ResumeConversation>
└── teleport: <TeleportResumeWrapper>
```
## 3. 核心模块详解
### 3.1 QueryEngine (`src/QueryEngine.ts`)
QueryEngine 是对话引擎的核心,负责:
- **API 通信**:封装对 Anthropic API 的调用(通过 `@anthropic-ai/sdk`
- **上下文管理**:构建系统提示词、拼接历史消息、控制 Token 预算
- **工具调用循环**:发送用户输入 → 接收响应 → 解析工具调用 → 执行工具 → 回传结果 → 循环
- **会话持久化**`flushSessionStorage()` 保存到磁盘,`recordTranscript()` 记录对话
- **错误处理**:可重试 API 错误分类、退避重试
- **用量统计**Token 计数、成本计算
```
QueryEngine 输入输出:
输入: ProcessUserInputContext (用户消息 + 历史 + 系统提示词)
输出: Stream<SDKMessage> (助手消息 + 工具调用结果)
```
### 3.2 全局状态管理 (`src/state/`)
```
AppState (全局单例状态树):
├── messages: Message[] # 当前会话消息列表
├── tasks: TaskState[] # 活动任务列表
├── session: SessionInfo # 会话元数据
├── settings: Settings # 用户配置
├── toolPermissionContext # 工具权限模式
├── model: string # 当前模型
├── fastMode: boolean # 快速模式状态
├── thinking: ThinkingConfig # 思考开关配置
├── statusLine: StatusLineState # 状态栏信息
├── bridge: BridgeState # 远程桥接状态
├── voice: VoiceState # 语音输入状态
└── ui: UIState # UI 状态 (全屏/弹窗等)
```
状态通过 `createStore()` (基于 React `useSyncExternalStore`) 实现,配合 `AppStateProvider` 在组件树中注入。
### 3.3 REPL 主界面 (`src/screens/REPL.tsx`)
REPL.tsx 是最大的单个文件(约 900KB包含整个交互式对话界面
- **消息列表**: `VirtualMessageList` 虚拟滚动渲染对话
- **输入区域**: `TextInput` / `VimTextInput` 多行输入 + 补全
- **状态栏**: `StatusLine` 显示模型/成本/任务数等信息
- **模态层**: 权限请求、OAuth 流程、设置面板等弹窗
- **键盘导航**: 全局快捷键绑定 (`KeybindingProviderSetup`)
### 3.4 消息系统 (`src/utils/messages.ts`, 198KB)
消息是系统的核心数据结构:
```
Message 类型层级:
├── UserMessage # 用户输入
├── AssistantMessage # 模型回复 (含 thinking/content/tool_use)
│ ├── ThinkingBlock # 扩展思考块
│ ├── TextBlock # 文本回复
│ └── ToolUseBlock # 工具调用
├── ToolResult # 工具执行结果
├── SystemMessage # 系统级别的消息
├── CompactBoundaryMessage # 压缩边界标记
└── StatusMessage # 状态更新 (不持久化)
```
消息处理的辅助模块:
- `messages/mappers.ts` — Anthropic SDK 消息 ↔ 内部 Message 映射
- `messages/systemInit.ts` — 构建系统初始化消息
- `messagePredicates.ts` — 消息类型判断工具函数
- `messageQueueManager.ts` — 消息队列管理
- `groupToolUses.ts` — 工具调用分组
- `collapseReadSearch.ts` — 折叠连续的读/搜索操作
### 3.5 Bridge 系统 (`src/bridge/`)
Bridge 系统实现远程会话功能(约 500KB 代码),支持:
- **远程 REPL**: `replBridge.ts` (102KB) — 将本地 REPL 状态同步到远程
- **会话桥接**: `bridgeMain.ts` (118KB) — WebSocket 双向通信
- **消息传递**: `bridgeMessaging.ts` — 结构化消息序列化
- **会话创建**: `createSession.ts` — 远程会话创建流程
- **权限同步**: `bridgePermissionCallbacks.ts` — 远程权限交互
- **JWT 认证**: `jwtUtils.ts` — 设备信任和会话认证
Bridge 模式状态机:
```
DISCONNECTED → CONNECTING → HANDSHAKE → CONNECTED → SYNCED
└── RECONNECTING → ...
```
### 3.6 Task 系统 (`src/tasks/`)
```
Task 类型:
├── LocalMainSessionTask # 主会话任务 (核心对话)
├── LocalAgentTask # 子 Agent 任务 (AgentTool 创建)
├── RemoteAgentTask # 远程 Agent 任务
├── LocalShellTask # Shell 命令任务 (后台执行)
├── LocalWorkflowTask # 工作流任务
├── InProcessTeammateTask # 队友(协程)任务
├── MonitorMcpTask # MCP 监控任务
└── DreamTask # "梦想"任务(后台思考)
```
任务生命周期:
```
pending → running → completed
→ failed
→ cancelled (用户中断)
```
### 3.7 终端渲染层 (`src/ink/`)
对 Ink 框架的深度定制和增强:
| 模块 | 大小 | 功能 |
|---|---|---|
| `ink.tsx` | 253KB | Ink 主渲染器 (useInput/useStdin/useStdout 等) |
| `screen.ts` | 50KB | 屏幕缓冲区管理 |
| `output.ts` | 26KB | 终端输出渲染 |
| `selection.ts` | 35KB | 文本选择/复制 |
| `render-node-to-output.ts` | 64KB | 虚拟 DOM → ANSI 输出 |
| `Ansi.tsx` | 33KB | ANSI 转义序列处理 |
| `log-update.ts` | 27KB | 日志输出更新管理 |
| `parse-keypress.ts` | 24KB | 按键解析 |
| `reconciler.ts` | 15KB | React Reconciler 适配 |
| `styles.ts` | 21KB | 样式系统 (颜色/边框/布局) |
| `searchHighlight.ts` | 3KB | 搜索高亮 |
### 3.8 内存/记忆系统 (`src/memdir/`)
持久的项目级和用户级记忆:
```
memdir/
├── memdir.ts # 核心:加载/保存 MEMORY.md 文件
├── memoryTypes.ts # 记忆类型定义 (user/feedback/project/reference)
├── findRelevantMemories.ts # 语义检索相关记忆
├── memoryScan.ts # 扫描记忆目录
├── memoryAge.ts # 记忆新鲜度计算
├── paths.ts # 记忆文件路径管理
├── teamMemPaths.ts # 团队共享记忆路径
└── teamMemPrompts.ts # 团队记忆提示词拼装
```
记忆文件格式(位于 `~/.claude/projects/<project>/memory/`
```markdown
---
name: <记忆名>
description: <一行描述>
type: user|feedback|project|reference
---
<记忆内容>
```
## 4. 组件树(简化版)
```
<App>
├── <AppStateProvider> # 全局状态注入
│ ├── <MailboxProvider> # 消息邮箱
│ ├── <VoiceProvider> # 语音 (ANT Only)
│ ├── <KeybindingProviderSetup> # 键盘快捷键
│ ├── <Notifications> # 通知系统
│ ├── <OverlayProvider> # 模态层管理
│ │
│ ├── <REPL> # 主界面 [仅默认模式]
│ │ ├── <FullscreenLayout> # 全屏布局容器
│ │ ├── <StatusLine> # 底部状态栏
│ │ ├── <VirtualMessageList> # 虚拟滚动消息列表
│ │ │ └── <MessageRow> ×N # 单条消息行
│ │ │ └── <Message> # 消息渲染
│ │ │ ├── <Markdown> # Markdown 渲染
│ │ │ ├── <FileEditToolDiff> # Diff 展示
│ │ │ └── <ToolUseLoader> # 工具调用动画
│ │ ├── <TextInput> # 输入框 (支持 Vim 模式)
│ │ ├── <TaskListV2> # 任务列表面板
│ │ └── <Spinner> # 加载动画
│ │
│ ├── <Doctor> # 诊断界面
│ └── <ResumeConversation> # 恢复会话界面
└── 模态层 (通过 OverlayProvider 按需渲染)
├── <PermissionsDialog>
├── <ModelPicker>
├── <Feedback>
├── <Onboarding>
├── <SettingsPanel>
├── <GlobalSearchDialog>
└── <ExportDialog>
```
## 5. 关键设计模式
### 5.1 Feature Flag 死代码消除 (DCE)
`bun:bundle``feature()` 函数在构建时进行死代码消除:
```typescript
import { feature } from 'bun:bundle'
// PROACTIVE=false 时,整个 if 块在构建产物中被移除
if (feature('PROACTIVE')) {
const proactive = require('./commands/proactive.js').default
}
```
使用的 Feature Flags 包括:
`PROACTIVE`, `KAIROS`, `VOICE_MODE`, `DAEMON`, `BRIDGE_MODE`, `AGENT_TRIGGERS`, `MONITOR_TOOL`, `COMPUTER_USE`, `CHICAGO_MCP` 等。
### 5.2 ANT/External 双轨制
大量代码通过 `process.env.USER_TYPE === 'ant'` 区分内部和外部构建:
- 内部版包含更多工具REPLTool, SuggestBackgroundPRTool
- 外部版使用 Stub 替代原生模块
### 5.3 动态 Import
为减少启动时模块加载量,大量使用 `await import()` 延迟加载:
```typescript
// cli.tsx 中的 fast-path 模式
async function main() {
if (args[0] === '--version') {
console.log(`${MACRO.VERSION}`);
return; // 零额外模块加载
}
const { profileCheckpoint } = await import('../utils/startupProfiler.js');
// ...
}
```
### 5.4 虚拟滚动
`VirtualMessageList` (149KB) 实现消息列表的虚拟滚动,支持数十万条消息的高效渲染。
---
*本文档基于 2026-06-11 源码状态生成*