← Back

Inside Claude Code

Architecture breakdown from the leaked source

March 31, 2026AIArchitectureOpen Source

512K lines of TypeScript. 144 React components rendered via Ink in a terminal. 43 tools behind permission gates. 86 slash commands. 16 bundled skills. 85 hooks. This is what's inside.

STACK
RuntimeBun
UIReact + Ink (terminal renderer) — 144 components in src/components/
CLICommander.js with preAction hooks for initialization
Statesrc/state/ — AppStateStore.ts with selectors, change handlers, no external library
Entrysrc/main.tsx → Commander parse → preAction init → React/Ink REPL
Enginesrc/QueryEngine.ts — async generator, drives the agentic loop
Bridgesrc/bridge/ — 32 files for IDE communication (VS Code, JetBrains). JWT auth, session management, bidirectional messaging
STARTUP SEQUENCE

Startup is a race against the 135ms import window. Three prefetches fire before any module loads:

startMdmRawRead()Spawns subprocess for managed device settings — completes in ~80ms
startKeychainPrefetch()macOS keychain read — 50-180ms, already done by the time CLI parses
captureEarlyInput()Buffers keystrokes during boot so nothing is lost
init()Loads settings, establishes trust dialog, loads remote managed settings
DeferredAfter first render: initUser(), getUserContext(), getRelevantTips(), countFilesRoundedRg() (3s timeout), prefetchOfficialMcpUrls(), refreshModelCapabilities()
CONTEXT ASSEMBLY

System prompt is layered. Each function uses memoize() — computed once, cached for the session. Calling setSystemPromptInjection() clears both caches:

Base promptBehavior rules, constraints, output format, tool descriptions
getSystemContext()git status --short (truncated at 2000 chars), git log --oneline -n 5, current + main branch names, git user name. Includes disclaimer: "snapshot in time, will not update during conversation"
getUserContext()getMemoryFiles() discovers all CLAUDE.md files. Disabled by CLAUDE_CODE_DISABLE_CLAUDE_MDS env var or --bare mode. Returns claudeMd content + ISO date.
Memory systemsrc/memdir/ — 8 files: findRelevantMemories.ts, memoryScan.ts, memoryAge.ts (staleness tracking), memoryTypes.ts, team-level paths and prompts
THE AGENTIC LOOP

QueryEngine.submitMessage() is an async generator yielding typed SDK messages. It calls query() (from src/query/) which manages the multi-turn loop. The query pipeline has 5 files: config.ts, deps.ts, stopHooks.ts, tokenBudget.ts, transitions.ts.

1. API callMessages + system prompt + tool definitions → Claude API
2. StreamResponse arrives. Content blocks yielded as they stream.
3. textIf just text → render to terminal. Yield success result.
4. tool_useIf tool_use blocks → wrappedCanUseTool() checks permission → execute → result becomes user message
5. LoopGo to step 1 with updated messages

Terminal states: success, error_max_turns, error_max_budget_usd, error_max_structured_output_retries (limit: 5), error_during_execution. Each includes duration_ms, usage, modelUsage, permission_denials, fast_mode_state.

43 TOOLS

Each tool is a directory under src/tools/ with implementation, UI component, prompt, and types. The BashTool alone has 18 files:

File I/ORead, Write, Edit, Glob, Grep
ShellBash (18 files), PowerShell, REPL
CodeLSP integration
TasksCreate, Get, List, Update, Stop, Output
WebSearch, Fetch
AgentsAgent, SendMessage, TeamCreate, TeamDelete
PlanningEnterPlanMode, ExitPlanMode
WorktreesEnterWorktree, ExitWorktree
MCPMCPTool, ListResources, ReadResource, McpAuth
NotebooksNotebookEdit
SchedulingScheduleCron, Sleep, RemoteTrigger
OtherToolSearch, Brief, Config, TodoWrite, Skill, SyntheticOutput
BASH SECURITY

bashSecurity.ts runs 20+ numbered validators on every command. shouldUseSandbox.ts determines sandboxing. commandSemantics.ts analyzes command intent. sedValidation.ts + sedEditParser.ts specifically validate sed commands. destructiveCommandWarning.ts warns before dangerous ops.

#1Incomplete commands — tab/flag/operator starting fragments
#2-3jq injection — system() function, -f/--rawfile/--slurpfile
#4Obfuscated flags — ANSI-C quoting, locale quoting
#5Shell metacharacters — ;|& in arguments
#6Dangerous variables in redirections/pipes
#7Newline injection — multi-command separation
#8-10Redirections — input, output, command substitution
#11IFS injection — $IFS variable usage
#12Git commit substitution — cmd sub in git messages
#13/proc/*/environ reads
#14Malformed token injection — unbalanced delimiters
#15Backslash-escaped whitespace outside quotes
#20Zsh builtins — zmodload, ztcp, zsocket, zpty, sysopen/read/write, zf_*
#21-23Backslash-escaped operators, quote desync detection

Only early-allow bypass: safe heredoc patterns with single-quoted delimiters that are provably non-expanding. Everything else goes through the full chain. Quote-aware analysis prevents ANSI-C and locale quoting escapes.

FILE EDIT INTERNALS

FileEditTool/utils.ts implements a multi-step matching pipeline for old_string. Edits don't just do string replace — they handle quote normalization and API artifact desanitization:

findActualString()Tries exact match → curly-to-straight quote normalization → API desanitization. Returns first match.
applyEditToFile()replaceAll() if replace_all flag, else replace(). Empty newString strips trailing newline.
getPatchForEdits()Validates no new_string contains a future old_string (prevents conflicts). Applies sequentially, generates unified diff hunks.
SUB-AGENT SPAWNING

AgentTool.tsx supports three spawn modes. Each agent gets isolated context via assembleToolPool(). Flat roster — teammates cannot spawn other teammates.

SyncBlocks parent. Iterates agentMessages[] until completion. finalizeAgentTool() returns result.
AsyncregisterAsyncAgent() detaches. void runWithAgentContext() runs in background. Returns outputFile path. enqueueAgentNotification() on complete.
TeamspawnTeammate() with tmux splitpane. use_splitpane: true. Flat roster enforced.
BackgroundingForeground agents can be backgrounded mid-execution — async closure takes over ownership
WorktreecreateAgentWorktree(slug) creates temporary git worktree. Auto-cleaned if no changes.
86 SLASH COMMANDS

Each command is a directory under src/commands/. Here's every one:

/add-dir/agents/autofix-pr/branch/btw/bughunter/chrome/clear/color/compact/config/context/copy/cost/debug-tool-call/desktop/diff/doctor/effort/env/exit/export/extra-usage/fast/feedback/files/good-claude/help/hooks/ide/install-github-app/install-slack-app/issue/keybindings/login/logout/mcp/memory/mobile/model/oauth-refresh/onboarding/output-style/passes/permissions/plan/plugin/pr_comments/privacy-settings/rate-limit-options/release-notes/reload-plugins/remote-env/remote-setup/rename/resume/review/rewind/sandbox-toggle/session/share/skills/stats/status/stickers/summary/tag/tasks/teleport/terminalSetup/theme/thinkback/thinkback-play/upgrade/usage/vim/voice/x402/commit/commit-push-pr/init/version/brief/insights/security-review/statusline/ultraplan/advisor
16 BUNDLED SKILLS

Skills are composable prompt+tool packages loaded from src/skills/bundled/. Custom skills loaded via loadSkillsDir.ts. MCP skills built via mcpSkillBuilders.ts.

batchRun prompts across multiple files
claudeApiBuild apps with Claude API
claudeInChromeBrowser automation via extension
debugDebug failing code
keybindingsConfigure keyboard shortcuts
loopRun commands on interval
loremIpsumGenerate placeholder text
rememberSave to memory system
scheduleRemoteAgentsCron-scheduled agents
simplifyCode review and cleanup
skillifyCreate new skills
stuckHelp when stuck on a problem
updateConfigModify settings.json
verifyVerify code changes
verifyContentValidate content accuracy
claudeApiContentAPI content generation
MCP INTEGRATION

23 files in src/services/mcp/. External tools are MCP servers — not built-in features.

TransportInProcessTransport.ts, SdkControlTransport.ts
ConnectionMCPConnectionManager.tsx, client.ts, useManageMCPConnections.ts hook
Authauth.ts, xaa.ts, xaaIdpLogin.ts, oauthPort.ts, channelAllowlist.ts, channelPermissions.ts
DiscoveryToolSearch — lazy loading. Tools discovered at runtime via officialRegistry.ts (prefetched after first render)
ApprovalmcpServerApproval.tsx — servers require user consent before activation
COST TRACKING

cost-tracker.ts uses OpenTelemetry-style counters:

TrackedInput tokens, output tokens, cache read/creation tokens, USD cost, API duration, wall-clock duration, tool exec time, lines added/removed
CalculationcalculateUSDCost() per model. Below $0.50: full precision. Above: rounded to cents.
PersistencerestoreCostStateForSession() — checks session ID match before restoring. Prevents duplication.
Nested costsAdvisor tool usage recursively tracked: addToTotalSessionCost(advisorCost, advisorUsage, model)
85 HOOKS

The entire application is hook-driven. Key groupings from src/hooks/:

PermissionsuseCanUseTool, useSwarmPermissionPoller, toolPermission/
IDEuseIDEIntegration, useIdeSelection, useDiffInIDE, useIdeConnectionStatus
SessionuseRemoteSession, useSSHSession, useDirectConnect, useSessionBackgrounding
InputuseVimInput, useTextInput, useInputBuffer, useArrowKeyHistory, usePasteHandler
PluginsuseManagePlugins, useMergedTools, useMergedClients, useMergedCommands
VoiceuseVoice, useVoiceEnabled, useVoiceIntegration
TasksuseTasksV2, useTaskListWatcher, useBackgroundTaskNavigation
ConfiguseSettings, useSettingsChange, useDynamicConfig, useSkillsChange
SOURCE

Based on analysis of github.com/nirholas/claude-code — the leaked Claude Code source.