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 · bubble
4-Way Race ResolutionUser · Hook · Classifier · Bridge
Bash ClassifierLLM auto-judges command safety
Rule Engineallow/deny/ask · glob · denial tracking
ResolveOnce atomic race · first claim wins
5-Layer Context Compaction
① snip compactOld tool_result → [snipped] preserves structure
② microcompactStrip old tool results · Notify cache detector
③ context collapseCollapse completed sub-conversations
④ autoCompactThreshold summary
⑤ reactivePTL error trigger
compact boundary · Incremental recovery · tool result budget
Four-Layer Extension System
Commands 80+built-in · skills · plugins · MCP prompt
SkillsMarkdown prompt · Dynamic discovery · Conditional activation
PluginsCapability bundle: cmd/skill/hook/MCP/agent
MCP Clientstdio/SSE/HTTP/WS/claudeai-proxy
External capabilities unified as tool/resource/command/skill
Agent / Task Subsystem
AgentToolSubagent · Independent tool pool/model/workdir
Task Unified Shelllocal_agent · remote · bash · workflow
SendMessageToolTeam context · Broadcast · Plan approval
worktree / remote IsolationGit worktree · Remote execution
Feature-Flagged
GrowthBook
BUDDY Virtual PetTamagotchi · 18 species · 500ms sprite animation
KAIROS Resident AgentNight Dream · Brief mode · Persistent memory
ULTRAPLAN Remote PlanningCCR 30min · Browser approval · teleport
CoordinatorMulti-agent parallel · Push notify · scratch
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