สถาปัตยกรรมระบบ
การวิเคราะห์เชิงลึกเกี่ยวกับโครงสร้างภายในของ Claude Code
ตัวชี้วัดหลัก
| ตัวชี้วัด | ค่า |
|---|---|
| บรรทัดโค้ด | ~512,000+ |
| ไฟล์ทั้งหมด | ~1,900 |
| Agent tools | ~40 |
| Slash commands | ~85 |
| React components | ~140 |
| React hooks | ~80 |
| Utility modules | ~331 |
โครงสร้างไดเรกทอรี
src/
├── Core Engine
│ ├── QueryEngine.ts (~46K lines) - วงจรชีวิตของการ query หลัก
│ └── Tool.ts (~29K lines) - การ abstract ระบบ tool
│
├── Tools (src/tools/)
│ ├── BashTool/
│ ├── FileReadTool/
│ ├── FileWriteTool/
│ ├── FileEditTool/
│ ├── AgentTool/
│ ├── MCPTool/
│ └── [40+ tool directories]
│
├── Commands (src/commands/)
│ ├── commitCommand.ts
│ ├── mcpCommand.ts
│ ├── memoryCommand.ts
│ └── [85+ command files]
│
├── Services (src/services/)
│ ├── api/ - Anthropic SDK, file uploads, bootstrap
│ ├── mcp/ - Model Context Protocol client
│ ├── oauth/ - Authentication flows
│ ├── lsp/ - Language Server Protocol manager
│ ├── analytics/ - GrowthBook feature flags
│ └── [10+ service modules]
│
├── UI Layer
│ ├── components/ (~140 React components)
│ ├── hooks/ (~80 React hooks)
│ └── state/ (AppState, selectors)
│
├── Utilities (src/utils/)
│ └── [331 utility modules]
│
└── Entry Points
├── main.tsx (~1,800 lines)
├── ink.tsx - Terminal UI rendering
└── bootstrap/ - Initialization logic
ภาพรวมระดับสูง
Claude Code คือ AI coding assistant แบบ terminal-native ที่สร้างเป็น single-binary CLI สถาปัตยกรรมเป็นแบบ pipeline model:
User Input → CLI Parser → Query Engine → LLM API → Tool Execution Loop → Terminal UI
UI layer ทั้งหมดสร้างด้วย React + Ink (React สำหรับ terminal) ทำให้เป็น reactive CLI application ที่มี components, hooks, state management และ pattern แบบ React web app ทั้งหมด — แต่ render ไปยัง terminal
Pipeline หลัก
1. Entrypoint (src/main.tsx)
CLI parser สร้างด้วย Commander.js เมื่อเริ่มต้นระบบจะ:
- เริ่ม parallel prefetch side-effects (MDM settings, Keychain, API preconnect) ก่อน import module หนัก
- Parse CLI arguments และ flags
- เริ่มต้น React/Ink renderer
- ส่งต่อไปยัง REPL launcher (
src/replLauncher.tsx)
2. Initialization (src/entrypoints/)
| ไฟล์ | บทบาท |
|---|---|
cli.tsx | CLI session orchestration — เส้นทางหลักจาก launch สู่ REPL |
init.ts | Config, telemetry, OAuth, MDM policy initialization |
mcp.ts | MCP server mode entrypoint (Claude Code ในฐานะ MCP server) |
sdk/ | Agent SDK — programmatic API สำหรับ embed Claude Code |
3. Query Engine (src/QueryEngine.ts, ~46K lines)
หัวใจของ Claude Code จัดการ:
- Streaming responses จาก Anthropic API
- Tool-call loops — เมื่อ LLM ร้องขอ tool ให้ execute แล้วส่งผลกลับ
- Thinking mode — extended thinking พร้อม budget management
- Retry logic — retry อัตโนมัติพร้อม backoff สำหรับความล้มเหลวชั่วคราว
- Token counting — ติดตาม input/output tokens และค่าใช้จ่ายต่อ turn
- Context management — จัดการ conversation history และ context windows
4. Tool System (src/Tool.ts + src/tools/)
ทุก capability ที่ Claude สามารถเรียกใช้คือ tool แต่ละ tool มีความสมบูรณ์ในตัวเองด้วย:
- Input schema (Zod validation)
- Permission model (สิ่งที่ต้องการการอนุมัติจาก user)
- Execution logic (การ implement จริง)
- UI components (วิธีแสดงผลการเรียกใช้/ผลลัพธ์ใน terminal)
Tools ลงทะเบียนใน src/tools.ts และถูกค้นพบโดย Query Engine ระหว่าง tool-call loops
ดู Tools Reference สำหรับ catalog ทั้งหมด
5. Command System (src/commands.ts + src/commands/)
User-facing slash commands (/commit, /review, /mcp ฯลฯ) ที่พิมพ์ใน REPL ได้ มีสามประเภท:
| ประเภท | คำอธิบาย | ตัวอย่าง |
|---|---|---|
| PromptCommand | ส่ง prompt ที่จัดรูปแบบไปยัง LLM พร้อม tools ที่ inject | /review, /commit |
| LocalCommand | ทำงานใน-process คืนค่า plain text | /cost, /version |
| LocalJSXCommand | ทำงานใน-process คืนค่า React JSX | /doctor, /install |
ดู Commands Reference สำหรับ catalog ทั้งหมด
State Management
Claude Code ใช้ pattern React context + custom store:
| Component | Location | วัตถุประสงค์ |
|---|---|---|
AppState | src/state/AppStateStore.ts | Global mutable state object |
| Context Providers | src/context/ | React context สำหรับ notifications, stats, FPS |
| Selectors | src/state/ | Derived state functions |
| Change Observers | src/state/onChangeAppState.ts | Side-effects เมื่อ state เปลี่ยนแปลง |
UI Layer
Components (src/components/, ~140 components)
- Functional React components ใช้ Ink primitives (
Box,Text,useInput()) - ตกแต่งด้วย Chalk สำหรับสี terminal
- React Compiler เปิดใช้งานสำหรับ optimized re-renders
- Design system primitives ใน
src/components/design-system/
Screens (src/screens/)
UI modes แบบเต็มจอ:
| Screen | วัตถุประสงค์ |
|---|---|
REPL.tsx | Main interactive REPL (หน้าจอเริ่มต้น) |
Doctor.tsx | Environment diagnostics (/doctor) |
ResumeConversation.tsx | Session restore (/resume) |
Hooks (src/hooks/, ~80 hooks)
Pattern React hooks มาตรฐาน หมวดหมู่ที่น่าสนใจ:
- Permission hooks —
useCanUseTool,src/hooks/toolPermission/ - IDE integration —
useIDEIntegration,useIdeConnectionStatus,useDiffInIDE - Input handling —
useTextInput,useVimInput,usePasteHandler,useInputBuffer - Session management —
useSessionBackgrounding,useRemoteSession,useAssistantHistory - Plugin/skill hooks —
useManagePlugins,useSkillsChange
Configuration & Schemas
Config Schemas (src/schemas/)
Zod v4-based schemas สำหรับทุก configuration:
- User settings
- Project-level settings
- Organization/enterprise policies
- Permission rules
Migrations (src/migrations/)
จัดการการเปลี่ยนแปลง config format ระหว่าง versions — อ่าน config เก่าและแปลงเป็น schema ปัจจุบัน
Build System
Bun Runtime
Claude Code ทำงานบน Bun (ไม่ใช่ Node.js) ผลที่ตามมาหลัก:
- Native JSX/TSX support โดยไม่ต้องผ่าน transpilation
bun:bundlefeature flags สำหรับ dead-code elimination- ES modules พร้อม
.jsextensions (Bun convention)
Feature Flags (Dead Code Elimination)
import { feature } from 'bun:bundle'
// โค้ดภายใน feature flag ที่ไม่ active จะถูกตัดออกทั้งหมดตอน build
if (feature('VOICE_MODE')) {
const voiceCommand = require('./commands/voice/index.js').default
}
Feature flags ที่น่าสนใจ:
| Flag | Feature |
|---|---|
PROACTIVE | Proactive agent mode (autonomous actions) |
KAIROS | Kairos subsystem |
BRIDGE_MODE | IDE bridge integration |
DAEMON | Background daemon mode |
VOICE_MODE | Voice input/output |
AGENT_TRIGGERS | Triggered agent actions |
COORDINATOR_MODE | Multi-agent coordinator |
WORKFLOW_SCRIPTS | Workflow automation scripts |
Lazy Loading
Module หนักๆ ถูก defer ผ่าน dynamic import() จนกว่าจะใช้งานครั้งแรก:
- OpenTelemetry (~400KB)
- gRPC (~700KB)
- Optional dependencies อื่นๆ
Key Files Reference
| ไฟล์ | บรรทัด | วัตถุประสงค์ |
|---|---|---|
src/QueryEngine.ts | ~46K | Core query lifecycle, message management |
src/Tool.ts | ~29K | Tool system abstraction and permissions |
src/commands.ts | ~25K | Slash command system |
src/main.tsx | ~1.8K | Entry point, startup optimization |
src/tools.ts | ~3K | Tool registry and loading |
Error Handling & Telemetry
Telemetry (src/services/analytics/)
- GrowthBook สำหรับ feature flags และ A/B testing
- OpenTelemetry สำหรับ distributed tracing และ metrics
- Custom event tracking สำหรับ usage analytics
Cost Tracking (src/cost-tracker.ts)
ติดตาม token usage และค่าใช้จ่ายโดยประมาณต่อ conversation turn เข้าถึงได้ผ่าน /cost command
Diagnostics (/doctor command)
หน้าจอ Doctor.tsx ทำการตรวจสอบ environment: API connectivity, authentication, tool availability, MCP server status และอื่นๆ
Concurrency Model
Claude Code ใช้ single-threaded event loop (Bun/Node.js model) พร้อม:
- Async/await สำหรับ I/O operations
- React’s concurrent rendering สำหรับ UI updates
- Web Workers หรือ child processes สำหรับงานที่ใช้ CPU เข้มข้น (gRPC ฯลฯ)
- Tool concurrency safety — แต่ละ tool ประกาศ
isConcurrencySafe()เพื่อระบุว่าสามารถทำงานพร้อมกันกับ tool อื่นได้หรือไม่
ดูเพิ่มเติม
- Tools Reference — Catalog ทั้งหมดของ agent tools ~40 รายการ
- Commands Reference — Catalog ทั้งหมดของ slash commands
- Subsystems Guide — Bridge, MCP, permissions, skills, plugins และอื่นๆ
- Exploration Guide — วิธีสำรวจ codebase นี้