Claude Code: Architecture of a Production Agentic System
On March 31, 2026, source map files were unintentionally included in the Claude Code npm package. This exposed 4,600+ internal TypeScript source files. The official open-source repository contains 279 files — primarily plugin interfaces. The leaked codebase contains the full engine.
We examine the architecture in detail.
Agentic Loop. The core execution engine is a 1,729-line async generator (query.ts). It implements a 6-stage per-turn pipeline: pre-request compaction, API call with parallel streaming tool execution, error recovery cascade, stop hook evaluation, tool execution, and state transition. The loop has 9 distinct termination conditions. State is managed through immutable reassignment — not incremental mutation.
Message Compaction. Context window management is implemented as a 4-tier system. Each tier operates at a different point on the cost–information-loss tradeoff curve: (1) Snip Compact — free, high loss; (2) Microcompact — free, cache-aware selective clearing; (3) Context Collapse — low cost, read-time projection over original history; (4) Auto-Compact — high cost, AI-generated summary. The ordering is strict. Cheaper methods run first. If they free sufficient tokens, expensive methods do not execute.
Error Recovery. Recovery follows a cost-aware cascade. For prompt-too-long errors: context collapse drain (cost: 0) → reactive compact (cost: 1 API call) → surface error. For max-output-token errors: silent cap escalation 8K→64K (cost: 0) → resume injection with up to 3 retries → graceful termination. A diminishing returns detector stops the loop when 3 consecutive continuations each produce fewer than 500 tokens.
Security. Eight layers: build-time dead code elimination, server-side feature flag kill switches, 8-source priority-ordered permission rules, ML-based transcript classification, dangerous pattern detection, 62K-line filesystem permission validation, trust dialog, and bypass kill switch. The design principle is defense in depth with fail-to-prompting semantics.
Unreleased Features. Feature flags reveal: voice mode (dedicated voice_stream endpoint, OAuth-only), web browser automation tool, multi-agent Coordinator mode (spawns workers via AgentTool, cannot execute tools directly), and Kairos proactive mode (GitHub webhook subscriptions, push notifications, background sleep polling).
The patterns observed — cost-aware recovery cascades, multi-tier compaction, build-time feature gating, diminishing returns detection — are general. They apply to any system where LLM API calls are the dominant cost.
