MCP Hub
Back to servers

claude-code-source-all-in-one

Always up-to-date open-source mirror of Claude Code with GPT-5.4 support. Run Claude Code from source with Claude or GPT models via ChatGPT subscription. 18 deep-dive architecture articles included. For educational and reference purposes only.

GitHub
Stars
65
Forks
85
Updated
Apr 16, 2026
Validated
Apr 18, 2026

Claude Code

Claude Code Source — Architecture Study & Learning Material

Production-grade AI Agent internals, dissected for learning.

Claude Code v2.1.89 Educational Only 18 Articles Runnable

中文版


This repository contains the extracted source code of Claude Code (Anthropic's AI programming CLI) along with 18 original deep-analysis articles (bilingual: English & Chinese) dissecting its architecture. The source was discovered from publicly available repositories and is provided strictly for educational and research purposes.

All intellectual property rights of the source code belong exclusively to Anthropic, PBC.

Kept in sync with upstream. This repository tracks the official Claude Code release stream and is kept current with the latest version. Each upstream release has a corresponding update applying the user-facing, tractable subset of its changelog — see CHANGELOG.md for the per-version record of what was applied here and what remains upstream-only.


Disclaimer · Why Study This · Architecture · Deep Analysis · Run from Source · Tech Stack · Structure · License


Disclaimer

IMPORTANT: READ BEFORE USE

This repository is strictly for educational and research purposes only.

  • Source: The source code was discovered from publicly available sources, including instructkr/claw-code. The run-from-source setup is based on JiaranI/start-claude-code. It contains extracted source code of Claude Code, a product by Anthropic.
  • Ownership: All intellectual property rights belong exclusively to Anthropic, PBC. This repository claims no ownership, authorship, or rights over the original code.
  • Purpose: Provided solely as learning material for understanding AI agent system architecture and engineering patterns — for academic study, technical research, and educational discussion.
  • Prohibited uses:
    • Commercial purposes of any kind
    • Building competing products or services
    • Redistribution or repackaging of the source code
    • Any purpose that violates Anthropic's Terms of Service or applicable laws
  • Analysis articles: The deep analysis articles (claude-code-deep-analysis/) are original commentary and analysis by the repository maintainers. Code snippets are included for commentary, criticism, and education purposes. These articles do not constitute legal advice.
  • DMCA / Takedown: If you represent Anthropic or believe this repository infringes on intellectual property rights, please contact us — we will promptly remove the infringing content. You may also file a DMCA takedown notice through GitHub's DMCA process.
  • No warranty: Provided "as is" without warranty of any kind.

Why study this codebase?

Claude Code is one of the most sophisticated production AI agent systems publicly observable. Unlike toy frameworks and demo agents, it is engineered for real-world, hours-long coding sessions with enterprise-grade reliability. Studying it reveals hard-won engineering decisions that no tutorial covers:

Design DecisionInsight
Loop over GraphA while(true) loop replaces DAG-based workflow orchestration — simpler, more flexible, easier to reason about at runtime
Recursion over OrchestrationSub-agents recursively call query(), inheriting compression, error recovery, and streaming for free
Model decides, Framework executesThe framework enforces safety constraints (concurrency, side effects, permissions); all reasoning stays in the model
Built for 4-hour sessionsFour-layer context compression and three-level 413 error recovery — invisible in demos, critical in production
Immutability as cost optimizationImmutable API messages maximize prompt caching hits, reducing long-session costs by ~80%

Architecture at a glance

                        CLI / VS Code / IDE Extension
                                    │
                                    ▼
                        ┌───────────────────────┐
                        │   EntryPoint (cli.tsx)  │
                        │   Fast-path routing     │
                        └───────────┬───────────┘
                                    │
                        ┌───────────▼───────────┐
                        │     QueryEngine         │
                        │   Session management    │
                        │   API client wrapper    │
                        └───────────┬───────────┘
                                    │
                ┌───────────────────▼───────────────────┐
                │          query() — Core Agent Loop     │
                │   ┌─────────────────────────────────┐  │
                │   │  while (true) {                 │  │
                │   │    messages = buildPrompt()      │  │
                │   │    response = stream(messages)   │  │
                │   │    tools = extractToolCalls()    │  │
                │   │    if (!tools) break             │  │
                │   │    results = executePar(tools)   │  │
                │   │    messages.push(results)        │  │
                │   │    maybeCompress(messages)       │  │
                │   │  }                              │  │
                │   └─────────────────────────────────┘  │
                └──────┬──────────┬──────────┬──────────┘
                       │          │          │
              ┌────────▼──┐ ┌────▼────┐ ┌───▼────────┐
              │ 45+ Tools  │ │ Permis- │ │ Context    │
              │ Bash, Edit │ │ sion    │ │ Compression│
              │ Glob, Grep │ │ System  │ │ 4 layers   │
              │ MCP, LSP…  │ │ 5 modes │ │ + 413 heal │
              └────────────┘ └─────────┘ └────────────┘

By the numbers

MetricCount
Core agent loop (query.ts)1,729 lines
Main UI component (main.tsx)4,683 lines
Tool implementations45+
Slash commands87+
React UI components146+
Utility functions564+
React hooks85+
Service modules38
Feature flags89
System prompt assembly (prompts.ts)54.3 KB

Deep Analysis Series

We produced 18 original articles with source-level deep dives into every major subsystem. Each article is available in both English and Chinese.

Enter the analysis series (EN) →进入分析系列 (中文) →

Part 1: Core Agent Engine

#TopicEnglish中文
00Core ConclusionsEN中文
01Entry PointEN中文
02Main LoopEN中文
03StreamingEN中文
04Tool OrchestrationEN中文
05Permission SystemEN中文
06Sub-AgentsEN中文
07Context WindowEN中文
08Message TypesEN中文
09Immutable MessagesEN中文
10Architecture DiagramEN中文
11Design PhilosophyEN中文

Part 2: Peripheral Subsystems

#TopicEnglish中文
12MCP IntegrationEN中文
13Memory SystemEN中文
14System PromptEN中文
15Session & BridgeEN中文
16Tool ImplementationsEN中文
17Hook SystemEN中文

Run from Source

This repository supports running Claude Code locally from source (with reduced functionality). Verified working with version 2.1.89.

Prerequisites

DependencyNotes
Node.js >= 18For the setup script
Bun >= 1.0Runtime for Claude Code (auto-installed by setup)
AuthenticationClaude Pro/Max/Team subscription (OAuth), API key (sk-ant-xxx), ChatGPT subscription, or OpenAI API key

Quick start

# 1. Install dependencies and generate shims
node scripts/setup.mjs

# 2. Login with your Claude subscription (opens browser)
./start.sh login

# 3. Launch
./start.sh

Claude Code running with subscription login
Running from source with Claude Pro/Max subscription — Opus 4.6 (1M context) ✓

Alternative: Use an API key instead
export ANTHROPIC_API_KEY="sk-ant-xxx"
./start.sh
Alternative: Use GPT-5.4 via ChatGPT subscription

If you have a ChatGPT Plus/Pro/Team subscription, you can use GPT-5.4 as the agent model — no API key needed:

# 1. Login with your ChatGPT account (opens browser)
./start.sh chatgpt-login

# 2. Launch with GPT-5.4
./start.sh --model gpt5.4

GPT-5.4 running via ChatGPT subscription
Running GPT-5.4 via ChatGPT subscription as the agent model

Available GPT model aliases: gpt5.4, gpt5.4-mini, gpt5.4-nano

You can also use the full format: --model chatgpt:gpt-5.4

Alternative: Use OpenAI API key
export OPENAI_API_KEY="sk-xxx"
./start.sh --model openai:gpt-5.4

Other OpenAI-compatible providers are also supported:

export DEEPSEEK_API_KEY="sk-xxx"
./start.sh --model deepseek:deepseek-chat

export MISTRAL_API_KEY="xxx"
./start.sh --model mistral:mistral-large-latest
Windows users
rem Use API key on Windows (OAuth login requires start.sh on macOS/Linux)
set ANTHROPIC_API_KEY=sk-ant-xxx
bun src/entrypoints/cli.tsx
  • ripgrep: The tar extraction in the setup script may fail on Windows. Install ripgrep manually and ensure rg is on your PATH.
  • Bun path: After installing Bun, restart your terminal or add %USERPROFILE%\.bun\bin to PATH.
  • OAuth login: start.sh login is macOS/Linux only. On Windows, run bun src/entrypoints/cli.tsx auth login --claudeai.

Shim files created

These files are not part of the original source — they were created to make the source runnable:

FilePurpose
package.json100+ dependencies reverse-engineered from import statements
tsconfig.jsonTypeScript config with baseUrl and .js → .ts/.tsx path resolution
bunfig.tomlBun config specifying the preload plugin
preload.tsCore shim: bun:bundle mock (feature() returns false), MACRO.* global injection
scripts/setup.mjsOne-command setup: dependency install, private package stubs, missing file generation, ripgrep download
start.shmacOS/Linux launcher with OAuth login (./start.sh login), credential detection (Keychain/file/env), proxy auto-detection, Bun transpiler cache cleanup

How it works

ChallengeSolution
bun:bundle compile-time APIpreload.ts provides a runtime shim; feature() returns false for all flags
89 feature flagsAll disabled — feature-gated code paths do not execute
MACRO.* compile-time macrosDefined as globalThis.MACRO in preload.ts
from 'src/...' importsSource under src/; tsconfig.json baseUrl: "." for natural resolution
No package.jsonReverse-engineered 100+ dependencies from import statements
@ant/* private packagesscripts/setup.mjs creates empty stubs

Unavailable features (missing private packages)

FeatureMissing PackageDescription
Computer Use@ant/computer-use-mcpScreenshots, mouse clicks, keyboard input
Native input@ant/computer-use-inputRust/enigo native bindings
macOS screen/window@ant/computer-use-swiftSwift native bindings (macOS only)
Chrome integration@ant/claude-for-chrome-mcpChrome extension MCP server
Sandbox runtime@anthropic-ai/sandbox-runtimeCommand execution sandbox
MCP Bridge@anthropic-ai/mcpbMCP protocol bridge
All 89 feature flags (all disabled)

Since feature() returns false at runtime, all feature-gated code paths are inactive:

ABLATION_BASELINE AGENT_MEMORY_SNAPSHOT AGENT_TRIGGERS BRIDGE_MODE BUDDY BUILDING_CLAUDE_APPS CCR_AUTO_CONNECT COORDINATOR_MODE DAEMON DIRECT_CONNECT DUMP_SYSTEM_PROMPT FORK_SUBAGENT HISTORY_PICKER KAIROS MCP_SKILLS MONITOR_TOOL NATIVE_CLIPBOARD_IMAGE PERFETTO_TRACING QUICK_SEARCH SSH_REMOTE STREAMLINED_OUTPUT TEAMMEM TEMPLATES TERMINAL_PANEL TORCH ULTRAPLAN ULTRATHINK VOICE_MODE WEB_BROWSER_TOOL WORKFLOW_SCRIPTS and 59 more.

Inferred build pipeline

TypeScript source
  │
  ├─ Bun bundler (bun build)
  │   ├─ Inject MACRO.* constants (--define)
  │   ├─ Resolve feature() calls → set 89 feature flags true/false
  │   ├─ Dead Code Elimination → strip disabled feature branches
  │   └─ Bundle into single JS file
  │
  ├─ Optional: Bun compile → single-file executable binary
  │
  └─ Publish to npm (@anthropic-ai/claude-code)

Troubleshooting

ErrorFix
Cannot find module 'src/...'Verify source is under src/ and bunfig.toml exists
Missing 'default' export in module '*.md'Run node scripts/setup.mjs to regenerate stubs
Cannot find package '@ant/...'Run node scripts/setup.mjs to recreate stubs
bun: command not foundInstall Bun: curl -fsSL https://bun.sh/install | bash
No authentication foundRun ./start.sh login for OAuth, or export ANTHROPIC_API_KEY="sk-ant-xxx" for API key
Using a non-Anthropic proxystart.sh auto-detects; manual: set DISABLE_PROMPT_CACHING=1 and DISABLE_INTERLEAVED_THINKING=1
Only works from one directory / hangs after moving sourceBun caches transpiled modules by absolute path. start.sh clears the cache automatically. If launching manually: rm -rf ~/Library/Caches/bun (macOS) or rm -rf ~/.cache/bun (Linux)

Want the official release?

npm install -g @anthropic-ai/claude-code

Technology stack

LayerTechnologies
RuntimeNode.js >= 18, Bun >= 1.0
LanguageTypeScript with React JSX
UIReact 19, custom terminal reconciler, 146+ components
CLICommander.js 12
AI/LLMAnthropic SDK, Claude Agent SDK, OpenAI SDK, AWS Bedrock, Azure Identity
ProtocolsModel Context Protocol (MCP, 6 transports), LSP, OAuth/XAA
ObservabilityOpenTelemetry (traces, metrics, logs) with OTLP exporters
Code toolsripgrep, Sharp (image processing), Marked, Turndown, Diff

Project structure

claude-code-source/
├── README.md                         # This document (English)
├── README.zh.md                      # 中文版文档
├── assets/                           # Images
│   ├── anthropic-claude-code.webp
│   └── screenshot.png
├── package.json                      # Dependencies (reverse-engineered)
├── tsconfig.json                     # TypeScript configuration
├── bunfig.toml                       # Bun preload configuration
├── preload.ts                        # Runtime shim (feature flags, macros)
├── start.sh                          # Launcher script
├── scripts/setup.mjs                 # One-command setup
│
├── claude-code-deep-analysis/        # 18 original analysis articles (EN + 中文)
│   ├── README.en.md                  #   Series index (English)
│   ├── README.md                     #   Series index (中文)
│   ├── 00-core-conclusion.en.md      #   Each article has .en.md + .md
│   ├── 00-core-conclusion.md
│   ├── ...
│   └── 17-hook-system.en.md
│
└── src/                              # Claude Code source (Anthropic)
    ├── query.ts                      # Core agent loop (1,729 lines)
    ├── QueryEngine.ts                # Session management (46.6 KB)
    ├── Tool.ts                       # Tool interface & registry (29.5 KB)
    ├── main.tsx                      # Main React component (4,683 lines)
    │
    ├── entrypoints/                  # Entry points (CLI, MCP, SDK types)
    ├── commands/                     # 87+ slash commands
    ├── tools/                        # 45+ tool implementations
    │   ├── BashTool/                 #   Shell execution (430 KB of safety code)
    │   ├── AgentTool/                #   Sub-agent execution
    │   ├── FileEditTool/             #   File editing with diff matching
    │   ├── MCPTool/                  #   Model Context Protocol
    │   └── ...                       #   30+ more tools
    │
    ├── services/                     # 38 service modules
    │   ├── api/                      #   Anthropic API integration
    │   ├── mcp/                      #   MCP protocol (25 subdirs)
    │   ├── compact/                  #   Context compression
    │   ├── SessionMemory/            #   Cross-session memory
    │   └── ...
    │
    ├── components/                   # 146+ React UI components
    ├── hooks/                        # 85+ React hooks
    ├── utils/                        # 564+ utility functions
    ├── permissions/                  # Permission system (5 modes)
    ├── bridge/                       # CLI ↔ VS Code integration
    ├── constants/                    # System prompt assembly & config
    ├── memdir/                       # Cross-session memory system
    ├── skills/                       # Skill/plugin system
    ├── voice/                        # Voice input handling
    └── ...

License

  • Source code: All rights belong to Anthropic, PBC. No license is granted.
  • Analysis articles (claude-code-deep-analysis/): Original commentary by the repository maintainers. Code snippets are for educational purposes only.

Contact: For any questions, please reach out via GitHub Issues.

Reviews

No reviews yet

Sign in to write a review