
這份是配合 12 設計哲學 的查閱版——不解釋「為什麼」,只整理「是什麼」。需要確認某個模組或工具的細節時直接跳對應章節。
基於 Claude Code v2.1.88 source code 公開分析整理 · 2026-04-01
基於 Claude Code v2.1.88 source code 公開分析整理 版本:2026-04-01
目錄
- 專案統計
- 技術棧
- 目錄結構
- 入口點
- 核心架構:Agent Loop
- Query Engine
- 工具系統(41 個工具)
- 命令系統(101 個 slash commands)
- Permission 系統
- Sub-Agent 與多 Agent 架構
- Context Compaction
- Memory 系統
- System Prompt 組裝
- Task 系統
- State 管理
- Services 層
- UI 層(React + Ink)
- MCP 整合
- Plugin & Skill 系統
- Hook 系統
- Special Modes
- Feature Flag 系統
- Session 持久化
- Bridge 層
- 關鍵設計模式
1. 專案統計
| 項目 | 數量 |
|---|---|
| TypeScript 檔案(.ts/.tsx) | ~1,884 |
| 程式碼行數 | ~512,664 |
| 最大單一檔案 | query.ts(~785KB) |
| 內建工具 | 41 個 |
| Slash Commands | 101 個 |
| UI 元件 | 130+ |
| Utility 模組 | 300+ |
| npm 依賴 | ~192 個 package |
| Runtime | Bun(編譯為 Node.js >= 18 bundle) |
2. 技術棧
| 層次 | 技術 |
|---|---|
| 語言 | TypeScript (.ts / .tsx) |
| Runtime/打包 | Bun(含 feature() compile-time flag) |
| UI Framework | React + Ink(Terminal React renderer) |
| API Client | @anthropic-ai/sdk |
| MCP | @modelcontextprotocol/sdk |
| CLI | @commander-js/extra-typings |
| Validation | Zod v4 |
| State | Zustand-style store + React Context |
| 終端顏色 | Chalk |
3. 目錄結構
src/
├── main.tsx # REPL 引導程式(4,683 行)
├── QueryEngine.ts # Headless/SDK 查詢生命週期引擎(46KB)
├── query.ts # 主 Agent Loop(785KB,最大檔案)
├── Tool.ts # Tool 介面 + buildTool() 工廠
├── Task.ts # Task 類型、ID、狀態基類
├── commands.ts # Slash commands 定義
├── tools.ts # Tool 註冊、預設、過濾
├── context.ts # 使用者輸入 context
├── cost-tracker.ts # API 成本累積
├── setup.ts # 首次運行設置流程
│
├── bridge/ # Claude Desktop / Remote 橋接
├── cli/ # CLI 基礎設施
├── commands/ # ~80 個 slash command 實作
├── components/ # React/Ink Terminal UI
├── entrypoints/ # 應用入口點
├── hooks/ # React hooks
├── services/ # 業務邏輯層
│ ├── api/ # Claude API client
│ ├── analytics/ # 遙測 + GrowthBook
│ ├── compact/ # Context 壓縮
│ ├── mcp/ # MCP 連接管理
│ ├── tools/ # Tool 執行引擎
│ │ ├── StreamingToolExecutor.ts
│ │ └── toolOrchestration.ts
│ ├── plugins/ # Plugin loader
│ └── settingsSync/ # 跨設備設置同步
├── state/ # 應用狀態
├── tasks/ # Task 實作
│ ├── LocalShellTask/ # Bash 命令執行
│ ├── LocalAgentTask/ # 子 agent 執行
│ ├── RemoteAgentTask/ # 遠端 agent
│ ├── InProcessTeammateTask/ # 進程內 teammate
│ └── DreamTask/ # 後台 memory 整合
├── tools/ # 41 個工具實作
├── types/ # 類型定義
├── utils/ # 工具函數(最大目錄,300+ 檔案)
│ ├── permissions/ # Permission 規則引擎
│ ├── memory/ # Memory 系統工具
│ ├── swarm/ # Multi-agent 集群
│ └── ...
├── assistant/ # KAIROS(autonomous mode)
├── buddy/ # Tamagotchi 陪伴系統
├── coordinator/ # Multi-agent 協調器
├── voice/ # 語音輸入輸出
└── vim/ # Vim 模式整合
4. 入口點
| 檔案 | 用途 |
|---|---|
src/entrypoints/cli.tsx | CLI 主程式(版本、幫助、daemon) |
src/entrypoints/init.ts | Bootstrap 初始化、版本檢查 |
src/entrypoints/mcp.ts | MCP Server 入口 |
src/entrypoints/sdk/ | Agent SDK 類型與 session |
main.tsx 啟動流程:
- Startup profiling
- MDM 預讀、Keychain 預讀(並行)
- Feature flag 初始化(Bun
feature()) - CLI 參數解析(Commander.js)
- 認證(API key / OAuth / AWS Bedrock / GCP Vertex / Azure)
- GrowthBook 初始化(A/B testing)
- Policy limits + remote managed settings
- Tool、command、skill、MCP server 註冊
- REPL 啟動(
replLauncher.tsx)
5. 核心架構:Agent Loop
使用者輸入 (prompt / slash command)
│
▼
processUserInput() ← 解析 /commands,建立 UserMessage
│
▼
fetchSystemPromptParts() ← 組裝 system prompt(靜態 + 動態)
│
▼
recordTranscript() ← 持久化使用者訊息到磁碟(JSONL)
│
▼
┌──→ normalizeMessagesForAPI() ← 剝離 UI 欄位,按需壓縮
│ │
│ ▼
│ Claude API(Streaming)← POST /v1/messages
│ │
│ ▼
│ 流事件處理
│ ├─ 文字區塊 ────────────────→ 傳遞給消費者
│ └─ tool_use 區塊?
│ │
│ ▼
│ StreamingToolExecutor ← 分類:並發安全 vs 串行
│ │
│ ▼
│ canUseTool() ← Permission 決策
│ ├─ 拒絕 ──→ 追加 tool_result(error),繼續
│ └─ 允許
│ │
│ ▼
│ tool.call() ← 執行工具
│ │
│ ▼
│ 追加 tool_result ← 推入 messages[],recordTranscript()
└──────────┘ ← 循環到 API 呼叫
(stop_reason != "tool_use") → 回傳最終結果
6. Query Engine
src/QueryEngine.ts(~46KB)負責:
| 職責 | 說明 |
|---|---|
| 訊息管理 | 維護 conversation history(user/assistant/system/tool) |
| Streaming | 即時 token streaming + tool use 執行 |
| Auto-compaction | Context 接近上限時自動壓縮 |
| Prompt caching | Cache-aware 策略,優化重複 context |
| Retry logic | 處理 API errors、rate limits、overload(exponential backoff) |
| Usage tracking | 計算 token 用量(input/output/cache read/write)和費用 |
| Tool orchestration | 調度 tool calls,收集結果,管理 permissions |
7. 工具系統
Tool 生命週期介面
buildTool(definition) → Tool<Input, Output, Progress>
// 每個 Tool 實作:
validateInput() // 最早拒絕無效輸入
checkPermissions() // Tool 專屬授權檢查
call() // 執行並回傳結果
isEnabled() // Feature flag 檢查
isConcurrencySafe() // 是否可平行執行
isReadOnly() // 是否無副作用
isDestructive() // 是否不可逆
interruptBehavior() // 中斷時行為
renderToolUseMessage() // 輸入顯示
renderToolResultMessage() // 輸出顯示
renderToolUseProgressMessage() // 進度顯示
prompt() // 提供給 LLM 的工具描述完整工具清單(41 個)
檔案操作
| Tool | 用途 |
|---|---|
| FileReadTool | 讀取檔案(支援 PDF、圖片等) |
| FileWriteTool | 完整檔案建立或覆寫 |
| FileEditTool | 精確字串替換編輯 |
| GlobTool | Pattern-based 檔案搜尋 |
| GrepTool | 內容搜尋(ripgrep-based) |
| NotebookEditTool | Jupyter notebook cell 操作 |
程式碼執行
| Tool | 用途 |
|---|---|
| BashTool | Shell 命令執行(含 timeout) |
| PowerShellTool | PowerShell 執行(Windows) |
| REPLTool | Python 執行(僅內部) |
網路與搜尋
| Tool | 用途 |
|---|---|
| WebFetchTool | 抓取並解析網頁內容 |
| WebSearchTool | 網路搜尋 |
| ToolSearchTool | 搜尋可用的 deferred tools |
Agent 與 Task 管理
| Tool | 用途 |
|---|---|
| AgentTool | Spawn 子 agent |
| TaskCreateTool | 建立背景任務 |
| TaskGetTool | 取得任務狀態 |
| TaskUpdateTool | 更新任務狀態 |
| TaskListTool | 列出所有任務 |
| TaskStopTool | 終止任務 |
| TaskOutputTool | 串流讀取任務輸出 |
| SendMessageTool | Agent 間訊息傳遞 |
計畫與 Workflow
| Tool | 用途 |
|---|---|
| EnterPlanModeTool | 進入唯讀計畫模式 |
| ExitPlanModeTool | 帶批准離開計畫模式 |
| EnterWorktreeTool | 建立隔離 git worktree |
| ExitWorktreeTool | 帶修改返回 worktree |
MCP
| Tool | 用途 |
|---|---|
| MCPTool | 呼叫 MCP server 上的工具 |
| McpAuthTool | MCP server 認證 |
| ListMcpResourcesTool | 列出 MCP 資源 |
| ReadMcpResourceTool | 讀取 MCP 資源 |
設定與系統
| Tool | 用途 |
|---|---|
| ConfigTool | 讀寫設定(僅內部) |
| SkillTool | 執行使用者定義 skill |
| AskUserQuestionTool | 向使用者提問 |
| BriefTool | 產生 session 摘要 |
| TodoWriteTool | 管理 todo list |
| SleepTool | 暫停執行 |
Team 與遠端
| Tool | 用途 |
|---|---|
| TeamCreateTool | 建立 agent team |
| TeamDeleteTool | 刪除 agent team |
| RemoteTriggerTool | 觸發遠端任務 |
| ScheduleCronTool | 排程任務 |
| LSPTool | Language Server Protocol 整合 |
8. 命令系統
src/commands/:101 個模組,每個目錄 export 一個 Command object(name、description、handler、aliases)。
Git & Version Control
commit, commit-push-pr, diff, branch, review, autofix-pr, pr_comments, teleport, rewind, tag
Session & History
session, resume, clear, compact, export, share, summary, context
Agent & Task
agents, tasks, brief
Extensions & Plugins
mcp, plugin, reload-plugins, skills
Workspace
plan, sandbox-toggle, init
Memory & Knowledge
memory
Model & Performance
model, effort, fast, thinkback, advisor
Special Operations
bridge, voice, remote-setup, stickers, feedback, ultraplan
9. Permission 系統
決策鏈
Tool 呼叫請求
│
validateInput() ← 拒絕無效參數
│
PreToolUse Hooks ← 使用者定義(可批准/拒絕/修改輸入)
│
Permission Rules:
├─ alwaysAllowRules → 自動允許
├─ alwaysDenyRules → 自動拒絕
└─ alwaysAskRules → 強制詢問
│
(沒有規則命中)→ 互動式提示
│
checkPermissions() ← Tool 專屬邏輯(路徑沙盒等)
│
tool.call()
Permission Modes
| Mode | 說明 |
|---|---|
| default | 互動式提示 |
| auto | ML-based YOLO 分類器自動判斷 |
| bypass | 跳過檢查(需顯式授權) |
| plan | 唯讀模式,需批准才執行 |
Protected Files(不能自動編輯)
.gitconfig, .bashrc, .zshrc, .mcp.json, .claude.json
安全防護
- Path traversal 防護(URL-encoded、Unicode normalization、backslash injection)
- Permission Explainer:另一個 LLM call 向使用者解釋工具風險
10. Sub-Agent 與多 Agent 架構
Spawn Modes
| Mode | 說明 |
|---|---|
| default | In-process,共享對話 |
| fork | 子進程,全新 messages[],共享 file cache |
| worktree | 隔離的 git worktree + fork |
| remote | 透過 bridge 連到遠端 CCR |
通訊機制
SendMessageTool:agent 間訊息傳遞TaskCreate/Update:共享任務看板TeamCreate/Delete:team 生命週期管理
Swarm Mode(Coordinator)
Lead Agent
├── Teammate A → 認領 Task 1
├── Teammate B → 認領 Task 2
└── Teammate C → 認領 Task 3
共享:任務看板、訊息收件匣
隔離:messages[]、file cache、cwd
四階段 Coordinator 協作:
- Research(Workers 並行):調查 codebase
- Synthesis(Coordinator):讀取 findings,制定 spec
- Implementation(Workers):根據 spec 修改
- Verification(Workers):測試修改
Fork Cache 優勢
Parent context 是 byte-for-byte 複製 → API cache 命中 → spawn 5 個並行 agent ≈ 1 個循序 agent 的費用
11. Context Compaction
Context 視窗結構
┌─────────────────────────────────────────────┐
│ System Prompt(工具、permissions、CLAUDE.md) │
│─────────────────────────────────────────────│
│ 對話歷史 │
│ [壓縮摘要] │
│ [compact_boundary 標記] │
│ [最近訊息 — 完整保真度] │
│ user → assistant → tool_use → tool_result │
└─────────────────────────────────────────────┘
三種壓縮策略
| 策略 | 觸發條件 | 說明 |
|---|---|---|
| autoCompact | token 超過閾值 | 用另一個 API call 總結舊訊息 |
| snipCompact | HISTORY_SNIP flag | 移除重複 system message 和過時標記 |
| contextCollapse | CONTEXT_COLLAPSE flag | 重構整個 context |
壓縮流程
messages[]
→ getMessagesAfterCompactBoundary()
→ 舊訊息 → Claude API(總結)→ 壓縮摘要
→ [摘要] + [compact_boundary] + [最近訊息]
12. Memory 系統
三層架構
MEMORY.md(永遠在 context,≤200 行/25KB,只存指針)
↓
Topic files(實際內容,按主題分檔)
↓
Daily logs(原始觀察,autoDream 的輸入來源)
Dream System(autoDream)三門觸發
時間門:距上次 dream > 24 小時
AND
Session 門:至少 5 個 session
AND
Lock 門:取得 consolidation lock
↓
DreamTask(read-only bash,不可修改 project)
Consolidation 四階段
| 階段 | 操作 |
|---|---|
| Orient | ls memory dir,讀 MEMORY.md,掃描 topic files |
| Gather | daily logs → 漂移的 memories → transcript search |
| Consolidate | 寫/更新 topic files,轉換相對日期,刪除矛盾 facts |
| Prune | 維持 MEMORY.md ≤200 行,移除過期指針 |
13. System Prompt 組裝
靜態前綴(可 cache)
getSimpleIntroSection()
getSimpleSystemSection()
getSimpleDoingTasksSection()
getActionsSection()
getUsingYourToolsSection()
getSimpleToneAndStyleSection()
getOutputEfficiencySection()
動態後綴(按 session 注入,破壞 cache)
session_guidance
memory_prompt
env_info
language_preference
output_style
mcp_instructions
scratchpad
function_result_clearing
token_budget
brief_mode
關鍵邊界
SYSTEM_PROMPT_DYNAMIC_BOUNDARY:分隔靜態(cacheable)和動態(non-cacheable)部分。
DANGEROUS_uncachedSystemPromptSection():明確標示會破壞 cache 的 section。
14. Task 系統
Task 類型
| 類型 | 說明 |
|---|---|
local_bash | Local shell 命令 |
local_agent | Local 子 agent(AgentTool spawn) |
remote_agent | 遠端 agent 執行 |
in_process_teammate | 進程內 teammate(共享記憶體) |
dream | 背景 memory 整合 |
local_workflow | Local 多步驟 workflow |
monitor_mcp | MCP server 監控 |
Task 生命週期
pending → running → completed / failed / killed
Task ID 格式
帶前綴的 UUID:b-xxx(bash)、a-xxx(agent)、r-xxx(remote)、t-xxx(teammate)
15. State 管理
src/state/AppStateStore.ts:
AppState {
toolPermissionContext: {
mode: PermissionMode,
additionalWorkingDirectories,
alwaysAllowRules, // 自動批准
alwaysDenyRules, // 自動拒絕
alwaysAskRules, // 永遠詢問
isBypassPermissionsModeAvailable
},
fileHistory: FileHistoryState, // 撤銷快照
attribution: AttributionState, // commit 追蹤
verbose: boolean,
mainLoopModel: string, // 當前模型
fastMode: FastModeState,
kairosEnabled: boolean,
remoteConnectionStatus: Status,
speculationState: Cache
}React 整合
AppStateProvider:透過createContext建立 storeuseAppState(sel):Selector-based 訂閱useSetAppState():Immer-style 更新函數
16. Services 層
API Client(src/services/api/)
| 檔案 | 職責 |
|---|---|
client.ts | 支援多 provider(Anthropic / AWS Bedrock / GCP / Azure) |
claude.ts | Streaming 訊息處理 |
withRetry.ts | Exponential backoff |
errors.ts | 錯誤分類 |
Analytics(src/services/analytics/)
- GrowthBook:Feature flag + A/B testing
- Datadog:監控整合
- 雙層分析管道(1P + Datadog)
Compaction(src/services/compact/)
| 檔案 | 職責 |
|---|---|
compact.ts | 完整 context 壓縮 |
autoCompact.ts | 自動觸發邏輯 |
microCompact.ts | 選擇性訊息修剪 |
sessionMemoryCompact.ts | 壓縮時的 memory 持久化 |
17. UI 層
Framework:React + Ink(Terminal React renderer)
核心元件
| 元件 | 用途 |
|---|---|
App.tsx | Root application component |
REPL.tsx | 主 REPL 畫面 |
Messages.tsx | 對話訊息列表 |
PromptInput/ | 使用者輸入 + 自動補全 |
StatusLine.tsx | 底部狀態欄 |
18. MCP 整合
連接方式
| 傳輸 | 說明 |
|---|---|
| stdio | spawn 子進程 |
| sse | HTTP EventSource |
| http | 串流 HTTP |
| ws | WebSocket |
| sdk | 進程內傳輸 |
工具命名慣例
mcp__<server>__<tool>
認證
- OAuth 2.0(McpOAuthConfig)
- 跨應用存取(XAA / SEP-990)
- Headers 傳遞 API key
19. Plugin & Skill 系統
Plugin
- 位置:
src/plugins/bundled/ - 組成:prompt + metadata + runtime constraints
- 支援 hot-reload(
/reload-plugins)
Skill
- 位置:
src/skills/bundled/ - 本質:可復用的 workflow package,按需注入到 system prompt(via
tool_result,不是 system prompt 前綴) - 觸發:
/skill-name
20. Hook 系統
Hook 類型(25+ lifecycle events)
| 事件 | 說明 |
|---|---|
| PreToolUse | Tool 執行前 |
| PostToolUse | Tool 執行後 |
| UserPromptSubmit | 使用者提交 prompt |
| SessionStart | Session 開始 |
| SessionEnd | Session 結束 |
Hook 實作方式
- Shell commands
- LLM-injected context
- Full agent verification loops
- HTTP webhooks
- JavaScript functions
21. Special Modes
| Mode | 啟動方式 | 說明 |
|---|---|---|
| Bridge Mode | src/bridge/ | 透過 WebSocket 持久連接 claude.ai |
| KAIROS | KAIROS flag | Always-on 自主 agent,有 tick 機制 |
| Coordinator | COORDINATOR_MODE | Multi-agent 協調器 |
| Plan Mode | EnterPlanModeTool | 唯讀規劃模式 |
| Worktree Mode | EnterWorktreeTool | Git worktree 隔離 |
| Voice Mode | VOICE_MODE flag | 語音輸入輸出(push-to-talk) |
| Vim Mode | src/vim/ | Vim 按鍵綁定 |
| Undercover Mode | 自動(非內部 repo) | 隱藏 AI 身份,防止洩漏內部資訊 |
| ULTRAPLAN | /ultraplan | 遠端 CCR 跑 30 分鐘深度規劃 |
22. Feature Flag 系統
使用 Bun feature() 函數,編譯時 constant-fold + 死碼消除。
已知 Flag 清單
| Flag | 功能 |
|---|---|
KAIROS | Always-on 自主 assistant mode |
COORDINATOR_MODE | Multi-agent 協調器 |
BRIDGE_MODE | Remote control via claude.ai |
DAEMON | 背景 daemon worker |
VOICE_MODE | 語音輸入輸出 |
BUDDY | Tamagotchi 陪伴系統 |
HISTORY_SNIP | 激進的歷史修剪 |
CONTEXT_COLLAPSE | Context 重構 |
WORKFLOW_SCRIPTS | Workflow 自動化工具 |
TRANSCRIPT_CLASSIFIER | AFK mode ML 自動批准 |
TERMINAL_PANEL | Terminal 面板擷取 |
CHICAGO_MCP | Computer Use MCP |
EXPERIMENTAL_SKILL_SEARCH | Skill 探索功能 |
AGENT_TRIGGERS | Cron / 遠端觸發器 |
MONITOR_TOOL | MCP 監控工具 |
PROACTIVE | Sleep tool、主動行為 |
NATIVE_CLIENT_ATTESTATION | Client 真實性驗證 |
Runtime Gate
process.env.USER_TYPE === 'ant' → 開啟 Anthropic 內部功能(staging API、Undercover mode、ConfigTool、TungstenTool 等)
23. Session 持久化
存儲位置
~/.claude/projects/<hash>/sessions/
└── <session-id>.jsonl ← append-only log
JSONL 格式
{"type":"user",...}
{"type":"assistant",...}
{"type":"progress",...}
{"type":"system","subtype":"compact_boundary",...}恢復模式
| 模式 | 說明 |
|---|---|
--continue | cwd 中的最後一個 session |
--resume <id> | 指定 session ID |
--fork-session | 新 ID,複製歷史 |
寫入策略
| 類型 | 策略 |
|---|---|
| 使用者訊息 | 阻塞寫入(crash recovery) |
| Assistant 訊息 | Fire-and-forget(有序隊列) |
| Progress | Inline 寫入(下次 query 時去重) |
24. Bridge 層
協議
- JWT 認證
- Work secret 交換
- 退避策略:連接 2s→2min,spawn 500ms→30s
- 令牌刷新排程器
Work Modes
single-session | worktree | same-dir
25. 關鍵設計模式
| 模式 | 位置 | 用途 |
|---|---|---|
| AsyncGenerator Streaming | QueryEngine, query() | API → 消費者全鏈路 streaming |
| Builder + Factory | buildTool() | Tool 定義的安全預設值 |
| Branded Types | SystemPrompt, asSystemPrompt() | 防止 string/array 混淆 |
| Feature Flag + DCE | feature() from bun:bundle | 編譯時死碼消除 |
| Discriminated Unions | Message 類型 | 類型安全的訊息處理 |
| Observer + State Machine | StreamingToolExecutor | Tool 執行生命週期追蹤 |
| Snapshot State | FileHistoryState | 檔案操作 undo/redo |
| Ring Buffer | Error logs | 長 session 的有限記憶體 |
| Fire-and-Forget Write | recordTranscript() | 有序的非阻塞持久化 |
| Lazy Schema | lazySchema() | 延遲 Zod schema 評估,提升效能 |
| Context Isolation | AsyncLocalStorage | 同一進程內每個 agent 的獨立 context |
附錄:Beta Headers(已協商 API 功能)
interleaved-thinking-2025-05-14 // Extended thinking
context-1m-2025-08-07 // 1M token context window
structured-outputs-2025-12-15 // Structured output
web-search-2025-03-05 // Web search
advanced-tool-use-2025-11-20 // Advanced tool use
effort-2025-11-24 // Effort level control
task-budgets-2026-03-13 // Task budget management
prompt-caching-scope-2026-01-05 // Prompt cache scoping
fast-mode-2026-02-01 // Fast mode (Penguin Mode)
redact-thinking-2026-02-12 // Redacted thinking
token-efficient-tools-2026-03-28 // Token-efficient tool schemas
afk-mode-2026-01-31 // AFK mode(未上線)
advisor-tool-2026-03-01 // Advisor tool(未上線)