Claude Code Agent Runtime Architecture · v2.1.88 Sourcemap Reconstruction
Single Query Loop Iteration
System Prompt Assembly
Cache Boundary · Dynamic Context
Context Governance
5-Layer Compaction · Budget Control
Claude API Streaming
Streaming · Extended Thinking
Tool Dispatch & Execution
Concurrency Groups · Permissions · Hooks
Loop Control
Continue · Terminate · Recover
Interactive REPLReact/Ink · Declarative Terminal UI
Headless / SDK--print · stream-json
Remote / CCRWebSocket · Remote Sessions
Bridge Worker NodeRemote Control · Polling
Server ModeHTTP API · SDK Embedding
Message-Driven Core — Interactive and Headless share the same query/tool/message infrastructure
Query Loop · Conversation Core
QueryEngine.tsSession object · Message array · File cache · Usage tracking
query.ts Main LoopAPI streaming → tool_use detection → tool_result feedback
System Prompt AssemblyStatic prefix + DYNAMIC_BOUNDARY + Dynamic context
services/api/claude.tsRequest assembly · beta header · tool schema · prompt cache
Loop Controlmax-output recovery · auto-compact · stop hook
Tool Runtime · 40+ Tools
tools.ts Registryfeature gate · stable ordering · prompt cache friendly
toolOrchestration.tsConcurrency-safe grouping · read/write parallel split
toolExecution.tsschema validation · hook · permissions · telemetry · OTel
Tool.ts Unified Protocolcall + checkPermissions + render + isReadOnly
StreamingToolExecutorConcurrent execution while streaming · Progress rendering
Anthropic Claude APIOpus · Sonnet · Haiku · Streaming
MCP Server Processesstdio · SSE · HTTP · WS
Local File SystemRead · Edit · Write · Glob
Shell / SubprocessBash · PowerShell · sandbox
4-Way Permission Race
PermissionModedefault · plan · auto · bypass
4-Way Race ResolutionUser · Hook · Classifier · Bridge
Bash ClassifierLLM judges cmd safety
Rule Engineallow/deny/ask · glob · denials
ResolveOnce · first claim wins
5-Layer Context Compaction
① snip compactOld tool_result → [snipped]
② microcompactStrip old results · cache detector
③ context collapseCollapse completed sub-convos
④ autoCompactThreshold
⑤ reactivePTL error
compact boundary · result budget
Four-Layer Extension System
Commands 80+built-in · skills · plugins · MCP
SkillsMarkdown · dynamic discovery
PluginsBundle: cmd/skill/hook/MCP/agent
MCP Clientstdio/SSE/HTTP/WS · proxy
Unified as tool / resource / command / skill
Agent / Task Subsystem
AgentToolSubagent · own pool/model/dir
Task Unified Shelllocal_agent · remote · bash
SendMessageToolBroadcast · plan approval
Worktree IsolationGit worktree · remote exec
Feature-Flagged
GrowthBook
BUDDY Virtual PetTamagotchi · 18 species · sprite anim
KAIROS Resident AgentNight Dream · brief mode · memory
ULTRAPLAN Remote PlanningCCR 30min · browser approval · teleport
CoordinatorMulti-agent parallel · push notify
Persistence & State Layer ~/.claude/ · Session lifecycle management
bootstrap/state.tsProcess-level global state
AppStateStoreZustand-style runtime state
sessionStorage.tstranscript JSONL · Recovery core
history.tsInput history · Project-level
compact boundaryCompaction point · Incremental recovery
fileHistoryFile change snapshots
memdir/Memory directory · MEMORY.md
analytics / OTelDatadog · Telemetry
Key Architectural Observations
Message-Driven — User input, model output, tool progress, and system events are all Messages; the transcript is the recovery core
Prompt Cache First — Stable tool ordering, DYNAMIC_BOUNDARY split, deferred tools, cache break detection
Four-Layer Extensions — Command + Skill + Plugin + MCP coexist without conflict — this is a platform, not a client
Agent as First-Class — Independent tool pool / model / permissions / worktree, with SendMessage for team collaboration
Tech Stack
TypeScript + Bun ← Runtime
React / Ink ← Terminal UI framework
@anthropic-ai/sdk ← Claude API client
Zod v4 ← Tool schema validation
@modelcontextprotocol/sdk ← MCP protocol
vendor/: Rust native modules (audio · image · key modifiers · URL handler)
↑ Loop iteration until plain-text return or termination
Bash · Read · Edit · Write · Glob · Grep
Agent · Skill · ToolSearch · WebSearch …
Security Boundaries
User Input
4-Way Permission Race
User · Hook · Classifier · Bridge
Tool Safety Boundary
isReadOnly · Path checks · Dangerous files
Input Sanitization
Unicode anti-injection · SSRF guard
Hook Interception
PreToolUse · PostToolUse
Feature Gate
feature() · ant-only · GrowthBook