跳到主要内容
极客日志极客日志面向AI+效率的开发者社区
首页博客GitHub 精选镜像工具UI配色美学隐私政策关于联系
搜索内容 / 工具 / 仓库 / 镜像...⌘K搜索
注册
返回 GitHub 精选在 GitHub 打开
chauncygu
本周热门 · 2026-03-30#30

chauncygu/collection-claude-code-source-code

🔥 A collection of the newest Claude Code open source

TypeScript1.5k1.7k3 issues
创建于 2026-03-31最近推送 2026-04-05

项目说明

A collection of the newest Claude Code open source

License and Disclaimer This repository is for academic research and educational purposes only. All subprojects are built from publicly accessible information. Users are responsible for complying with applicable laws, regulations, and service terms.

Source archive of Claude Code and different versions of the clean-room Python rewrite research repository

🔥🔥🔥 News (Pacific Time)

  • 12:20 PM · Apr 02, 2026: Nano Claude Code v3.0: Multi-agent packages, memory package, skill package with built-in skills, argument substitution, fork/inline execution, AI memory search, git worktree isolation, agent type definitions (~5000 Lines)
  • 7:40 AM · Apr 02, 2026: Nano Claude Code v2.0: A Minimal Python Reimplementation (~3400 Lines), support open and closed source models, skill and memory
  • 8:36 AM · Apr 01, 2026: Nano Claude Code v1.0: A Minimal Python Reimplementation (~1300 Lines)
  • 0:20 AM · Apr 01, 2026: Analysis of Claude Code source code (Video: In Chinese)
  • 19:45 PM · Mar 31, 2026: Claude Code Research Report (In Chinese)
  • 17:13 PM · Mar 31, 2026: Architecture Analysis of Claude Code (In Chinese)
  • 16:43 PM · Mar 31, 2026: An Overview of Claude Code Features (In Chinese)
  • 15:00 PM · Mar 31, 2026: Hacker News Community Discussion about Claude Code Leak
  • 11:48 AM · Mar 31, 2026: How Anthropic Built 7 Layers of Memory and a Dreaming System for Claude Code
  • 9:50 AM · Mar 31, 2026: Claude code memory analysis
  • 9:48 AM · Mar 31, 2026: Claude Code's source code appears to have leaked: here's what we know
  • 9:04 AM · Mar 31, 2026: Deconstructing the Claude Code Architecture (In Chinese)
  • 7:07 AM · Mar 31, 2026: A Walkthrough of Claude Code's Source Code (In Chinese)
  • 5:41 AM · Mar 31, 2026: Why Claude Code Outperforms Other Tools: An Analysis
  • 5:03 AM · Mar 31, 2026: Anthropic's AI Coding Tool Leaks Its Own Source Code
  • 3:28 AM · Mar 31, 2026: Claude Code Source Code Unveiled: Prompts, Self-Healing Mechanisms, and Multi-Agent Architecture (In Chinese)
  • 3:02 AM · Mar 31, 2026: Community Reaction to the Claude Code Source Exposure
  • 2:57 AM · Mar 31, 2026: The code behind Claude Code
  • 1:23 AM · Mar 31, 2026: A Viral Post on the Claude Code Source Leak

  • Content

    • 1. original-source-code
    • 2. claude-code-source-code
      • Overall Architecture
      • Core Execution Flow
      • Tech Stack
      • Main Module Descriptions
        • Tool System (40+ tools)
        • Slash Commands (~87)
        • Permission System
        • Context Management
        • Analysis Documents (docs/)
    • 3. claw-code
      • Overall Architecture
      • Core Classes
      • CLI Commands
      • Design Features
    • 4. nano-claude-code
      • Features
      • Supported Models
      • Project Structure
    • Comparison of the Projects
    • License and Disclaimer

    This repository contains subprojects that study Claude Code (Anthropic's official CLI tool) from multiple angles:

    SubprojectLanguageNatureFile Count
    original-source-codeTypeScriptRaw leaked source archive1,884 files
    claude-code-source-codeTypeScriptDecompiled source archive (v2.1.88) + docs1,940 files
    claw-codePythonClean-room architectural rewrite109 files
    nano-claude-codePythonMinimal multi-provider reimplementation~30 files

    1. original-source-code

    The raw leaked TypeScript source of Claude Code, preserved as-is from the original exposure on March 31, 2026. Contains 1,884 TypeScript/TSX files (packaged as src.zip) spanning the full src/ directory tree — the same files that triggered community discussion and downstream research.

    original-source-code/
    ├── src/                  # Full TypeScript source tree (1,884 .ts/.tsx files)
    │   ├── main.tsx          # CLI entry point
    │   ├── query.ts          # Core agent loop
    │   ├── commands.ts       # Slash command definitions
    │   ├── tools.ts          # Tool registration
    │   └── ...               # All other source directories (same layout as claude-code-source-code/src)
    ├── src.zip               # Compressed archive (~9.5 MB)
    └── readme.md
    

    This directory serves as the unmodified reference snapshot. No annotations, docs, or build tooling have been added — use claude-code-source-code for the researched and annotated version.


    2. claude-code-source-code

    A decompiled/unpacked source archive of Claude Code v2.1.88, reconstructed from the npm package @anthropic-ai/[email protected], containing approximately 163,318 lines of TypeScript code.

    Overall Architecture

    claude-code-source-code/
    ├── src/
    │   ├── main.tsx              # CLI entry and REPL bootstrap (4,683 lines)
    │   ├── query.ts              # Core main agent loop (largest single file, 785KB)
    │   ├── QueryEngine.ts        # SDK/Headless query lifecycle engine
    │   ├── Tool.ts               # Tool interface definitions + buildTool factory
    │   ├── commands.ts           # Slash command definitions (~25K lines)
    │   ├── tools.ts              # Tool registration and presets
    │   ├── context.ts            # User input context handling
    │   ├── history.ts            # Session history management
    │   ├── cost-tracker.ts       # API cost tracking
    │   ├── setup.ts              # First-run initialization
    │   │
    │   ├── cli/                  # CLI infrastructure (stdio, structured transports)
    │   ├── commands/             # ~87 slash command implementations
    │   ├── components/           # React/Ink terminal UI (33 subdirectories)
    │   ├── tools/                # 40+ tool implementations (44 subdirectories)
    │   ├── services/             # Business logic layer (22 subdirectories)
    │   ├── utils/                # Utility function library
    │   ├── state/                # Application state management
    │   ├── types/                # TypeScript type definitions
    │   ├── hooks/                # React Hooks
    │   ├── bridge/               # Claude Desktop remote bridge
    │   ├── remote/               # Remote mode
    │   ├── coordinator/          # Multi-agent coordination
    │   ├── tasks/                # Task management
    │   ├── assistant/            # KAIROS assistant mode
    │   ├── memdir/               # Long-term memory management
    │   ├── plugins/              # Plugin system
    │   ├── voice/                # Voice mode
    │   └── vim/                  # Vim mode
    │
    ├── docs/                     # In-depth analysis docs (bilingual: Chinese/English)
    │   ├── en/                   # English analysis
    │   └── zh/                   # Chinese analysis
    ├── vendor/                   # Third-party dependencies
    ├── stubs/                    # Module stubs
    ├── types/                    # Global type definitions
    ├── utils/                    # Top-level utility functions
    ├── scripts/                  # Build scripts
    └── package.json
    

    Core Execution Flow

    User Input
      ↓
    processUserInput()         # Parse /slash commands
      ↓
    query()                    # Main agent loop (query.ts)
      ├── fetchSystemPromptParts()    # Assemble system prompt
      ├── StreamingToolExecutor       # Parallel tool execution
      ├── autoCompact()               # Automatic context compression
      └── runTools()                  # Tool orchestration and scheduling
      ↓
    yield SDKMessage           # Stream results back to the consumer
    

    Tech Stack

    ComponentTechnology
    LanguageTypeScript 6.0+
    RuntimeBun (compiled into Node.js >= 18 bundle)
    Claude APIAnthropic SDK
    Terminal UIReact + Ink
    Code Bundlingesbuild
    Data ValidationZod
    Tool ProtocolMCP (Model Context Protocol)

    Main Module Descriptions

    Tool System (40+ tools)
    CategoryTools
    File OperationsFileReadTool, FileEditTool, FileWriteTool
    Code SearchGlobTool, GrepTool
    System ExecutionBashTool
    Web AccessWebFetchTool, WebSearchTool
    Task ManagementTaskCreateTool, TaskUpdateTool, TaskGetTool, TaskListTool
    Sub-agentsAgentTool
    Code EnvironmentsNotebookEditTool, REPLTool, LSPTool
    Git WorkflowEnterWorktreeTool, ExitWorktreeTool
    Configuration & PermissionsConfigTool, AskUserQuestionTool
    Memory & PlanningTodoWriteTool, EnterPlanModeTool, ExitPlanModeTool
    AutomationScheduleCronTool, RemoteTriggerTool, SleepTool
    MCP IntegrationMCPTool
    Slash Commands (~87)

    /commit /commit-push-pr /review /resume /session /memory /config /skills /help /voice /desktop /mcp /permissions /theme /vim /copy and more

    Permission System
    • Three modes: default (ask user) / bypass (auto-allow) / strict (auto-deny)
    • Tool-level fine-grained control
    • ML-based automated permission inference classifier
    • Persistent storage of permission rules
    Context Management
    • Automatic compression strategies (autoCompact): reactive compression, micro-compression, trimmed compression
    • Context collapsing (CONTEXT_COLLAPSE)
    • Token counting and estimation
    • Session transcript persistence
    Analysis Documents (docs/)
    DocumentContent
    01 - Telemetry and PrivacyDual-layer analysis pipeline (Anthropic + Datadog), with no opt-out switch
    02 - Hidden Features and Model CodenamesInternal codenames such as Capybara, Tengu, Fennec, Numbat
    03 - Undercover ModeAnthropic employees automatically entering undercover mode in public repositories
    04 - Remote Control and Emergency SwitchesHourly polling, 6+ killswitches, dangerous-change popups
    05 - Future RoadmapKAIROS autonomous agent, voice mode, 17 unreleased tools

    3. claw-code

    A clean-room Python rewrite of Claude Code (without including original source copies), focused on architectural mirroring and research. Built by @instructkr (Sigrid Jin), and became one of the fastest GitHub repositories in the world to reach 30K stars.

    Overall Architecture

    claw-code/
    ├── src/
    │   ├── __init__.py               # Package export interface
    │   ├── main.py                   # CLI entry (~200 lines)
    │   ├── query_engine.py           # Core query engine
    │   ├── runtime.py                # Runtime session management
    │   ├── models.py                 # Shared data classes
    │   ├── commands.py               # Command metadata and execution framework
    │   ├── tools.py                  # Tool metadata and execution framework
    │   ├── permissions.py            # Permission context management
    │   ├── context.py                # Ported context layer
    │   ├── setup.py                  # Workspace initialization
    │   ├── session_store.py          # Session persistence
    │   ├── transcript.py             # Session transcript storage
    │   ├── port_manifest.py          # Workspace manifest generation
    │   ├── execution_registry.py     # Execution registry
    │   ├── history.py                # History logs
    │   ├── parity_audit.py           # Parity audit against TypeScript source
    │   ├── remote_runtime.py         # Remote mode simulation
    │   ├── bootstrap_graph.py        # Bootstrap graph generation
    │   ├── command_graph.py          # Command graph partitioning
    │   ├── tool_pool.py              # Tool pool assembly
    │   │
    │   ├── reference_data/           # JSON snapshot data (drives command/tool metadata)
    │   │   ├── commands_snapshot.json
    │   │   └── tools_snapshot.json
    │   │
    │   ├── commands/                 # Command implementation subdirectory
    │   ├── tools/                    # Tool implementation subdirectory
    │   ├── services/                 # Business logic services
    │   ├── components/               # Terminal UI components (Python version)
    │   ├── state/                    # State management
    │   ├── types/                    # Type definitions
    │   ├── utils/                    # Utility functions
    │   ├── remote/                   # Remote mode
    │   ├── bridge/                   # Bridge modules
    │   ├── hooks/                    # Hook system
    │   ├── memdir/                   # Memory management
    │   ├── vim/                      # Vim mode
    │   ├── voice/                    # Voice mode
    │   └── plugins/                  # Plugin system
    │
    └── tests/                        # Validation tests
    

    Core Classes

    Class / ModuleResponsibility
    QueryEnginePortQuery engine handling message submission, streaming output, and session compression
    PortRuntimeRuntime manager responsible for routing, session startup, and turn-loop execution
    PortManifestWorkspace manifest that generates Markdown overviews
    ToolPermissionContextTool permission context (allow / deny / ask)
    WorkspaceSetupEnvironment detection and initialization reporting
    TranscriptStoreSession transcript storage with append, compaction, and replay support

    CLI Commands

    python3 -m src.main [COMMAND]
    
    # Overview
    summary              # Markdown workspace overview
    manifest             # Print manifest
    subsystems           # List Python modules
    
    # Routing and indexing
    commands             # List all commands
    tools                # List all tools
    route [PROMPT]       # Route prompt to corresponding command/tool
    
    # Execution
    bootstrap [PROMPT]   # Start runtime session
    turn-loop [PROMPT]   # Run turn loop (--max-turns)
    exec-command NAME    # Execute command
    exec-tool NAME       # Execute tool
    
    # Session management
    flush-transcript     # Persist session transcript
    load-session ID      # Load saved session
    
    # Remote mode
    remote-mode TARGET   # Simulate remote control
    ssh-mode TARGET      # Simulate SSH branch
    teleport-mode TARGET # Simulate Teleport branch
    
    # Audit and config
    parity-audit         # Compare consistency with TypeScript source
    setup-report         # Startup configuration report
    bootstrap-graph      # Bootstrap phase graph
    command-graph        # Command graph partition view
    tool-pool            # Tool pool assembly view
    

    Design Features

    • Snapshot-driven: command/tool metadata is loaded through JSON snapshots without requiring full logical implementations
    • Clean-room rewrite: does not include original TypeScript code; independently implemented
    • Parity audit: built-in parity_audit.py tracks gaps from the original implementation
    • Lightweight architecture: core framework implemented in 109 files, suitable for learning and extension

    4. nano-claude-code

    A minimal, fully-runnable Python reimplementation of Claude Code (~5,000 lines). Unlike claw-code (which focuses on architectural mapping), nano-claude-code is a real coding assistant that can be used immediately. It supports 20+ closed-source models and local open-source models, and has grown from a ~900-line prototype to a feature-rich v3.0 with multi-agent orchestration, persistent memory, and a skill system.

    Features

    FeatureDetails
    Multi-providerAnthropic · OpenAI · Gemini · Kimi · Qwen · Zhipu · DeepSeek · Ollama · LM Studio · Custom endpoint
    Interactive REPLreadline history, Tab-complete slash commands
    Agent loopStreaming API + automatic tool-use loop
    18 built-in toolsRead · Write · Edit · Bash · Glob · Grep · WebFetch · WebSearch · MemorySave · MemoryDelete · MemorySearch · MemoryList · Agent · SendMessage · CheckAgentResult · ListAgentTasks · ListAgentTypes · Skill · SkillList
    Diff viewGit-style red/green diff display for Edit and Write
    Context compressionAuto-compact long conversations to stay within model limits
    Persistent memoryDual-scope memory (user + project) with 4 types, AI search, staleness warnings
    Multi-agentSpawn typed sub-agents (coder/reviewer/researcher/…), git worktree isolation, background mode
    SkillsBuilt-in /commit · /review + custom markdown skills with argument substitution and fork/inline execution
    Plugin toolsRegister custom tools via tool_registry.py
    Permission systemauto / accept-all / manual modes
    17 slash commands/model · /config · /save · /cost · /memory · /skills · /agents · …
    Context injectionAuto-loads CLAUDE.md, git status, cwd, persistent memory
    Session persistenceSave / load conversations to ~/.nano_claude/sessions/
    Extended ThinkingToggle on/off (Claude models only)
    Cost trackingToken usage + estimated USD cost
    Non-interactive mode--print flag for scripting / CI

    Supported Models

    Closed-source (API): Claude (Anthropic), GPT / o-series (OpenAI), Gemini (Google), Kimi (Moonshot AI), Qwen (Alibaba DashScope), GLM (Zhipu), DeepSeek

    Open-source (local via Ollama): llama3.3/3.2, qwen2.5-coder, deepseek-r1, phi4, mistral, mixtral, gemma3, codellama, and any model on ollama list

    Self-hosted: vLLM, LM Studio, or any OpenAI-compatible endpoint via CUSTOM_BASE_URL

    Project Structure

    nano-claude-code/
    ├── nano_claude.py       # Entry point: REPL + slash commands + rendering   (~748 lines)
    ├── agent.py             # Agent loop: message format + tool dispatch        (~174 lines)
    ├── providers.py         # Multi-provider adapters + message conversion      (~507 lines)
    ├── tools.py             # Tool dispatch + auto-registration of all packages (~467 lines)
    ├── tool_registry.py     # Central tool registry + plugin entry point        (~98 lines)
    ├── context.py           # System prompt builder: CLAUDE.md + git + memory  (~135 lines)
    ├── compaction.py        # Context compression (auto-compact)                (~196 lines)
    ├── config.py            # Config load/save/defaults                         (~72 lines)
    ├── memory.py            # Backward-compat shim → memory/
    ├── skills.py            # Backward-compat shim → skill/
    ├── subagent.py          # Backward-compat shim → multi_agent/
    │
    ├── memory/              # Persistent memory package
    │   ├── store.py         # Save/load/delete/search memory entries
    │   ├── scan.py          # Index scanning, age/freshness helpers
    │   ├── context.py       # System-prompt injection + AI-ranked search
    │   ├── types.py         # MEMORY_TYPES definitions
    │   └── tools.py         # MemorySave · MemoryDelete · MemorySearch · MemoryList
    │
    ├── skill/               # Skill system package
    │   ├── loader.py        # SkillDef, file parsing, argument substitution
    │   ├── builtin.py       # Built-in skills: /commit, /review
    │   ├── executor.py      # Inline + fork execution modes
    │   └── tools.py         # Skill · SkillList
    │
    ├── multi_agent/         # Multi-agent orchestration package
    │   ├── subagent.py      # AgentDefinition, SubAgentTask, SubAgentManager, worktree helpers
    │   └── tools.py         # Agent · SendMessage · CheckAgentResult · ListAgentTasks · ListAgentTypes
    │
    ├── tests/               # 101 tests (monkeypatched, no real ~/.nano_claude touched)
    ├── docs/                # Docs and demo assets
    └── requirements.txt
    

    Quick start:

    pip install anthropic openai httpx rich
    export ANTHROPIC_API_KEY=sk-ant-...
    python nano_claude.py
    
    # Switch provider at startup
    python nano_claude.py --model gpt-4o
    python nano_claude.py --model ollama/qwen2.5-coder
    
    # Non-interactive / CI
    python nano_claude.py --print "Write a Python fibonacci function" --accept-all
    

    Memory — persistent across sessions, dual-scope (user ~/.nano_claude/memory/ and project .nano_claude/memory/):

    /memory               # list all memories with staleness info
    MemorySave(name="...", type="feedback", content="...", scope="user")
    MemorySearch(query="...", use_ai=True)
    

    Skills — reusable prompt templates, invoke from REPL:

    /commit               # built-in: review staged changes and create a git commit
    /review 123           # built-in: review PR #123
    /skills               # list all available skills with triggers and hints
    

    Multi-agent — spawn typed sub-agents with optional git worktree isolation:

    Agent(prompt="...", subagent_type="coder", isolation="worktree", wait=False)
    SendMessage(agent_name="my-agent", message="...")
    /agents               # show all active and finished sub-agent tasks
    

    Comparison of the Projects

    Dimensionoriginal-source-codeclaude-code-source-codeclaw-codenano-claude-code
    LanguageTypeScriptTypeScriptPythonPython
    Code Size~163,000 lines~163,000 lines + docs~5,000 lines~5,000 lines
    NatureRaw leaked source archiveDecompiled source archive + analysisClean-room architectural rewriteMinimal functional reimplementation
    Functional CompletenessComplete (100%)Complete (100%)Architectural framework (~20%)Core loop + memory + multi-agent + skills
    Core Loopquery.ts (785KB)query.ts (785KB)QueryEnginePort (~200 lines)agent.py (~174 lines)
    Tool System40+ fully implemented tools40+ fully implemented toolsSnapshot metadata + execution framework18 fully implemented tools + plugin registry
    Memory SystemYes (7-layer, complex)Yes (7-layer, complex)NoYes (dual-scope, 4 types, AI search)
    Multi-agentYes (full coordinator)Yes (full coordinator)NoYes (typed agents, worktree isolation)
    SkillsYes (~87 commands)Yes (~87 commands)Snapshot metadata onlyYes (built-in + custom markdown skills)
    Multi-providerNo (Anthropic only)No (Anthropic only)NoYes (10+ providers)
    Immediately RunnableNoNoLimited (CLI metadata only)Yes
    Main Use CaseRaw reference snapshotDeep study of full implementation detailsArchitectural understanding and porting researchLightweight full-featured coding assistant