Claude Code: ภาพรวมสถาปัตยกรรมระบบ

🇹🇭 Thai claude-codearchitectureanalysisthai
📋 Table of Contents (13 sections)
  1. สถาปัตยกรรมระบบ
  2. ตัวชี้วัดหลัก
  3. โครงสร้างไดเรกทอรี
  4. ภาพรวมระดับสูง
  5. Pipeline หลัก
  6. State Management
  7. UI Layer
  8. Configuration & Schemas
  9. Build System
  10. Key Files Reference
  11. Error Handling & Telemetry
  12. Concurrency Model
  13. ดูเพิ่มเติม

สถาปัตยกรรมระบบ

การวิเคราะห์เชิงลึกเกี่ยวกับโครงสร้างภายในของ 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.tsxCLI session orchestration — เส้นทางหลักจาก launch สู่ REPL
init.tsConfig, telemetry, OAuth, MDM policy initialization
mcp.tsMCP 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:

ComponentLocationวัตถุประสงค์
AppStatesrc/state/AppStateStore.tsGlobal mutable state object
Context Providerssrc/context/React context สำหรับ notifications, stats, FPS
Selectorssrc/state/Derived state functions
Change Observerssrc/state/onChangeAppState.tsSide-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.tsxMain interactive REPL (หน้าจอเริ่มต้น)
Doctor.tsxEnvironment diagnostics (/doctor)
ResumeConversation.tsxSession restore (/resume)

Hooks (src/hooks/, ~80 hooks)

Pattern React hooks มาตรฐาน หมวดหมู่ที่น่าสนใจ:

  • Permission hooksuseCanUseTool, src/hooks/toolPermission/
  • IDE integrationuseIDEIntegration, useIdeConnectionStatus, useDiffInIDE
  • Input handlinguseTextInput, useVimInput, usePasteHandler, useInputBuffer
  • Session managementuseSessionBackgrounding, useRemoteSession, useAssistantHistory
  • Plugin/skill hooksuseManagePlugins, 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:bundle feature flags สำหรับ dead-code elimination
  • ES modules พร้อม .js extensions (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 ที่น่าสนใจ:

FlagFeature
PROACTIVEProactive agent mode (autonomous actions)
KAIROSKairos subsystem
BRIDGE_MODEIDE bridge integration
DAEMONBackground daemon mode
VOICE_MODEVoice input/output
AGENT_TRIGGERSTriggered agent actions
COORDINATOR_MODEMulti-agent coordinator
WORKFLOW_SCRIPTSWorkflow automation scripts

Lazy Loading

Module หนักๆ ถูก defer ผ่าน dynamic import() จนกว่าจะใช้งานครั้งแรก:

  • OpenTelemetry (~400KB)
  • gRPC (~700KB)
  • Optional dependencies อื่นๆ

Key Files Reference

ไฟล์บรรทัดวัตถุประสงค์
src/QueryEngine.ts~46KCore query lifecycle, message management
src/Tool.ts~29KTool system abstraction and permissions
src/commands.ts~25KSlash command system
src/main.tsx~1.8KEntry point, startup optimization
src/tools.ts~3KTool 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 อื่นได้หรือไม่

ดูเพิ่มเติม

← Back to claudecodeanalysis