The world needs an open-source Claude Code.It will become the foundational infrastructure of AI in the future, running on every PC.
π visit website | π δΈζζζ‘£
A reverse-engineered restoration based on @anthropic-ai/claude-code v2.1.14.
For educational and research purposes only.
This is an educational project for studying and learning CLI tool architecture design. This is NOT the official Claude Code source code, but a reimplementation based on public APIs and type definitions.
For the official Claude Code, please install the official version:
npm install -g @anthropic-ai/claude-code# Install dependencies
npm install
# Build the project
npm run build
# Link globally (optional)
npm link# Interactive mode
npm run dev
# Or run after building
node dist/cli.js
# With initial prompt
node dist/cli.js "Hello, please analyze this project"
# Print mode
node dist/cli.js -p "Explain this code"
# Specify model
node dist/cli.js -m opus "Complex task"
# Resume last session
node dist/cli.js --resumeSet up your API key:
Linux/macOS:
export ANTHROPIC_API_KEY=your-api-key
# or
export CLAUDE_API_KEY=your-api-keyWindows Command Prompt:
set ANTHROPIC_API_KEY=your-api-key
# or
set CLAUDE_API_KEY=your-api-keyWindows PowerShell:
$env:ANTHROPIC_API_KEY="your-api-key"
# or
$env:CLAUDE_API_KEY="your-api-key"| Variable | Description | Default |
|---|---|---|
ANTHROPIC_API_KEY |
API Key | - |
BASH_MAX_OUTPUT_LENGTH |
Max Bash output length | 30000 |
CLAUDE_CODE_MAX_OUTPUT_TOKENS |
Max output tokens | 32000 |
CLAUDE_TELEMETRY_ENABLED |
Enable telemetry | true |
src/
βββ index.ts # Main export barrel
βββ cli.ts # CLI entry point (Commander.js)
βββ core/ # Core engine
β βββ client.ts # Anthropic API client (streaming, retry, cost)
β βββ session.ts # Session state management
β βββ loop.ts # Conversation orchestrator
β βββ context.ts # Context management & summarization
βββ tools/ # 25+ tools
β βββ bash.ts # Bash execution (sandbox support)
β βββ file.ts # Read/Write/Edit/MultiEdit
β βββ search.ts # Glob/Grep search
β βββ web.ts # WebFetch/WebSearch
β βββ todo.ts # TodoWrite task management
β βββ agent.ts # Task/TaskOutput sub-agents
β βββ notebook.ts # Jupyter Notebook editing
β βββ planmode.ts # EnterPlanMode/ExitPlanMode
β βββ mcp.ts # MCP protocol (ListMcpResources/ReadMcpResource)
β βββ ask.ts # AskUserQuestion
β βββ tmux.ts # Tmux multi-terminal (Linux/macOS)
β βββ skill.ts # Skill system
β βββ lsp.ts # LSP integration (diagnostics, hover, references)
β βββ sandbox.ts # Bubblewrap sandbox (Linux)
βββ ui/ # Ink/React UI framework
β βββ App.tsx # Main app component
β βββ components/ # Reusable UI components
β βββ Spinner.tsx
β βββ Message.tsx
β βββ ToolCall.tsx
β βββ TodoList.tsx
β βββ PermissionPrompt.tsx
β βββ StatusBar.tsx
βββ agents/ # Specialized sub-agents
β βββ explore.ts # Codebase exploration agent
β βββ plan.ts # Implementation planning agent
β βββ guide.ts # Claude Code documentation agent
βββ auth/ # Authentication
β βββ oauth.ts # OAuth flow
β βββ api-key.ts # API key management
βββ session/ # Session persistence
β βββ manager.ts # Session lifecycle
β βββ storage.ts # Disk persistence (~/.claude/sessions/)
β βββ export.ts # Markdown export
βββ context/ # Context management
β βββ estimator.ts # Token estimation
β βββ compressor.ts # Message summarization
β βββ budget.ts # Token budget tracking
βββ parser/ # Code parsing
β βββ tree-sitter.ts # Tree-sitter WASM integration
β βββ languages/ # Language-specific parsers
βββ search/ # Search utilities
β βββ ripgrep.ts # Vendored ripgrep binary
β βββ glob.ts # File pattern matching
βββ hooks/ # Hook system
β βββ registry.ts # Hook registration
β βββ executor.ts # Hook execution
βββ mcp/ # MCP protocol
β βββ client.ts # MCP client
β βββ server.ts # MCP server connection
β βββ registry.ts # MCP server registry
βββ permissions/ # Permission system
β βββ manager.ts # Permission requests
β βββ modes.ts # Permission modes (accept/bypass/plan)
βββ config/ # Configuration
β βββ loader.ts # Load from ~/.claude/settings.json
β βββ env.ts # Environment variable handling
βββ telemetry/ # Telemetry
β βββ collector.ts # Event collection
β βββ analytics.ts # Local analytics (not uploaded)
βββ skills/ # Skills system
β βββ loader.ts # Load from ~/.claude/skills/
β βββ registry.ts # Skill registration
βββ commands/ # Slash commands
β βββ registry.ts # Command registration
β βββ builtin/ # Built-in commands (/help, /clear, etc.)
βββ plugins/ # Plugin system
β βββ manager.ts # Plugin lifecycle
β βββ loader.ts # Plugin discovery
βββ models/ # Model configuration
β βββ registry.ts # Model definitions
β βββ pricing.ts # Token pricing
βββ network/ # Network utilities
β βββ proxy.ts # Proxy support
β βββ retry.ts # Retry logic
βββ streaming/ # Streaming I/O
β βββ parser.ts # JSON message streaming
β βββ writer.ts # Stream writing
βββ security/ # Security features
β βββ validator.ts # Input validation
β βββ sanitizer.ts # Output sanitization
βββ types/ # TypeScript definitions
β βββ tools.ts # Tool types
β βββ session.ts # Session types
β βββ config.ts # Configuration types
βββ utils/ # Utility functions
βββ fs.ts # File system helpers
βββ path.ts # Path utilities
βββ time.ts # Time formatting
| Tool | Status | Description |
|---|---|---|
| File Operations | ||
| Read | β Complete | File reading with image/PDF/Notebook support + external modification detection |
| Write | β Complete | File writing with overwrite protection |
| Edit | β Complete | File editing (string replacement) |
| MultiEdit | β Complete | Batch file editing (atomic operations) |
| Search & Discovery | ||
| Glob | β Complete | File pattern matching |
| Grep | β Complete | Content search (ripgrep-based) with official output format |
| Execution | ||
| Bash | β Complete | Command execution with background & sandbox support |
| TaskOutput | β Complete | Get background command/agent output (unified UUID/task_id format) |
| KillShell | β Complete | Terminate background processes |
| Web Access | ||
| WebFetch | β Complete | Web page fetching with caching |
| WebSearch | Web search (requires API configuration) | |
| Task Management | ||
| TodoWrite | β Complete | Task management with auto-reminder system |
| Task | β Complete | Sub-agents (explore, plan, guide, etc.) |
| Planning | ||
| EnterPlanMode | β Complete | Enter plan mode with permission system |
| ExitPlanMode | β Complete | Exit plan mode |
| Interaction | ||
| AskUserQuestion | β Complete | Ask user questions (multiSelect, options, validation) |
| Code Tools | ||
| NotebookEdit | β Complete | Jupyter Notebook cell editing (replace/insert/delete) |
| LSP* | β Complete | Language Server Protocol integration (diagnostics, hover, references) |
| Integration | ||
| ListMcpResources | β Complete | List MCP resources |
| ReadMcpResource | β Complete | Read MCP resource |
| Skill | β Complete | Skill system with args parameter and permission checks |
| Terminal | ||
| Tmux | β Complete | Multi-terminal session management (Linux/macOS) |
*LSP tools available when language servers are configured
Supports both API Key and OAuth authentication:
import { initAuth, startOAuthLogin, setApiKey } from './auth';
// Using API Key
setApiKey('your-api-key', true); // true for persistence
// Or using OAuth login
await startOAuthLogin({
clientId: 'your-client-id',
scope: ['read', 'write'],
});Automatic conversation saving and restoration:
import { SessionManager, listSessions, loadSession } from './session';
const manager = new SessionManager({ autoSave: true });
// Start new session or resume
const session = manager.start({
model: 'claude-sonnet-4-20250514',
resume: true, // Try to resume last session
});
// List all sessions
const sessions = listSessions({ limit: 10 });
// Export as Markdown
const markdown = manager.export();Intelligent context compression and summarization:
import { ContextManager, estimateTokens } from './context';
const context = new ContextManager({
maxTokens: 180000,
summarizeThreshold: 0.7, // Start compressing at 70%
keepRecentMessages: 10,
});
// Add conversation turn
context.addTurn(userMessage, assistantMessage);
// Get optimized messages
const messages = context.getMessages();
// Manual compaction
context.compact();Multi-language code analysis support:
import { parseFile, parseCode, detectLanguage } from './parser';
// Detect language
const lang = detectLanguage('app.tsx'); // 'typescript'
// Parse file
const parsed = parseFile('/path/to/file.ts');
console.log(parsed.classes); // Class definitions
console.log(parsed.functions); // Function definitions
console.log(parsed.imports); // Import statements
console.log(parsed.exports); // Export statementsSupported languages: JavaScript, TypeScript, Python, Go, Rust, Java, C/C++, Ruby, PHP, Swift, Kotlin, Scala, etc.
Built-in ripgrep support, no system installation required:
import { search, listFiles, getRipgrepVersion } from './search/ripgrep';
// Search content
const results = await search({
pattern: 'function.*async',
glob: '*.ts',
ignoreCase: true,
});
// List files
const files = await listFiles({
glob: '**/*.tsx',
hidden: false,
});Local usage statistics (data is not uploaded):
import { telemetry, getTelemetryStats } from './telemetry';
// Record session
telemetry.startSession('claude-sonnet-4-20250514');
telemetry.recordMessage('user', 100);
telemetry.recordToolCall('Bash', true, 50);
telemetry.endSession();
// Get statistics
const stats = getTelemetryStats();
console.log(stats.totalSessions);
console.log(stats.totalTokens);Complete terminal UI component system:
Spinner- Loading animationsToolCall- Tool call displayMessage- Message displayInput- Input boxHeader- Header barTodoList- Task listPermissionPrompt- Permission confirmationStatusBar- Status bar
Linux only: If bubblewrap is installed, Bash commands will execute in a sandbox for enhanced security:
# Ubuntu/Debian
sudo apt install bubblewrap
# Arch Linux
sudo pacman -S bubblewrapNote for Windows/macOS users:
- Bubblewrap sandbox is only available on Linux
- Windows and macOS users can use WSL (Windows Subsystem for Linux) to enable sandbox support
- Alternatively, commands will run without sandboxing (use with caution)
Sandbox can be disabled with dangerouslyDisableSandbox: true parameter.
Execute custom scripts before/after tool calls:
// .claude/settings.json
{
"hooks": [
{
"event": "PreToolUse",
"matcher": "Bash",
"command": "/path/to/script.sh", // Linux/macOS: .sh, Windows: .bat or .ps1
"blocking": true
}
]
}Supported events:
PreToolUse- Before tool callPostToolUse- After tool callPrePromptSubmit- Before submissionPostPromptSubmit- After submissionNotification- NotificationsStop- Stop
Connect to MCP (Model Context Protocol) servers:
// .claude/settings.json
{
"mcpServers": {
"filesystem": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path"] // Use absolute path
}
}
}Path examples:
- Linux/macOS:
"/home/user/projects"or"/Users/user/projects" - Windows:
"C:\\Users\\user\\projects"(use double backslashes in JSON)
Linux/macOS only: Manage multiple terminal sessions:
// Create session
{ action: "new", session_name: "dev-server" }
// Send command
{ action: "send", session_name: "dev-server", command: "npm run dev" }
// Capture output
{ action: "capture", session_name: "dev-server" }Note for Windows users:
- Tmux is not available natively on Windows
- Use WSL (Windows Subsystem for Linux) to access Tmux
- Alternative: Use Windows Terminal with multiple tabs/panes
Load from the following directories:
- Linux/macOS:
~/.claude/skills/and.claude/commands/ - Windows:
%USERPROFILE%\.claude\skills\and.claude\commands\
Features:
- Skills: Reusable prompt templates
- Slash Commands: Custom command extensions
- Exponential backoff retry (up to 4 times)
- Automatic cost calculation
- Token usage statistics
- Multi-model pricing support
/help- Show help/clear- Clear conversation history/save- Save session/stats- Show statistics/tools- List tools/model- Switch model/resume- Resume session/compact- Compress context/exit- Exit
This project includes comprehensive testing:
# Run all tests
npm test
# Run with UI
npm run test:ui
# Run specific test suites
npm run test:unit # Unit tests
npm run test:integration # Integration tests
npm run test:e2e # End-to-end tests
# Run with coverage
npm run test:coverage
# Watch mode
npm run test:watch- Unit Tests (
src/**/*.test.ts) - Individual component tests - Integration Tests (
tests/integration/) - Multi-component interaction tests - E2E Tests (
tests/e2e/) - Full CLI workflow tests - Tool Tests (
tests/tools/) - Individual tool functionality tests
Core Features:
- β
Bash History Autocomplete β - Type partial command + Tab to complete from bash/zsh history
- Reads system history files (~/.bash_history, ~/.zsh_history)
- Dual-source integration (UI session + system history)
- Smart priority ranking (recent UI commands prioritized)
- Maximum 15 suggestions (aligned with official vx0=15)
- Performance optimized with 60s caching and deduplication
UI Improvements:
- β Plugin Search - Real-time search in installed plugins list (type to filter by name/description)
- β Git SHA Pinning - Pin plugins to specific git commit SHAs for exact version control
Critical Fixes:
- β Context Window Blocking - Fixed regression: blocking threshold increased from 65% to 98%
- β Memory Leaks - Fixed parallel sub-agent crashes and shell stream resource cleanup
- β @ Symbol in Bash - Fixed incorrect file autocomplete trigger in bash mode
- β Slash Command Selection - Fixed autocomplete selecting wrong command (e.g., /context vs /compact)
- β /feedback URL Fix - Long descriptions no longer generate invalid GitHub URLs (6000 char limit)
Implementation:
- π New:
src/tools/bash-history.ts(320 lines) - System history file reader - π Enhanced:
src/ui/autocomplete/bash-history.ts- UI integration with dual-source logic - π§ͺ Testing:
tests/bash-history.test.ts(180 lines) - Complete test coverage
- β auto:N syntax - Configure MCP tool search auto-enable threshold (context window percentage 0-100)
- β plansDirectory setting - Customize where plan files are stored
- β External editor (Ctrl+G) - Support in AskUserQuestion "Other" input field
- β Session URL attribution - Add session URL to commits and PRs from web sessions
- β ${CLAUDE_SESSION_ID} - String substitution support for skills to access current session ID
- β PreToolUse additionalContext - Hooks can return additional context to the model
- β Parallel tool call fix - Fixed orphan tool_result blocks API error in long sessions
- β MCP reconnection fix - Fixed hanging when cached connection promise never resolves
- β Kitty Ctrl+Z fix - Fixed suspend not working in Kitty keyboard protocol terminals
- β Tool-level error handling & retry - Exponential backoff for transient failures
- β LSP URI handling - Enhanced URI parsing and location validation
- β Grep output format - 100% match with official implementation
- β OAuth authentication - Streamlined auth flow and system prompt formatting
- β AskUserQuestion - Full parity with official (multiSelect, validation)
- β Shell ID format - Unified UUID/task_id format across all background tasks
- β Tool result persistence - Automatic saving of tool execution results
- β Permission dialog flow - Complete permission request workflow
- β TodoWrite auto-reminders - Official reminder system for task tracking
- β Plan mode permissions - Permission checks integrated into planning tools
- β File modification detection - Alerts when files are modified externally
- β Skill args parameter - Full skill argument passing and permission system
- β NotebookEdit insert mode - Fixed cell insertion position logic
| Component | Status | Notes |
|---|---|---|
| Core Architecture | β 100% | Three-layer design (Entry β Engine β Tools) |
| CLI Interface | β 100% | All commands & flags implemented |
| Tool System | β 100% | 25+ tools with full feature parity |
| API Client | β 100% | Streaming, retry, cost calculation |
| Permission System | β 100% | Accept/bypass/plan modes |
| Error Handling | β 100% | Tool-level retry with exponential backoff |
| File Operations | β 100% | External modification detection |
| Background Tasks | β 100% | Unified UUID/task_id format |
| Output Formatting | β 100% | Grep, LSP, and all tools match official |
| Sandbox | β 100% | Bubblewrap isolation (Linux) |
| Hooks | β 100% | Complete event system |
| MCP | β 100% | Full protocol support |
| UI Components | β 100% | Ink/React framework with auto-scroll |
| Skills/Commands | β 100% | Args, permissions, discovery |
| Authentication | β 100% | API Key + OAuth |
| Session Management | β 100% | Persistence, recovery, export |
| Context Management | β 100% | Auto-summarization |
| Code Parser | β 100% | Tree-sitter WASM |
| Telemetry | β 100% | Local analytics |
Overall Accuracy: ~100% (based on public API and behavioral analysis)
# Development mode (using tsx)
npm run dev
# Build
npm run build
# Type checking
npx tsc --noEmit- TypeScript - Type safety
- Anthropic SDK - API calls
- Ink + React - Terminal UI
- Commander - CLI framework
- Chalk - Terminal colors
- Glob - File matching
- Zod - Schema validation
- Discord: Join our Discord
- X (Twitter): @wangbingjie1989
This project is for educational purposes only. Original Claude Code is owned by Anthropic PBC.
This project is a reverse engineering study of obfuscated code and does not represent the official implementation.