(Alleged) Leaked source of Claude Code
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

docs: rewrite README in English

+160 -158
+160 -158
README.md
··· 1 - # cczip — Claude Code Source Analysis 1 + # Claude Code — Source Analysis 2 2 3 - > Anthropic의 공식 CLI 도구인 **Claude Code**의 소스코드를 분석하기 위한 레포지토리입니다. 3 + > An archive of [Anthropic](https://www.anthropic.com)'s official CLI tool **Claude Code** source code, for analysis and educational purposes. 4 4 > 5 - > 참고: [트윗 원문](https://x.com/Fried_rice/status/2038894956459290963) 5 + > Reference: [Original tweet](https://x.com/Fried_rice/status/2038894956459290963) 6 6 7 7 --- 8 8 9 - ## 개요 9 + ## Overview 10 10 11 - Claude Code는 터미널에서 직접 Claude와 대화하며 소프트웨어 엔지니어링 작업을 수행할 수 있는 CLI 도구입니다. 이 레포는 해당 도구의 `src/` 디렉토리를 분석 목적으로 아카이빙한 것입니다. 11 + 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. 12 12 13 - - **언어**: TypeScript 14 - - **런타임**: Bun 15 - - **터미널 UI**: React + [Ink](https://github.com/vadimdemedes/ink) (React for CLI) 16 - - **규모**: 약 1,900개 파일, 512,000+ 라인 13 + This repository contains the `src/` directory extracted for study. 14 + 15 + - **Language**: TypeScript 16 + - **Runtime**: Bun 17 + - **Terminal UI**: React + [Ink](https://github.com/vadimdemedes/ink) (React for CLI) 18 + - **Scale**: ~1,900 files, 512,000+ lines of code 17 19 18 20 --- 19 21 20 - ## 디렉토리 구조 22 + ## Directory Structure 21 23 22 24 ``` 23 25 src/ 24 - ├── main.tsx # 엔트리포인트 (Commander.js 기반 CLI 파싱) 25 - ├── commands.ts # 커맨드 레지스트리 26 - ├── tools.ts # 툴 레지스트리 27 - ├── Tool.ts # 툴 타입 정의 28 - ├── QueryEngine.ts # LLM 쿼리 엔진 (Anthropic API 호출 핵심) 29 - ├── context.ts # 시스템/유저 컨텍스트 수집 30 - ├── cost-tracker.ts # 토큰 비용 추적 26 + ├── main.tsx # Entrypoint (Commander.js-based CLI parser) 27 + ├── commands.ts # Command registry 28 + ├── tools.ts # Tool registry 29 + ├── Tool.ts # Tool type definitions 30 + ├── QueryEngine.ts # LLM query engine (core Anthropic API caller) 31 + ├── context.ts # System/user context collection 32 + ├── cost-tracker.ts # Token cost tracking 31 33 32 - ├── commands/ # 슬래시 커맨드 구현 (~50개) 33 - ├── tools/ # 에이전트 툴 구현 (~40개) 34 - ├── components/ # Ink UI 컴포넌트 (~140개) 35 - ├── hooks/ # React 훅 36 - ├── services/ # 외부 서비스 연동 37 - ├── screens/ # 전체 화면 UI (Doctor, REPL, Resume) 38 - ├── types/ # TypeScript 타입 정의 39 - ├── utils/ # 유틸리티 함수 34 + ├── commands/ # Slash command implementations (~50) 35 + ├── tools/ # Agent tool implementations (~40) 36 + ├── components/ # Ink UI components (~140) 37 + ├── hooks/ # React hooks 38 + ├── services/ # External service integrations 39 + ├── screens/ # Full-screen UIs (Doctor, REPL, Resume) 40 + ├── types/ # TypeScript type definitions 41 + ├── utils/ # Utility functions 40 42 41 - ├── bridge/ # IDE 연동 브릿지 (VS Code, JetBrains) 42 - ├── coordinator/ # 멀티 에이전트 코디네이터 43 - ├── plugins/ # 플러그인 시스템 44 - ├── skills/ # 스킬 시스템 45 - ├── keybindings/ # 키바인딩 설정 46 - ├── vim/ # Vim 모드 47 - ├── voice/ # 음성 입력 48 - ├── remote/ # 원격 세션 49 - ├── server/ # 서버 모드 50 - ├── memdir/ # 메모리 디렉토리 (영속 기억) 51 - ├── tasks/ # 태스크 관리 52 - ├── state/ # 상태 관리 53 - ├── migrations/ # 설정 마이그레이션 54 - ├── schemas/ # 설정 스키마 (Zod) 55 - ├── entrypoints/ # 초기화 로직 56 - ├── ink/ # Ink 렌더러 래퍼 57 - ├── buddy/ # 컴패니언 스프라이트 (Easter egg) 58 - ├── native-ts/ # 네이티브 타입스크립트 유틸 59 - ├── outputStyles/ # 출력 스타일링 60 - ├── query/ # 쿼리 파이프라인 61 - └── upstreamproxy/ # 프록시 설정 43 + ├── bridge/ # IDE integration bridge (VS Code, JetBrains) 44 + ├── coordinator/ # Multi-agent coordinator 45 + ├── plugins/ # Plugin system 46 + ├── skills/ # Skill system 47 + ├── keybindings/ # Keybinding configuration 48 + ├── vim/ # Vim mode 49 + ├── voice/ # Voice input 50 + ├── remote/ # Remote sessions 51 + ├── server/ # Server mode 52 + ├── memdir/ # Memory directory (persistent memory) 53 + ├── tasks/ # Task management 54 + ├── state/ # State management 55 + ├── migrations/ # Config migrations 56 + ├── schemas/ # Config schemas (Zod) 57 + ├── entrypoints/ # Initialization logic 58 + ├── ink/ # Ink renderer wrapper 59 + ├── buddy/ # Companion sprite (Easter egg) 60 + ├── native-ts/ # Native TypeScript utils 61 + ├── outputStyles/ # Output styling 62 + ├── query/ # Query pipeline 63 + └── upstreamproxy/ # Proxy configuration 62 64 ``` 63 65 64 66 --- 65 67 66 - ## 핵심 아키텍처 68 + ## Core Architecture 67 69 68 - ### 1. 툴 시스템 (`src/tools/`) 70 + ### 1. Tool System (`src/tools/`) 69 71 70 - Claude Code가 사용하는 모든 도구의 구현체입니다. 각 툴은 독립적인 디렉토리에 정의되어 있습니다. 72 + Every tool Claude Code can invoke is implemented as a self-contained module. Each tool defines its input schema, permission model, and execution logic. 71 73 72 - | 툴 | 설명 | 74 + | Tool | Description | 73 75 |---|---| 74 - | `BashTool` | 셸 명령 실행 | 75 - | `FileReadTool` | 파일 읽기 (이미지, PDF, 노트북 포함) | 76 - | `FileWriteTool` | 파일 생성/덮어쓰기 | 77 - | `FileEditTool` | 파일 부분 수정 (string replacement) | 78 - | `GlobTool` | 파일 패턴 매칭 검색 | 79 - | `GrepTool` | ripgrep 기반 콘텐츠 검색 | 80 - | `WebFetchTool` | URL 콘텐츠 가져오기 | 81 - | `WebSearchTool` | 웹 검색 | 82 - | `AgentTool` | 서브에이전트 생성 | 83 - | `SkillTool` | 스킬 실행 | 84 - | `MCPTool` | MCP 서버 툴 호출 | 85 - | `LSPTool` | Language Server Protocol 연동 | 86 - | `NotebookEditTool` | Jupyter 노트북 편집 | 87 - | `TaskCreateTool` / `TaskUpdateTool` | 태스크 생성/관리 | 88 - | `SendMessageTool` | 에이전트 간 메시지 전송 | 89 - | `TeamCreateTool` / `TeamDeleteTool` | 팀 에이전트 관리 | 90 - | `EnterPlanModeTool` / `ExitPlanModeTool` | 계획 모드 전환 | 91 - | `EnterWorktreeTool` / `ExitWorktreeTool` | Git worktree 격리 | 92 - | `ToolSearchTool` | 지연 로드된 툴 검색 | 93 - | `CronCreateTool` | 스케줄 트리거 생성 | 94 - | `RemoteTriggerTool` | 원격 트리거 | 95 - | `SleepTool` | 프로액티브 모드 대기 | 96 - | `SyntheticOutputTool` | 구조화된 출력 생성 | 76 + | `BashTool` | Shell command execution | 77 + | `FileReadTool` | File reading (images, PDFs, notebooks) | 78 + | `FileWriteTool` | File creation / overwrite | 79 + | `FileEditTool` | Partial file modification (string replacement) | 80 + | `GlobTool` | File pattern matching search | 81 + | `GrepTool` | ripgrep-based content search | 82 + | `WebFetchTool` | Fetch URL content | 83 + | `WebSearchTool` | Web search | 84 + | `AgentTool` | Sub-agent spawning | 85 + | `SkillTool` | Skill execution | 86 + | `MCPTool` | MCP server tool invocation | 87 + | `LSPTool` | Language Server Protocol integration | 88 + | `NotebookEditTool` | Jupyter notebook editing | 89 + | `TaskCreateTool` / `TaskUpdateTool` | Task creation and management | 90 + | `SendMessageTool` | Inter-agent messaging | 91 + | `TeamCreateTool` / `TeamDeleteTool` | Team agent management | 92 + | `EnterPlanModeTool` / `ExitPlanModeTool` | Plan mode toggle | 93 + | `EnterWorktreeTool` / `ExitWorktreeTool` | Git worktree isolation | 94 + | `ToolSearchTool` | Deferred tool discovery | 95 + | `CronCreateTool` | Scheduled trigger creation | 96 + | `RemoteTriggerTool` | Remote trigger | 97 + | `SleepTool` | Proactive mode wait | 98 + | `SyntheticOutputTool` | Structured output generation | 97 99 98 - ### 2. 커맨드 시스템 (`src/commands/`) 100 + ### 2. Command System (`src/commands/`) 99 101 100 - 사용자가 `/`로 시작하는 슬래시 커맨드입니다. 102 + User-facing slash commands invoked with `/` prefix. 101 103 102 - | 커맨드 | 설명 | 104 + | Command | Description | 103 105 |---|---| 104 - | `/commit` | Git 커밋 생성 | 105 - | `/review` | 코드 리뷰 | 106 - | `/compact` | 컨텍스트 압축 | 107 - | `/mcp` | MCP 서버 관리 | 108 - | `/config` | 설정 관리 | 109 - | `/doctor` | 환경 진단 | 110 - | `/login` / `/logout` | 인증 | 111 - | `/memory` | 영속 기억 관리 | 112 - | `/skills` | 스킬 관리 | 113 - | `/tasks` | 태스크 관리 | 114 - | `/vim` | Vim 모드 토글 | 115 - | `/diff` | 변경사항 확인 | 116 - | `/cost` | 비용 확인 | 117 - | `/theme` | 테마 변경 | 118 - | `/context` | 컨텍스트 시각화 | 119 - | `/pr_comments` | PR 코멘트 확인 | 120 - | `/resume` | 이전 세션 복원 | 121 - | `/share` | 세션 공유 | 122 - | `/desktop` | 데스크톱 앱 연결 | 123 - | `/mobile` | 모바일 앱 연결 | 106 + | `/commit` | Create a git commit | 107 + | `/review` | Code review | 108 + | `/compact` | Context compression | 109 + | `/mcp` | MCP server management | 110 + | `/config` | Settings management | 111 + | `/doctor` | Environment diagnostics | 112 + | `/login` / `/logout` | Authentication | 113 + | `/memory` | Persistent memory management | 114 + | `/skills` | Skill management | 115 + | `/tasks` | Task management | 116 + | `/vim` | Vim mode toggle | 117 + | `/diff` | View changes | 118 + | `/cost` | Check usage cost | 119 + | `/theme` | Change theme | 120 + | `/context` | Context visualization | 121 + | `/pr_comments` | View PR comments | 122 + | `/resume` | Restore previous session | 123 + | `/share` | Share session | 124 + | `/desktop` | Desktop app handoff | 125 + | `/mobile` | Mobile app handoff | 124 126 125 - ### 3. 서비스 레이어 (`src/services/`) 127 + ### 3. Service Layer (`src/services/`) 126 128 127 - | 서비스 | 설명 | 129 + | Service | Description | 128 130 |---|---| 129 - | `api/` | Anthropic API 클라이언트, 파일 API, 부트스트랩 | 130 - | `mcp/` | Model Context Protocol 서버 연결 및 관리 | 131 - | `oauth/` | OAuth 2.0 인증 플로우 | 132 - | `lsp/` | Language Server Protocol 매니저 | 133 - | `analytics/` | GrowthBook 기반 피처 플래그 및 분석 | 134 - | `plugins/` | 플러그인 로더 | 135 - | `compact/` | 대화 컨텍스트 압축 | 136 - | `policyLimits/` | 조직 정책 제한 | 137 - | `remoteManagedSettings/` | 원격 관리 설정 | 138 - | `extractMemories/` | 자동 기억 추출 | 139 - | `tokenEstimation.ts` | 토큰 수 추정 | 140 - | `teamMemorySync/` | 팀 메모리 동기화 | 131 + | `api/` | Anthropic API client, file API, bootstrap | 132 + | `mcp/` | Model Context Protocol server connection and management | 133 + | `oauth/` | OAuth 2.0 authentication flow | 134 + | `lsp/` | Language Server Protocol manager | 135 + | `analytics/` | GrowthBook-based feature flags and analytics | 136 + | `plugins/` | Plugin loader | 137 + | `compact/` | Conversation context compression | 138 + | `policyLimits/` | Organization policy limits | 139 + | `remoteManagedSettings/` | Remote managed settings | 140 + | `extractMemories/` | Automatic memory extraction | 141 + | `tokenEstimation.ts` | Token count estimation | 142 + | `teamMemorySync/` | Team memory synchronization | 141 143 142 - ### 4. 브릿지 시스템 (`src/bridge/`) 144 + ### 4. Bridge System (`src/bridge/`) 143 145 144 - IDE 확장(VS Code, JetBrains)과 Claude Code CLI를 연결하는 양방향 통신 레이어입니다. 146 + A bidirectional communication layer connecting IDE extensions (VS Code, JetBrains) with the Claude Code CLI. 145 147 146 - - `bridgeMain.ts` — 브릿지 메인 루프 147 - - `bridgeMessaging.ts` — 메시지 프로토콜 148 - - `bridgePermissionCallbacks.ts` — 권한 콜백 149 - - `replBridge.ts` — REPL 세션 브릿지 150 - - `jwtUtils.ts` — JWT 기반 인증 151 - - `sessionRunner.ts` — 세션 실행 관리 148 + - `bridgeMain.ts` — Bridge main loop 149 + - `bridgeMessaging.ts` — Message protocol 150 + - `bridgePermissionCallbacks.ts` — Permission callbacks 151 + - `replBridge.ts` — REPL session bridge 152 + - `jwtUtils.ts` — JWT-based authentication 153 + - `sessionRunner.ts` — Session execution management 152 154 153 - ### 5. 권한 시스템 (`src/hooks/toolPermission/`) 155 + ### 5. Permission System (`src/hooks/toolPermission/`) 154 156 155 - 모든 툴 호출에 대해 권한을 검사하는 시스템입니다. 사용자에게 승인/거부를 요청하거나, 설정된 권한 모드(`default`, `plan`, `bypassPermissions`, `auto` 등)에 따라 자동으로 처리합니다. 157 + 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.). 156 158 157 - ### 6. 피처 플래그 159 + ### 6. Feature Flags 158 160 159 - Bun의 `bun:bundle` feature flag를 활용한 데드코드 제거: 161 + Dead code elimination via Bun's `bun:bundle` feature flags: 160 162 161 163 ```typescript 162 164 import { feature } from 'bun:bundle' 163 165 164 - // 빌드 시점에 비활성 코드를 완전히 제거 166 + // Inactive code is completely stripped at build time 165 167 const voiceCommand = feature('VOICE_MODE') 166 168 ? require('./commands/voice/index.js').default 167 169 : null 168 170 ``` 169 171 170 - 주요 피처 플래그: `PROACTIVE`, `KAIROS`, `BRIDGE_MODE`, `DAEMON`, `VOICE_MODE`, `AGENT_TRIGGERS`, `MONITOR_TOOL` 등 172 + Notable flags: `PROACTIVE`, `KAIROS`, `BRIDGE_MODE`, `DAEMON`, `VOICE_MODE`, `AGENT_TRIGGERS`, `MONITOR_TOOL` 171 173 172 174 --- 173 175 174 - ## 주요 파일 상세 176 + ## Key Files in Detail 175 177 176 - ### `QueryEngine.ts` (~46K 라인) 178 + ### `QueryEngine.ts` (~46K lines) 177 179 178 - LLM API 호출의 핵심 엔진입니다. 스트리밍 응답 처리, 툴 호출 루프, thinking 모드, 재시도 로직, 토큰 카운팅 등을 담당합니다. 180 + The core engine for LLM API calls. Handles streaming responses, tool-call loops, thinking mode, retry logic, and token counting. 179 181 180 - ### `Tool.ts` (~29K 라인) 182 + ### `Tool.ts` (~29K lines) 181 183 182 - 모든 툴의 기본 타입과 인터페이스를 정의합니다. 툴 입력 스키마, 권한 모델, 진행 상태 타입 등이 포함됩니다. 184 + Defines base types and interfaces for all tools — input schemas, permission models, and progress state types. 183 185 184 - ### `commands.ts` (~25K 라인) 186 + ### `commands.ts` (~25K lines) 185 187 186 - 모든 슬래시 커맨드의 등록과 실행을 관리합니다. 조건부 임포트를 통해 환경별로 다른 커맨드 세트를 로드합니다. 188 + Manages registration and execution of all slash commands. Uses conditional imports to load different command sets per environment. 187 189 188 190 ### `main.tsx` 189 191 190 - Commander.js 기반의 CLI 파서 + React/Ink 렌더러 초기화. 시작 시 MDM 설정, 키체인 프리페치, GrowthBook 초기화 등을 병렬로 수행합니다. 192 + Commander.js-based CLI parser + React/Ink renderer initialization. At startup, parallelizes MDM settings, keychain prefetch, and GrowthBook initialization for faster boot. 191 193 192 194 --- 193 195 194 - ## 기술 스택 196 + ## Tech Stack 195 197 196 - | 카테고리 | 기술 | 198 + | Category | Technology | 197 199 |---|---| 198 - | 런타임 | [Bun](https://bun.sh) | 199 - | 언어 | TypeScript (strict) | 200 - | 터미널 UI | [React](https://react.dev) + [Ink](https://github.com/vadimdemedes/ink) | 201 - | CLI 파싱 | [Commander.js](https://github.com/tj/commander.js) (extra-typings) | 202 - | 스키마 검증 | [Zod v4](https://zod.dev) | 203 - | 검색 | [ripgrep](https://github.com/BurntSushi/ripgrep) (Grep 툴) | 204 - | 프로토콜 | [MCP SDK](https://modelcontextprotocol.io), LSP | 200 + | Runtime | [Bun](https://bun.sh) | 201 + | Language | TypeScript (strict) | 202 + | Terminal UI | [React](https://react.dev) + [Ink](https://github.com/vadimdemedes/ink) | 203 + | CLI Parsing | [Commander.js](https://github.com/tj/commander.js) (extra-typings) | 204 + | Schema Validation | [Zod v4](https://zod.dev) | 205 + | Code Search | [ripgrep](https://github.com/BurntSushi/ripgrep) (via GrepTool) | 206 + | Protocols | [MCP SDK](https://modelcontextprotocol.io), LSP | 205 207 | API | [Anthropic SDK](https://docs.anthropic.com) | 206 - | 텔레메트리 | OpenTelemetry + gRPC | 207 - | 피처 플래그 | GrowthBook | 208 - | 인증 | OAuth 2.0, JWT, macOS Keychain | 208 + | Telemetry | OpenTelemetry + gRPC | 209 + | Feature Flags | GrowthBook | 210 + | Auth | OAuth 2.0, JWT, macOS Keychain | 209 211 210 212 --- 211 213 212 - ## 주목할만한 설계 패턴 214 + ## Notable Design Patterns 213 215 214 - ### 병렬 프리페치 216 + ### Parallel Prefetch 215 217 216 - 시작 시간을 최적화하기 위해 MDM 설정, 키체인, API preconnect 등을 병렬로 프리페치합니다. 218 + Startup time is optimized by prefetching MDM settings, keychain reads, and API preconnect in parallel — before heavy module evaluation begins. 217 219 218 220 ```typescript 219 - // main.tsx — 모듈 임포트 전에 side-effect로 실행 221 + // main.tsx — fired as side-effects before other imports 220 222 startMdmRawRead() 221 223 startKeychainPrefetch() 222 224 ``` 223 225 224 - ### 지연 로딩 (Lazy Loading) 226 + ### Lazy Loading 225 227 226 - 무거운 모듈(OpenTelemetry ~400KB, gRPC ~700KB)은 실제로 필요할 때까지 `import()`로 지연 로딩합니다. 228 + Heavy modules (OpenTelemetry ~400KB, gRPC ~700KB) are deferred via dynamic `import()` until actually needed. 227 229 228 - ### 에이전트 스웜 230 + ### Agent Swarms 229 231 230 - `AgentTool`을 통해 서브에이전트를 생성하고, `coordinator/`가 멀티에이전트 오케스트레이션을 담당합니다. `TeamCreateTool`로 팀 단위 병렬 작업도 지원합니다. 232 + Sub-agents are spawned via `AgentTool`, with `coordinator/` handling multi-agent orchestration. `TeamCreateTool` enables team-level parallel work. 231 233 232 - ### 스킬 시스템 234 + ### Skill System 233 235 234 - `skills/` 디렉토리에 재사용 가능한 워크플로우를 정의하고, `SkillTool`로 실행합니다. 사용자가 커스텀 스킬을 추가할 수 있습니다. 236 + Reusable workflows defined in `skills/` and executed through `SkillTool`. Users can add custom skills. 235 237 236 - ### 플러그인 아키텍처 238 + ### Plugin Architecture 237 239 238 - `plugins/` 를 통해 빌트인 플러그인과 서드파티 플러그인을 로드합니다. 240 + Built-in and third-party plugins are loaded through the `plugins/` subsystem. 239 241 240 242 --- 241 243 242 - ## 라이선스 244 + ## License 243 245 244 - 이 레포지토리는 분석 및 학습 목적으로만 사용됩니다. 원본 소스코드의 저작권은 [Anthropic](https://www.anthropic.com)에 있습니다. 246 + This repository is for analysis and educational purposes only. All original source code is copyrighted by [Anthropic](https://www.anthropic.com).