Skip to content

fuyundev/claude-code-source

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Claude Code Source Analysis

Deep architecture analysis of Claude Code — Anthropic's official CLI for Claude, an AI-powered interactive development assistant.

Project Overview

Claude Code is a sophisticated TypeScript/React terminal application built with a custom Ink-like React-to-terminal renderer. It provides an AI-powered interactive shell for software engineering tasks including code editing, debugging, search, and multi-agent coordination.

  • Language: TypeScript + React (TSX)
  • Runtime: Bun (primary), with bun:bundle feature flags for compile-time dead code elimination
  • Terminal UI: Custom Ink-like implementation using React
  • Module System: ESM (import/export)
  • Scale: ~1,884 TypeScript/TSX files

Architecture Overview

┌─────────────────────────────────────────────────────┐
│  CLI Entry Points (entrypoints/cli.tsx, main.tsx)    │
├─────────────────────────────────────────────────────┤
│  Interactive Shell (screens/REPL.tsx, ink/)           │
├─────────────────────────────────────────────────────┤
│  Commands (commands/, commands.ts)  ←→  Skills       │
├─────────────────────────────────────────────────────┤
│  Query Engine (QueryEngine.ts, query.ts)             │
│  Tool System (Tool.ts, tools.ts, tools/)             │
├─────────────────────────────────────────────────────┤
│  State Management (state/, bootstrap/)               │
│  Services (api/, mcp/, compact/)                     │
├─────────────────────────────────────────────────────┤
│  MCP/Plugin System    │  Coordinator (multi-agent)   │
│  Remote Execution     │  Utilities & Infrastructure  │
└─────────────────────────────────────────────────────┘

Key Modules

Entry Points

File Description
main.tsx (~803KB) Primary entry point. Handles startup profiling, prefetching (MDM settings, keychain, MCP registry), model initialization, settings/migration loading, permission setup, analytics, and routing to interactive vs headless mode.
entrypoints/cli.tsx (~39KB) Fast-path bootstrap for special CLI flags (--version, --dump-system-prompt, --daemon-worker, --claude-in-chrome-mcp, etc.) that bypass the full app loading.
entrypoints/init.ts (~13KB) Core system initialization before main loop — trust dialog, analytics, policy limits.

Core Engine

File Description
QueryEngine.ts (~46KB) Core conversation engine. Orchestrates message processing, streaming API calls with retry logic, tool execution via StreamingToolExecutor, and multiple compaction strategies (auto-compact, microcompact, reactive compact, context collapse). Manages permissions, hooks, extended thinking, and budget tracking.
query.ts (~68KB) Main query function. Builds query config from runtime gates, prepares system/user context, fetches attachment messages (memory, CLAUDE.md), calls the API with streaming, processes tool use blocks, records transcripts, and manages token/cost budgets.

Tool System

File Description
Tool.ts (~29KB) Defines the fundamental Tool interface — name, description, JSON Schema parameters, ToolUseContext for execution, ToolPermissionContext for permission management, progress types, and result/error handling.
tools.ts (~17KB) Central tool registry. getAllBaseTools() is the source of truth for all tools. assembleToolPool() combines built-in + MCP tools with dedup and sort-stable ordering for prompt cache stability. Many tools are conditionally loaded via feature() or process.env checks.
tools/ (44+ subdirectories) Each tool is a self-contained module. Core tools include: BashTool, FileReadTool, FileEditTool, FileWriteTool, GlobTool, GrepTool, WebFetchTool, WebSearchTool, AgentTool, SkillTool, NotebookEditTool, and many more.

Tool Categories

  • Core: Bash, File Read/Edit/Write, Glob, Grep, Web Fetch/Search
  • Task Management: TaskCreate, TaskGet, TaskUpdate, TaskList, TaskStop, TaskOutput
  • Agent: AgentTool (spawn sub-agents), SendMessage (continue agents), TeamCreate/TeamDelete
  • Planning: EnterPlanMode, ExitPlanModeV2
  • Worktree: EnterWorktree, ExitWorktree (git worktree isolation)
  • MCP: ListMcpResources, ReadMcpResource, McpAuth
  • Advanced: WebBrowser, PowerShell, REPL, Notebook, LSP, ToolSearch
  • Scheduling: CronCreate, CronDelete, CronList, RemoteTrigger
  • Feature-gated: Many tools use feature() from bun:bundle for compile-time dead code elimination

Command System

File Description
commands.ts (~25KB) Exports all 88+ slash commands with Commander.js integration.
commands/ (88 subdirectories) Each command is self-contained with builder, handler, and optional React/Ink dialog components.

Command Categories

  • Utility: help, version, clear, color, theme, config, status, usage, cost
  • Session: session, resume, share, session.history
  • Development: commit, review, pr-comments, diff, autofix-pr, security-review
  • File Operations: files, copy, rename
  • Project Management: tasks, plan, agent, skills, memory, onboarding
  • Advanced: permissions, hooks, mcp, plugin, teleport, desktop, ide, mobile, voice, vim
  • Feature-gated: proactive, brief, assistant, bridge, workflow, ultraplan, torch, buddy

Skills System

Directory Description
skills/bundled/ Built-in skills registered via initBundledSkills(). Includes: updateConfig, keybindings, verify, debug, simplify, skillify, remember, batch, loop, scheduleRemoteAgents, claudeApi, claudeInChrome, and more.

State Management

File Description
state/AppState.tsx (~23KB) Centralized immutable state store using DeepImmutable types. Manages: settings, model selection, UI state, agent coordination, permissions, hooks, attributes, file history, tasks, memory, theme.
state/AppStateStore.ts (~21KB) Store implementation with getter/setter patterns.
state/onChangeAppState.ts (~6KB) Side effect handlers — settings persistence, model capability refresh, analytics events, UI updates.
bootstrap/state.ts (~56KB) Global singleton state registry — session identity, model info, CWD, cost tracking, auth (OAuth tokens, API keys), feature gates, hooks, performance profiling.

Services Layer

API Client

File Description
services/api/claude.ts (~125KB) Claude API client with streaming, retries, cache breaking.
services/api/bootstrap.ts Bootstrap data fetching.
services/api/filesApi.ts File upload/download.

MCP (Model Context Protocol)

File Description
services/mcp/client.ts (~119KB) Main MCP client managing server connections.
services/mcp/config.ts (~51KB) Configuration parsing, validation, merging from multiple sources (settings, env, project files).
services/mcp/auth.ts (~88KB) OAuth/authentication for MCP servers, including XAA IDP login.
services/mcp/officialRegistry.ts Official MCP registry synchronization.

Message Compaction

Directory Description
services/compact/ Multiple strategies for managing context window limits: auto-compact with token thresholds, microcompact, snip compact, reactive compact, context collapse, and tool use summary generation.

Other Services

  • services/analytics/: GrowthBook feature flags, event logging
  • services/lsp/: Language Server Protocol integration
  • services/SessionMemory/: Session memory management
  • services/extractMemories/: AI-powered memory extraction
  • services/oauth/: OAuth flow handling
  • services/plugins/: Plugin loading and management
  • services/policyLimits/: Enterprise policy enforcement
  • services/remoteManagedSettings/: Remote configuration management
  • services/teamMemorySync/: Team memory synchronization

UI Layer

File/Directory Description
ink/ Custom terminal UI framework (React-to-terminal renderer). Core rendering engine ink.tsx (~251KB), Ansi.tsx (~33KB) for ANSI code generation, plus DOM abstraction, focus management, frame rendering, and color utilities.
screens/REPL.tsx (~895KB) Main interactive shell screen — the primary user-facing UI.
screens/ResumeConversation.tsx (~59KB) Session recovery UI.
screens/Doctor.tsx (~73KB) Diagnostics and health check.
components/ (33 subdirectories) React/Ink components: design-system (themed Box/Text), messages, permissions, tasks, mcp, diff visualization, agents, Spinner, PromptInput, Settings, and more.

Multi-Agent Coordination

File Description
coordinator/coordinatorMode.ts (~19KB) Multi-agent orchestration system. A coordinator spawns worker agents via AgentTool, communicates via SendMessage, and manages a durable cross-worker scratchpad. Feature-gated via COORDINATOR_MODE.

Remote Execution (CCR)

File Description
remote/RemoteSessionManager.ts (~9KB) Manages remote CCR (Cloud Code Runtime) sessions.
remote/SessionsWebSocket.ts (~12KB) WebSocket client for session streaming with reconnection logic.
remote/sdkMessageAdapter.ts (~9KB) Maps SDK messages to/from remote format.
utils/teleport/ Clone remote repository locally, validate git state, process messages for resume.

Utilities & Infrastructure

  • utils/permissions/: Permission system, auto-mode, bypass modes
  • utils/model/: Model resolution, capabilities, deprecation warnings
  • utils/git/: Git integration (status, branch, diffs)
  • utils/github/: GitHub API integration
  • utils/settings/: Configuration loading from multiple sources (settings.json, env, policy)
  • utils/hooks/: Permission hooks, post-sampling hooks
  • utils/messages/: Message creation, normalization, compaction utilities
  • utils/sandbox/: Sandbox adapter for secure execution
  • utils/skills/: Skill loading and management
  • utils/bash/: Bash execution utilities
  • native-ts/: Native compiled modules (color-diff, file-index, yoga-layout)

Key Data Flow

Interactive Query Loop

main.tsx (startup & prefetching)
  → entrypoints/init.ts (system initialization)
  → screens/REPL.tsx (interactive shell)
  → User input via PromptInput component
  → query() function (query.ts)
  → QueryEngine.ts (conversation orchestration)
    → queryModelWithStreaming (Claude API call)
    → runTools (execute tool calls)
    → normalizeMessages / compact (context management)
  → Response rendered back to UI

Multi-Agent Coordination

User message → Coordinator (query.ts)
  → AgentTool spawns worker agents
  → Workers run in separate contexts with limited tools
  → Worker results returned as task-notification messages
  → Coordinator synthesizes results for user

Remote Execution (CCR)

Local CLI (CLAUDE_CODE_REMOTE=true)
  → RemoteSessionManager
  → SessionsWebSocket (WebSocket streaming)
  → Remote CCR server → Remote QueryEngine → Remote tools
  → Results streamed back via WebSocket

Architecture Patterns

Feature Gating (Three Levels)

  1. Compile-time: feature() from bun:bundle for dead code elimination
  2. Runtime environment: process.env checks (e.g., USER_TYPE === 'ant' for Anthropic-internal features)
  3. Remote flags: Statsig/GrowthBook gates for A/B testing

Conditional Tool Loading

Tools in tools.ts use require() inside conditionals to enable tree-shaking:

const WebBrowserTool = feature('WEB_BROWSER_TOOL')
  ? require('./tools/WebBrowserTool/WebBrowserTool.js').WebBrowserTool
  : null

Immutable State

AppState uses DeepImmutable types with getter/setter access patterns and side-effect handlers on state changes.

Dependency Injection

QueryEngine accepts a deps parameter for testability, allowing injection of callModel, microcompact, autocompact, etc.

Lazy Imports for Circular Dependencies

const getTeamCreateTool = () =>
  require('./tools/TeamCreateTool/TeamCreateTool.js').TeamCreateTool

Prompt Cache Stability

assembleToolPool() sorts built-in tools as a contiguous prefix, with MCP tools appended separately, to maintain stable prompt cache keys.

License

This repository contains source code analysis for educational and research purposes.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors