claude-code-working

April 1, 2026 · View on GitHub

A working reverse-engineered Claude Code CLI codebase rebuilt from source analysis to reproduce the original terminal workflow, architecture, and engineering behavior.

Start with the architecture docs

Current focus:

  • The codebase runs and passes baseline type checks.
  • The monorepo and engineering scaffolding are in place.
    • Biome formatting is intentionally conservative to avoid massive diff churn.
    • The build pipeline produces runnable Node and Bun output.
  • The documentation set is available in English.
  • More tests can still be added to improve confidence and stability.

Quick start

Environmental requirements

You must have the latest version of bun, otherwise there will be a bunch of weird bugs!!! bun upgrade!!!

  • Bun >= 1.3.11
  • Conventional way to configure CC, each major provider has its own configuration method

Installation

bun install

Run

# Development mode, if you see the version number 888, it means it is correct
bun run dev

# Build
bun run build

The build uses code splitting multi-file packaging (build.ts), and the product is output to the dist/ directory (entry dist/cli.js + about 450 chunk files).

The built version can be started by both bun and node. You can start it directly by publishing it to a private source.

If you encounter a bug, please raise an issue directly and we will resolve it first.

Capability list

✅ = implemented ⚠️ = partially implemented / conditionally enabled ❌ = stub / removed / feature flag closed

Core System

CapabilitiesStatusDescription
REPL interactive interface (Ink terminal rendering)Home screen 5000+ lines, complete interaction
API Communication — Anthropic DirectSupport API Key + OAuth
API Communication — AWS BedrockSupports credential refresh, Bearer Token
API Communication — Google VertexSupport GCP credential refresh
API Communication — Azure FoundrySupports API Key + Azure AD
Streaming dialogue and tool call loop (query.ts)1700+ lines, including automatic compression and token tracking
Conversation Engine (QueryEngine.ts)1300+ lines to manage conversation state and attribution
Context build (git status / CLAUDE.md / memory)context.ts complete implementation
Permission system (plan/auto/manual mode)6300+ lines, including YOLO classifier, path verification, rule matching
Hook system (pre/post tool use)Support settings.json configuration
Session Resume (/resume)Standalone ResumeConversation screen
Doctor Diagnosis (/doctor)Version, API, plugin, sandbox check
Automatic compression (compaction)auto-compact / micro-compact / API compact

Tools — always available

ToolsStatusDescription
BashToolShell execution, sandbox, permission check
FileReadToolFile / PDF / Picture / Notebook Reading
FileEditToolString replacement editing + diff tracking
FileWriteToolFile creation/overwriting + diff generation
NotebookEditToolJupyter Notebook cell editing
AgentToolSubagent fork (fork/async/background/remote)
WebFetchToolURL Fetching → Markdown → AI Summary
WebSearchToolWeb search + domain name filtering
AskUserQuestionToolMultiple question interactive prompts + preview
SendMessageToolMessage sending (peers / teammates / mailbox)
SkillToolSlash command / Skill call
EnterPlanModeToolEnter planning mode
ExitPlanModeTool (V2)Exit plan mode
TodoWriteToolTodo List v1
BriefToolShort message + attachment sending
TaskOutputToolBackground task output reading
TaskStopToolBackground task stop
ListMcpResourcesTool⚠️MCP resource list (filtered by specialTools, added under specific conditions)
ReadMcpResourceTool⚠️MCP resource reading (same as above)
SyntheticOutputTool⚠️Created only in non-interactive sessions (SDK/pipe mode)
CronCreateToolScheduled task creation (AGENT_TRIGGERS gate has been removed)
CronDeleteToolScheduled task deletion
CronListToolScheduled task list
EnterWorktreeToolEnter Git Worktree (isWorktreeModeEnabled() is hardcoded to true)
ExitWorktreeToolExit Git Worktree

Tools — Conditional Enablement

ToolsStatusEnablement Conditions
GlobToolEnabled when bfs/ugrep is not embedded (enabled by default)
GrepToolSame as above
TaskCreateTool⚠️When isTodoV2Enabled() is true
TaskGetTool⚠️Same as above
TaskUpdateTool⚠️Same as above
TaskListTool⚠️Same as above
TeamCreateTool⚠️isAgentSwarmsEnabled()
TeamDeleteTool⚠️Same as above
ToolSearchTool⚠️isToolSearchEnabledOptimistic()
PowerShellTool⚠️Windows Platform Detection
LSPTool⚠️ENABLE_LSP_TOOL environment variable
ConfigToolUSER_TYPE === 'ant' (always false)

Tools — Feature Flag Off (all disabled)

ToolsFeature Flag
SleepToolPROACTIVE / KAIROS
RemoteTriggerToolAGENT_TRIGGERS_REMOTE
MonitorToolMONITOR_TOOL
SendUserFileToolKAIROS
OverflowTestToolOVERFLOW_TEST_TOOL
TerminalCaptureToolTERMINAL_PANEL
WebBrowserToolWEB_BROWSER_TOOL
SnipToolHISTORY_SNIP
WorkflowToolWORKFLOW_SCRIPTS
PushNotificationToolKAIROS / KAIROS_PUSH_NOTIFICATION
SubscribePRToolKAIROS_GITHUB_WEBHOOKS
ListPeersToolUDS_INBOX
CtxInspectToolCONTEXT_COLLAPSE

Tools — Stub / Not available

ToolsInstructions
TungstenToolANT-ONLY stub
REPLToolANT-ONLY,isEnabled: () => false
SuggestBackgroundPRToolANT-ONLY,isEnabled: () => false
VerifyPlanExecutionToolRequires CLAUDE_CODE_VERIFY_PLAN=true environment variable and is stub
ReviewArtifactToolstub, not registered to tools.ts
DiscoverSkillsToolstub, not registered to tools.ts

Slash command — available

CommandStatusDescription
/add-dirAdd directory
/advisorAdvisor Configuration
/agentsAgent list/management
/branchBranch management
/btwQuick Notes
/chromeChrome integration
/clearClear screen
/colorAgent color
/compactCompact conversation
/config (/settings)Configuration management
/contextContext information
/copyCopy last message
/costSession cost
/desktopClaude Desktop Integration
/diffshow diff
/doctorHealth Check
/effortSet effort level
/exitExit
/exportExport conversation
/extra-usageExtra usage information
/fastSwitch fast mode
/feedbackFeedback
/loopTimed loop execution (bundled skill, can be turned off via CLAUDE_CODE_DISABLE_CRON)
/heapdumpHeap dump (debug)
/helpHelp
/hooksHook Management
/ideIDE connection
/initInitialization project
/install-github-appInstall GitHub App
/install-slack-appInstall Slack App
/keybindingsShortcut key management
/login / /logoutLogin / Logout
/mcpMCP Service Management
/memoryMemory / CLAUDE.md Management
/mobileMobile QR code
/modelModel selection
/output-styleOutput style
/passesRecommendation code
/permissionsPermission management
/planPlan mode
/pluginPlug-in management
/pr-commentsPR comments
/privacy-settingsPrivacy Settings
/rate-limit-optionsRate limit options
/release-notesUpdate log
/reload-pluginsReload plugins
/remote-envRemote environment configuration
/renameRename session
/resumeResume session
/reviewCode review (local)
/ultrareviewCloud review
/rewindRewind conversation
/sandbox-toggleToggle sandbox
/security-reviewSecurity review
/sessionSession information
/skillsSkill Management
/statsSession statistics
/statusStatus information
/statuslineStatus bar UI
/stickersStickers
/tasksTask management
/themeTerminal theme
/think-backYear in Review
/upgradeUpgrade CLI
/usageUsage information
/insightsUsage analysis report
/vimVim mode

Slash Command — Feature Flag Off

CommandFeature Flag
/voiceVOICE_MODE
/proactivePROACTIVE / KAIROS
/briefKAIROS / KAIROS_BRIEF
/assistantKAIROS
/remote-control (alias rc)BRIDGE_MODE
/remote-control-serverDAEMON + BRIDGE_MODE
/force-snipHISTORY_SNIP
/workflowsWORKFLOW_SCRIPTS
/web-setupCCR_REMOTE_SETUP
/subscribe-prKAIROS_GITHUB_WEBHOOKS
/ultraplanULTRAPLAN
/torchTORCH
/peersUDS_INBOX
/forkFORK_SUBAGENT
/buddyBUDDY

Slash command — ANT-ONLY (not available)

/files /tag /backfill-sessions /break-cache /bughunter /commit /commit-push-pr /ctx_viz /good-claude /issue /init-verifiers /mock-limits /bridge-kick /version /reset-limits /onboarding /share /summary /teleport /ant-trace /perf-issue /env /oauth-refresh /debug-tool-call /agents-platform /autofix-pr

CLI subcommands

SubcommandStatusDescription
claude (default)Main REPL / interactive / print mode
claude mcp serve/add/remove/list/get/...MCP service management (7 subcommands)
claude auth login/status/logoutAuthentication management
claude plugin validate/list/install/...Plug-in management (7 subcommands)
claude setup-tokenLong-term Token configuration
claude agentsAgent list
claude doctorHealth Check
claude update / upgradeAutomatic update
claude install [target]Native installation
claude serverDIRECT_CONNECT flag
claude ssh <host>SSH_REMOTE flag
claude open <cc-url>DIRECT_CONNECT flag
claude auto-modeTRANSCRIPT_CLASSIFIER flag
claude remote-controlBRIDGE_MODE + DAEMON flag
claude assistantKAIROS flag
claude up/rollback/log/error/export/task/completionANT-ONLY

Service layer

ServiceStatusDescription
API Client (services/api/)3400+ lines, 4 providers
MCP (services/mcp/)34 files, 12000+ lines
OAuth (services/oauth/)Complete OAuth process
Plugins (services/plugins/)Complete infrastructure, no built-in plugins
LSP (services/lsp/)⚠️Implementation exists, closed by default
Compression (services/compact/)auto / micro / API compression
Hook system (services/tools/toolHooks.ts)pre/post tool use hooks
Session Memory (services/SessionMemory/)Session Memory Management
Memory extraction (services/extractMemories/)Automatic memory extraction
Skill Search (services/skillSearch/)Local/remote skill search
Policy Limits (services/policyLimits/)Policy Limit Enforcement
Analysis / GrowthBook / Sentry⚠️The frame exists, the actual sink is empty
Voice (services/voice.ts)VOICE_MODE flag off

Internal packages (packages/)

PackageStatusDescription
color-diff-napi1006 lines of complete TypeScript implementation (syntax highlighting diff)
audio-capture-napi151 lines of complete implementation (cross-platform audio recording, using SoX/arecord)
image-processor-napi125 lines of complete implementation (macOS clipboard image reading, using osascript + sharp)
modifiers-napi67 lines of complete implementation (macOS modifier key detection, bun:ffi + CoreGraphics)
url-handler-napistub, waitForUrlEvent() returns null
@ant/claude-for-chrome-mcpstub, createServer() returns null
@ant/computer-use-mcp⚠️Type-safe stub (line 265, complete type definition but function returns null)
@ant/computer-use-input183 lines of complete implementation (macOS keyboard and mouse simulation, AppleScript/JXA/CGEvent)
@ant/computer-use-swift388 lines of complete implementation (macOS display/application management/screenshot, JXA/screencapture)

Feature Flags (31, all return false)

ABLATION_BASELINE AGENT_MEMORY_SNAPSHOT BG_SESSIONS BRIDGE_MODE BUDDY CCR_MIRROR CCR_REMOTE_SETUP CHICAGO_MCP COORDINATOR_MODE DAEMON DIRECT_CONNECT EXPERIMENTAL_SKILL_SEARCH FORK_SUBAGENT HARD_FAIL HISTORY_SNIP KAIROS KAIROS_BRIEF KAIROS_CHANNELS KAIROS_GITHUB_WEBHOOKS LODESTONE MCP_SKILLS PROACTIVE SSH_REMOTE TORCH TRANSCRIPT_CLASSIFIER UDS_INBOX ULTRAPLAN UPLOAD_USER_SETTINGS VOICE_MODE WEB_BROWSER_TOOL WORKFLOW_SCRIPTS

Project structure

claude-code/
├── src/
│   ├── entrypoints/
│ │ ├── cli.tsx # Entry file (including MACRO/feature polyfill)
│ │ └── sdk/ # SDK submodule stub
│ ├── main.tsx # Main CLI logic (Commander definition)
│   └── types/
│ ├── global.d.ts # Global variable/macro declaration
│ └── internal-modules.d.ts # Internal npm package type declaration
├── packages/ # Monorepo workspace package
│ ├── color-diff-napi/ # Complete implementation (terminal color diff)
│ ├── modifiers-napi/ # stub (macOS modifier key detection)
│   ├── audio-capture-napi/  # stub
│   ├── image-processor-napi/# stub
│   ├── url-handler-napi/    # stub
│ └── @ant/ # Anthropic internal package stub
│       ├── claude-for-chrome-mcp/
│       ├── computer-use-mcp/
│       ├── computer-use-input/
│       └── computer-use-swift/
├── scripts/ # Automatic stub generation script
├── build.ts # Build script (Bun.build + code splitting + Node.js compatible post-processing)
├── dist/ # Build output (entry cli.js + ~450 chunk files)
└── package.json # Bun workspaces monorepo configuration

Technical description

Runtime Polyfill

The necessary polyfill is injected at the top of the entry file src/entrypoints/cli.tsx:

  • feature() — return false for all feature flags, skip unimplemented branches
  • globalThis.MACRO — emulates build-time macro injection (VERSION, etc.)

Monorepo

The project uses Bun workspaces to manage internal packages. The stubs that were originally placed manually under node_modules/ have been uniformly moved into packages/ and parsed through workspace:*.

Feature Flags detailed explanation

The original Claude Code injects feature flags during build through feature() of bun:bundle, and the grayscale release is controlled by A/B experiment platforms such as GrowthBook. In this project, feature() is polyfilled to always return false, so the following 30 flags are all turned off.

Autonomous Agent

FlagPurpose
KAIROSAssistant mode - long-running autonomous Agent (including brief, push notification, file sending)
KAIROS_BRIEFKairos Brief — Send briefing summary to user
KAIROS_CHANNELSKairos Channels — Multi-Channel Communication
KAIROS_GITHUB_WEBHOOKSGitHub Webhook subscription — PR events are pushed to Agent in real time
PROACTIVEActive mode - Agent actively performs tasks, including SleepTool scheduled wake-up
COORDINATOR_MODECoordinator mode - multi-Agent orchestration and scheduling
BUDDYBuddy pairing programming function
FORK_SUBAGENTFork subagent — fork an independent subagent from the current session

Remote/Distributed

FlagPurpose
BRIDGE_MODERemote control bridge — allows external clients to remotely control Claude Code
DAEMONDaemon process — background resident service, supports worker and supervisor
BG_SESSIONSBackground session — ps/logs/attach/kill/--bg and other background process management
SSH_REMOTESSH remote — claude ssh <host> connect to remote host
DIRECT_CONNECTDirect connection mode - cc:// URL protocol, server command, open command
CCR_REMOTE_SETUPWeb remote configuration - configure through browser Claude Code
CCR_MIRRORClaude Code Runtime Mirroring - Session State Sync/Replication

Communication

FlagPurpose
UDS_INBOXUnix Domain Socket Inbox - Local communication between Agents (/peers)

Enhancement Tools

FlagPurpose
CHICAGO_MCPComputer Use MCP — Computer operation (screenshot, mouse and keyboard control)
WEB_BROWSER_TOOLWeb browser tool - embedded browser interaction in the terminal
VOICE_MODEVoice mode - voice input and output, microphone push-to-talk
WORKFLOW_SCRIPTSWorkflow scripts — user-defined automated workflows
MCP_SKILLSMCP-based Skill loading mechanism

Dialogue management

FlagPurpose
HISTORY_SNIPHistory clipping — manually clip snippets in conversation history (/force-snip)
ULTRAPLANUltra Plan — Large-scale planning capabilities for remote Agent collaboration
AGENT_MEMORY_SNAPSHOTMemory snapshot function when Agent is running

Infrastructure/Experiments

FlagPurpose
ABLATION_BASELINEScience Experiment — Baseline ablation test for A/B experiment control group
HARD_FAILHard failure mode - interrupt directly instead of downgrading when an error occurs
TRANSCRIPT_CLASSIFIERConversation classifier — auto-mode command, automatically analyzes and classifies conversation records
UPLOAD_USER_SETTINGSSetting synchronization upload — synchronize local configuration to the cloud
LODESTONEDeep link protocol handler - jump from external application to the location specified by Claude Code
EXPERIMENTAL_SKILL_SEARCHExperimental Skill Search Index
TORCHTorch function (specific use unknown, may be some kind of highlighting/tracking mechanism)

License

This project is for study and research purposes only. All rights to Claude Code belong to Anthropic.