docs: rewrite README in English
This commit is contained in:
318
README.md
318
README.md
@@ -1,244 +1,246 @@
|
|||||||
# cczip — Claude Code Source Analysis
|
# Claude Code — Source Analysis
|
||||||
|
|
||||||
> Anthropic의 공식 CLI 도구인 **Claude Code**의 소스코드를 분석하기 위한 레포지토리입니다.
|
> An archive of [Anthropic](https://www.anthropic.com)'s official CLI tool **Claude Code** source code, for analysis and educational purposes.
|
||||||
>
|
>
|
||||||
> 참고: [트윗 원문](https://x.com/Fried_rice/status/2038894956459290963)
|
> Reference: [Original tweet](https://x.com/Fried_rice/status/2038894956459290963)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 개요
|
## Overview
|
||||||
|
|
||||||
Claude Code는 터미널에서 직접 Claude와 대화하며 소프트웨어 엔지니어링 작업을 수행할 수 있는 CLI 도구입니다. 이 레포는 해당 도구의 `src/` 디렉토리를 분석 목적으로 아카이빙한 것입니다.
|
Claude Code is a CLI tool that lets you interact with Claude directly from the terminal to perform software engineering tasks — editing files, running commands, searching codebases, managing git workflows, and more.
|
||||||
|
|
||||||
- **언어**: TypeScript
|
This repository contains the `src/` directory extracted for study.
|
||||||
- **런타임**: Bun
|
|
||||||
- **터미널 UI**: React + [Ink](https://github.com/vadimdemedes/ink) (React for CLI)
|
- **Language**: TypeScript
|
||||||
- **규모**: 약 1,900개 파일, 512,000+ 라인
|
- **Runtime**: Bun
|
||||||
|
- **Terminal UI**: React + [Ink](https://github.com/vadimdemedes/ink) (React for CLI)
|
||||||
|
- **Scale**: ~1,900 files, 512,000+ lines of code
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 디렉토리 구조
|
## Directory Structure
|
||||||
|
|
||||||
```
|
```
|
||||||
src/
|
src/
|
||||||
├── main.tsx # 엔트리포인트 (Commander.js 기반 CLI 파싱)
|
├── main.tsx # Entrypoint (Commander.js-based CLI parser)
|
||||||
├── commands.ts # 커맨드 레지스트리
|
├── commands.ts # Command registry
|
||||||
├── tools.ts # 툴 레지스트리
|
├── tools.ts # Tool registry
|
||||||
├── Tool.ts # 툴 타입 정의
|
├── Tool.ts # Tool type definitions
|
||||||
├── QueryEngine.ts # LLM 쿼리 엔진 (Anthropic API 호출 핵심)
|
├── QueryEngine.ts # LLM query engine (core Anthropic API caller)
|
||||||
├── context.ts # 시스템/유저 컨텍스트 수집
|
├── context.ts # System/user context collection
|
||||||
├── cost-tracker.ts # 토큰 비용 추적
|
├── cost-tracker.ts # Token cost tracking
|
||||||
│
|
│
|
||||||
├── commands/ # 슬래시 커맨드 구현 (~50개)
|
├── commands/ # Slash command implementations (~50)
|
||||||
├── tools/ # 에이전트 툴 구현 (~40개)
|
├── tools/ # Agent tool implementations (~40)
|
||||||
├── components/ # Ink UI 컴포넌트 (~140개)
|
├── components/ # Ink UI components (~140)
|
||||||
├── hooks/ # React 훅
|
├── hooks/ # React hooks
|
||||||
├── services/ # 외부 서비스 연동
|
├── services/ # External service integrations
|
||||||
├── screens/ # 전체 화면 UI (Doctor, REPL, Resume)
|
├── screens/ # Full-screen UIs (Doctor, REPL, Resume)
|
||||||
├── types/ # TypeScript 타입 정의
|
├── types/ # TypeScript type definitions
|
||||||
├── utils/ # 유틸리티 함수
|
├── utils/ # Utility functions
|
||||||
│
|
│
|
||||||
├── bridge/ # IDE 연동 브릿지 (VS Code, JetBrains)
|
├── bridge/ # IDE integration bridge (VS Code, JetBrains)
|
||||||
├── coordinator/ # 멀티 에이전트 코디네이터
|
├── coordinator/ # Multi-agent coordinator
|
||||||
├── plugins/ # 플러그인 시스템
|
├── plugins/ # Plugin system
|
||||||
├── skills/ # 스킬 시스템
|
├── skills/ # Skill system
|
||||||
├── keybindings/ # 키바인딩 설정
|
├── keybindings/ # Keybinding configuration
|
||||||
├── vim/ # Vim 모드
|
├── vim/ # Vim mode
|
||||||
├── voice/ # 음성 입력
|
├── voice/ # Voice input
|
||||||
├── remote/ # 원격 세션
|
├── remote/ # Remote sessions
|
||||||
├── server/ # 서버 모드
|
├── server/ # Server mode
|
||||||
├── memdir/ # 메모리 디렉토리 (영속 기억)
|
├── memdir/ # Memory directory (persistent memory)
|
||||||
├── tasks/ # 태스크 관리
|
├── tasks/ # Task management
|
||||||
├── state/ # 상태 관리
|
├── state/ # State management
|
||||||
├── migrations/ # 설정 마이그레이션
|
├── migrations/ # Config migrations
|
||||||
├── schemas/ # 설정 스키마 (Zod)
|
├── schemas/ # Config schemas (Zod)
|
||||||
├── entrypoints/ # 초기화 로직
|
├── entrypoints/ # Initialization logic
|
||||||
├── ink/ # Ink 렌더러 래퍼
|
├── ink/ # Ink renderer wrapper
|
||||||
├── buddy/ # 컴패니언 스프라이트 (Easter egg)
|
├── buddy/ # Companion sprite (Easter egg)
|
||||||
├── native-ts/ # 네이티브 타입스크립트 유틸
|
├── native-ts/ # Native TypeScript utils
|
||||||
├── outputStyles/ # 출력 스타일링
|
├── outputStyles/ # Output styling
|
||||||
├── query/ # 쿼리 파이프라인
|
├── query/ # Query pipeline
|
||||||
└── upstreamproxy/ # 프록시 설정
|
└── upstreamproxy/ # Proxy configuration
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 핵심 아키텍처
|
## Core Architecture
|
||||||
|
|
||||||
### 1. 툴 시스템 (`src/tools/`)
|
### 1. Tool System (`src/tools/`)
|
||||||
|
|
||||||
Claude Code가 사용하는 모든 도구의 구현체입니다. 각 툴은 독립적인 디렉토리에 정의되어 있습니다.
|
Every tool Claude Code can invoke is implemented as a self-contained module. Each tool defines its input schema, permission model, and execution logic.
|
||||||
|
|
||||||
| 툴 | 설명 |
|
| Tool | Description |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `BashTool` | 셸 명령 실행 |
|
| `BashTool` | Shell command execution |
|
||||||
| `FileReadTool` | 파일 읽기 (이미지, PDF, 노트북 포함) |
|
| `FileReadTool` | File reading (images, PDFs, notebooks) |
|
||||||
| `FileWriteTool` | 파일 생성/덮어쓰기 |
|
| `FileWriteTool` | File creation / overwrite |
|
||||||
| `FileEditTool` | 파일 부분 수정 (string replacement) |
|
| `FileEditTool` | Partial file modification (string replacement) |
|
||||||
| `GlobTool` | 파일 패턴 매칭 검색 |
|
| `GlobTool` | File pattern matching search |
|
||||||
| `GrepTool` | ripgrep 기반 콘텐츠 검색 |
|
| `GrepTool` | ripgrep-based content search |
|
||||||
| `WebFetchTool` | URL 콘텐츠 가져오기 |
|
| `WebFetchTool` | Fetch URL content |
|
||||||
| `WebSearchTool` | 웹 검색 |
|
| `WebSearchTool` | Web search |
|
||||||
| `AgentTool` | 서브에이전트 생성 |
|
| `AgentTool` | Sub-agent spawning |
|
||||||
| `SkillTool` | 스킬 실행 |
|
| `SkillTool` | Skill execution |
|
||||||
| `MCPTool` | MCP 서버 툴 호출 |
|
| `MCPTool` | MCP server tool invocation |
|
||||||
| `LSPTool` | Language Server Protocol 연동 |
|
| `LSPTool` | Language Server Protocol integration |
|
||||||
| `NotebookEditTool` | Jupyter 노트북 편집 |
|
| `NotebookEditTool` | Jupyter notebook editing |
|
||||||
| `TaskCreateTool` / `TaskUpdateTool` | 태스크 생성/관리 |
|
| `TaskCreateTool` / `TaskUpdateTool` | Task creation and management |
|
||||||
| `SendMessageTool` | 에이전트 간 메시지 전송 |
|
| `SendMessageTool` | Inter-agent messaging |
|
||||||
| `TeamCreateTool` / `TeamDeleteTool` | 팀 에이전트 관리 |
|
| `TeamCreateTool` / `TeamDeleteTool` | Team agent management |
|
||||||
| `EnterPlanModeTool` / `ExitPlanModeTool` | 계획 모드 전환 |
|
| `EnterPlanModeTool` / `ExitPlanModeTool` | Plan mode toggle |
|
||||||
| `EnterWorktreeTool` / `ExitWorktreeTool` | Git worktree 격리 |
|
| `EnterWorktreeTool` / `ExitWorktreeTool` | Git worktree isolation |
|
||||||
| `ToolSearchTool` | 지연 로드된 툴 검색 |
|
| `ToolSearchTool` | Deferred tool discovery |
|
||||||
| `CronCreateTool` | 스케줄 트리거 생성 |
|
| `CronCreateTool` | Scheduled trigger creation |
|
||||||
| `RemoteTriggerTool` | 원격 트리거 |
|
| `RemoteTriggerTool` | Remote trigger |
|
||||||
| `SleepTool` | 프로액티브 모드 대기 |
|
| `SleepTool` | Proactive mode wait |
|
||||||
| `SyntheticOutputTool` | 구조화된 출력 생성 |
|
| `SyntheticOutputTool` | Structured output generation |
|
||||||
|
|
||||||
### 2. 커맨드 시스템 (`src/commands/`)
|
### 2. Command System (`src/commands/`)
|
||||||
|
|
||||||
사용자가 `/`로 시작하는 슬래시 커맨드입니다.
|
User-facing slash commands invoked with `/` prefix.
|
||||||
|
|
||||||
| 커맨드 | 설명 |
|
| Command | Description |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `/commit` | Git 커밋 생성 |
|
| `/commit` | Create a git commit |
|
||||||
| `/review` | 코드 리뷰 |
|
| `/review` | Code review |
|
||||||
| `/compact` | 컨텍스트 압축 |
|
| `/compact` | Context compression |
|
||||||
| `/mcp` | MCP 서버 관리 |
|
| `/mcp` | MCP server management |
|
||||||
| `/config` | 설정 관리 |
|
| `/config` | Settings management |
|
||||||
| `/doctor` | 환경 진단 |
|
| `/doctor` | Environment diagnostics |
|
||||||
| `/login` / `/logout` | 인증 |
|
| `/login` / `/logout` | Authentication |
|
||||||
| `/memory` | 영속 기억 관리 |
|
| `/memory` | Persistent memory management |
|
||||||
| `/skills` | 스킬 관리 |
|
| `/skills` | Skill management |
|
||||||
| `/tasks` | 태스크 관리 |
|
| `/tasks` | Task management |
|
||||||
| `/vim` | Vim 모드 토글 |
|
| `/vim` | Vim mode toggle |
|
||||||
| `/diff` | 변경사항 확인 |
|
| `/diff` | View changes |
|
||||||
| `/cost` | 비용 확인 |
|
| `/cost` | Check usage cost |
|
||||||
| `/theme` | 테마 변경 |
|
| `/theme` | Change theme |
|
||||||
| `/context` | 컨텍스트 시각화 |
|
| `/context` | Context visualization |
|
||||||
| `/pr_comments` | PR 코멘트 확인 |
|
| `/pr_comments` | View PR comments |
|
||||||
| `/resume` | 이전 세션 복원 |
|
| `/resume` | Restore previous session |
|
||||||
| `/share` | 세션 공유 |
|
| `/share` | Share session |
|
||||||
| `/desktop` | 데스크톱 앱 연결 |
|
| `/desktop` | Desktop app handoff |
|
||||||
| `/mobile` | 모바일 앱 연결 |
|
| `/mobile` | Mobile app handoff |
|
||||||
|
|
||||||
### 3. 서비스 레이어 (`src/services/`)
|
### 3. Service Layer (`src/services/`)
|
||||||
|
|
||||||
| 서비스 | 설명 |
|
| Service | Description |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `api/` | Anthropic API 클라이언트, 파일 API, 부트스트랩 |
|
| `api/` | Anthropic API client, file API, bootstrap |
|
||||||
| `mcp/` | Model Context Protocol 서버 연결 및 관리 |
|
| `mcp/` | Model Context Protocol server connection and management |
|
||||||
| `oauth/` | OAuth 2.0 인증 플로우 |
|
| `oauth/` | OAuth 2.0 authentication flow |
|
||||||
| `lsp/` | Language Server Protocol 매니저 |
|
| `lsp/` | Language Server Protocol manager |
|
||||||
| `analytics/` | GrowthBook 기반 피처 플래그 및 분석 |
|
| `analytics/` | GrowthBook-based feature flags and analytics |
|
||||||
| `plugins/` | 플러그인 로더 |
|
| `plugins/` | Plugin loader |
|
||||||
| `compact/` | 대화 컨텍스트 압축 |
|
| `compact/` | Conversation context compression |
|
||||||
| `policyLimits/` | 조직 정책 제한 |
|
| `policyLimits/` | Organization policy limits |
|
||||||
| `remoteManagedSettings/` | 원격 관리 설정 |
|
| `remoteManagedSettings/` | Remote managed settings |
|
||||||
| `extractMemories/` | 자동 기억 추출 |
|
| `extractMemories/` | Automatic memory extraction |
|
||||||
| `tokenEstimation.ts` | 토큰 수 추정 |
|
| `tokenEstimation.ts` | Token count estimation |
|
||||||
| `teamMemorySync/` | 팀 메모리 동기화 |
|
| `teamMemorySync/` | Team memory synchronization |
|
||||||
|
|
||||||
### 4. 브릿지 시스템 (`src/bridge/`)
|
### 4. Bridge System (`src/bridge/`)
|
||||||
|
|
||||||
IDE 확장(VS Code, JetBrains)과 Claude Code CLI를 연결하는 양방향 통신 레이어입니다.
|
A bidirectional communication layer connecting IDE extensions (VS Code, JetBrains) with the Claude Code CLI.
|
||||||
|
|
||||||
- `bridgeMain.ts` — 브릿지 메인 루프
|
- `bridgeMain.ts` — Bridge main loop
|
||||||
- `bridgeMessaging.ts` — 메시지 프로토콜
|
- `bridgeMessaging.ts` — Message protocol
|
||||||
- `bridgePermissionCallbacks.ts` — 권한 콜백
|
- `bridgePermissionCallbacks.ts` — Permission callbacks
|
||||||
- `replBridge.ts` — REPL 세션 브릿지
|
- `replBridge.ts` — REPL session bridge
|
||||||
- `jwtUtils.ts` — JWT 기반 인증
|
- `jwtUtils.ts` — JWT-based authentication
|
||||||
- `sessionRunner.ts` — 세션 실행 관리
|
- `sessionRunner.ts` — Session execution management
|
||||||
|
|
||||||
### 5. 권한 시스템 (`src/hooks/toolPermission/`)
|
### 5. Permission System (`src/hooks/toolPermission/`)
|
||||||
|
|
||||||
모든 툴 호출에 대해 권한을 검사하는 시스템입니다. 사용자에게 승인/거부를 요청하거나, 설정된 권한 모드(`default`, `plan`, `bypassPermissions`, `auto` 등)에 따라 자동으로 처리합니다.
|
Checks permissions on every tool invocation. Either prompts the user for approval/denial or automatically resolves based on the configured permission mode (`default`, `plan`, `bypassPermissions`, `auto`, etc.).
|
||||||
|
|
||||||
### 6. 피처 플래그
|
### 6. Feature Flags
|
||||||
|
|
||||||
Bun의 `bun:bundle` feature flag를 활용한 데드코드 제거:
|
Dead code elimination via Bun's `bun:bundle` feature flags:
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import { feature } from 'bun:bundle'
|
import { feature } from 'bun:bundle'
|
||||||
|
|
||||||
// 빌드 시점에 비활성 코드를 완전히 제거
|
// Inactive code is completely stripped at build time
|
||||||
const voiceCommand = feature('VOICE_MODE')
|
const voiceCommand = feature('VOICE_MODE')
|
||||||
? require('./commands/voice/index.js').default
|
? require('./commands/voice/index.js').default
|
||||||
: null
|
: null
|
||||||
```
|
```
|
||||||
|
|
||||||
주요 피처 플래그: `PROACTIVE`, `KAIROS`, `BRIDGE_MODE`, `DAEMON`, `VOICE_MODE`, `AGENT_TRIGGERS`, `MONITOR_TOOL` 등
|
Notable flags: `PROACTIVE`, `KAIROS`, `BRIDGE_MODE`, `DAEMON`, `VOICE_MODE`, `AGENT_TRIGGERS`, `MONITOR_TOOL`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 주요 파일 상세
|
## Key Files in Detail
|
||||||
|
|
||||||
### `QueryEngine.ts` (~46K 라인)
|
### `QueryEngine.ts` (~46K lines)
|
||||||
|
|
||||||
LLM API 호출의 핵심 엔진입니다. 스트리밍 응답 처리, 툴 호출 루프, thinking 모드, 재시도 로직, 토큰 카운팅 등을 담당합니다.
|
The core engine for LLM API calls. Handles streaming responses, tool-call loops, thinking mode, retry logic, and token counting.
|
||||||
|
|
||||||
### `Tool.ts` (~29K 라인)
|
### `Tool.ts` (~29K lines)
|
||||||
|
|
||||||
모든 툴의 기본 타입과 인터페이스를 정의합니다. 툴 입력 스키마, 권한 모델, 진행 상태 타입 등이 포함됩니다.
|
Defines base types and interfaces for all tools — input schemas, permission models, and progress state types.
|
||||||
|
|
||||||
### `commands.ts` (~25K 라인)
|
### `commands.ts` (~25K lines)
|
||||||
|
|
||||||
모든 슬래시 커맨드의 등록과 실행을 관리합니다. 조건부 임포트를 통해 환경별로 다른 커맨드 세트를 로드합니다.
|
Manages registration and execution of all slash commands. Uses conditional imports to load different command sets per environment.
|
||||||
|
|
||||||
### `main.tsx`
|
### `main.tsx`
|
||||||
|
|
||||||
Commander.js 기반의 CLI 파서 + React/Ink 렌더러 초기화. 시작 시 MDM 설정, 키체인 프리페치, GrowthBook 초기화 등을 병렬로 수행합니다.
|
Commander.js-based CLI parser + React/Ink renderer initialization. At startup, parallelizes MDM settings, keychain prefetch, and GrowthBook initialization for faster boot.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 기술 스택
|
## Tech Stack
|
||||||
|
|
||||||
| 카테고리 | 기술 |
|
| Category | Technology |
|
||||||
|---|---|
|
|---|---|
|
||||||
| 런타임 | [Bun](https://bun.sh) |
|
| Runtime | [Bun](https://bun.sh) |
|
||||||
| 언어 | TypeScript (strict) |
|
| Language | TypeScript (strict) |
|
||||||
| 터미널 UI | [React](https://react.dev) + [Ink](https://github.com/vadimdemedes/ink) |
|
| Terminal UI | [React](https://react.dev) + [Ink](https://github.com/vadimdemedes/ink) |
|
||||||
| CLI 파싱 | [Commander.js](https://github.com/tj/commander.js) (extra-typings) |
|
| CLI Parsing | [Commander.js](https://github.com/tj/commander.js) (extra-typings) |
|
||||||
| 스키마 검증 | [Zod v4](https://zod.dev) |
|
| Schema Validation | [Zod v4](https://zod.dev) |
|
||||||
| 검색 | [ripgrep](https://github.com/BurntSushi/ripgrep) (Grep 툴) |
|
| Code Search | [ripgrep](https://github.com/BurntSushi/ripgrep) (via GrepTool) |
|
||||||
| 프로토콜 | [MCP SDK](https://modelcontextprotocol.io), LSP |
|
| Protocols | [MCP SDK](https://modelcontextprotocol.io), LSP |
|
||||||
| API | [Anthropic SDK](https://docs.anthropic.com) |
|
| API | [Anthropic SDK](https://docs.anthropic.com) |
|
||||||
| 텔레메트리 | OpenTelemetry + gRPC |
|
| Telemetry | OpenTelemetry + gRPC |
|
||||||
| 피처 플래그 | GrowthBook |
|
| Feature Flags | GrowthBook |
|
||||||
| 인증 | OAuth 2.0, JWT, macOS Keychain |
|
| Auth | OAuth 2.0, JWT, macOS Keychain |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 주목할만한 설계 패턴
|
## Notable Design Patterns
|
||||||
|
|
||||||
### 병렬 프리페치
|
### Parallel Prefetch
|
||||||
|
|
||||||
시작 시간을 최적화하기 위해 MDM 설정, 키체인, API preconnect 등을 병렬로 프리페치합니다.
|
Startup time is optimized by prefetching MDM settings, keychain reads, and API preconnect in parallel — before heavy module evaluation begins.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
// main.tsx — 모듈 임포트 전에 side-effect로 실행
|
// main.tsx — fired as side-effects before other imports
|
||||||
startMdmRawRead()
|
startMdmRawRead()
|
||||||
startKeychainPrefetch()
|
startKeychainPrefetch()
|
||||||
```
|
```
|
||||||
|
|
||||||
### 지연 로딩 (Lazy Loading)
|
### Lazy Loading
|
||||||
|
|
||||||
무거운 모듈(OpenTelemetry ~400KB, gRPC ~700KB)은 실제로 필요할 때까지 `import()`로 지연 로딩합니다.
|
Heavy modules (OpenTelemetry ~400KB, gRPC ~700KB) are deferred via dynamic `import()` until actually needed.
|
||||||
|
|
||||||
### 에이전트 스웜
|
### Agent Swarms
|
||||||
|
|
||||||
`AgentTool`을 통해 서브에이전트를 생성하고, `coordinator/`가 멀티에이전트 오케스트레이션을 담당합니다. `TeamCreateTool`로 팀 단위 병렬 작업도 지원합니다.
|
Sub-agents are spawned via `AgentTool`, with `coordinator/` handling multi-agent orchestration. `TeamCreateTool` enables team-level parallel work.
|
||||||
|
|
||||||
### 스킬 시스템
|
### Skill System
|
||||||
|
|
||||||
`skills/` 디렉토리에 재사용 가능한 워크플로우를 정의하고, `SkillTool`로 실행합니다. 사용자가 커스텀 스킬을 추가할 수 있습니다.
|
Reusable workflows defined in `skills/` and executed through `SkillTool`. Users can add custom skills.
|
||||||
|
|
||||||
### 플러그인 아키텍처
|
### Plugin Architecture
|
||||||
|
|
||||||
`plugins/` 를 통해 빌트인 플러그인과 서드파티 플러그인을 로드합니다.
|
Built-in and third-party plugins are loaded through the `plugins/` subsystem.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 라이선스
|
## License
|
||||||
|
|
||||||
이 레포지토리는 분석 및 학습 목적으로만 사용됩니다. 원본 소스코드의 저작권은 [Anthropic](https://www.anthropic.com)에 있습니다.
|
This repository is for analysis and educational purposes only. All original source code is copyrighted by [Anthropic](https://www.anthropic.com).
|
||||||
|
|||||||
Reference in New Issue
Block a user