Inside Claude Code: How Its Production‑Grade Agent Engine Works
This article dissects Claude Code’s architecture, detailing its simple while‑loop core, layered tool system with lazy loading, seven‑layer permission defense, five‑stage context compaction, sub‑agent collaboration, hook mechanisms, and the CLAUDE.md context‑engineering approach, revealing why token efficiency and deterministic security drive its design.
Preface
Many people treat Claude Code as merely a "chat window that can run Shell", similar to ChatGPT with a terminal, but that is a misconception. A source‑map leak in March 2026 exposed over 510 k lines of TypeScript, showing that Claude Code is built as a production‑grade autonomous execution system, far beyond a simple model‑plus‑tool call.
1. Core Architecture: A While‑Loop‑Driven Agent System
The heart of Claude Code is a straightforward while loop. Each iteration performs four steps: assemble context, invoke the model, receive tool requests, and execute tools. The loop repeats until the model stops requesting tools or a stop condition is triggered.
Five stop conditions exist: no tool call from the model, reaching the maximum round limit, context window overflow, Hook interception, or user‑initiated termination.
The loop itself is simple; the engineering difficulty lies in the surrounding infrastructure—permission checks, context management, error recovery, and sub‑agent scheduling—organized into a five‑layer architecture.
These layers map directly to source directories. The integration layer adapts CLI, SDK, IDE plugins, etc., all driven by the same Agent loop, meaning the code path is identical whether used in a terminal or VS Code.
2. Tool Execution System: More Than “Calling Functions”
Claude Code ships with a comprehensive tool suite: file read/write, Bash execution, text search (Grep/Glob), and sub‑agent scheduling (Task). Each tool implements a unified Tool interface defining name, description, parameter schema, permission requirements, and execution logic.
The standout design is the “lazy‑load” mechanism. When ToolSearch is enabled, only tool names are injected at startup; full parameter schemas are loaded only when the model actually requests a specific tool, saving thousands of tokens in a 200 K context window.
The Model Context Protocol (MCP) extends the tool system to external services such as databases, CI/CD pipelines, and project‑management tools. MCP tools follow the same permission flow but require extra caution because third‑party MCP servers can introduce prompt injection and data‑leak risks; several CVEs were reported for mcp‑server‑git at the end of 2025.
3. Permissions and Security: Seven‑Layer Defense in Depth
Claude Code defines seven permission modes ordered by trust: plan → default → acceptEdits → auto → dontAsk → bypassPermissions, plus an internal‑only bubble mode.
The auto mode is noteworthy: an internal ML classifier automatically judges whether a tool call is safe by evaluating operation type, target path, command content, etc. Anthropic engineers reported that enabling the sandbox reduced manual approvals from ~200 requests to 5‑10.
The security model follows a “deny‑over‑allow” principle—broad deny rules always override narrow allow rules—and permission state does not persist across sessions; trust must be re‑established each time.
The seven independent layers are: tool pre‑filtering, permission classifier, Hook interception, path‑rule matching, Shell sandbox isolation, sub‑command parsing, and network access control. If any layer fails, the others still provide protection.
A known weak point is that when a Shell command contains more than 50 sub‑commands, the parser skips security analysis to avoid event‑loop blockage, illustrating a performance‑vs‑security trade‑off.
4. Context Compression: Five‑Stage Compaction Pipeline
Context management is one of Claude Code’s largest subsystems; the src/services/compact/ directory alone contains nearly 4 000 lines of TypeScript. The core idea is “progressive compression”: cheap techniques are applied first, expensive ones later.
The most sophisticated part is the dual‑path design of L2 and L3. When the prompt cache is “hot” (potentially holding >100 K token prefixes), modifying the local message array would invalidate the cache, which is costly. The hot path uses the API‑side cache_edits mechanism—no local message changes, only a server‑side reference removal—keeping the cache intact.
When the cache is “cold” (e.g., after the user returns later), the cold path directly edits the local messages. The two paths are mutually exclusive and selected automatically based on cache timestamps.
L4 performs lossy compression by asking the model to summarize the entire dialogue history into a structured abstract. A practical caution: compression discards information, so security rules or critical commands placed in the dialogue (instead of system prompts or CLAUDE.md) may be forgotten after compression.
5. Sub‑Agent and Multi‑Agent Collaboration
Creating a sub‑agent is not merely “opening a new conversation”. When the main Agent uses the Task tool to spawn a sub‑agent, the sub‑agent receives its own context window, system prompt, and CLAUDE.md configuration, but it does not inherit the parent’s dialogue history.
This design enforces context isolation: a sub‑agent handling security audits should not be polluted by the parent’s UI‑refactoring discussion. After completing its task, the sub‑agent returns only a summary text to the parent, saving tokens and preventing context contamination.
A typical multi‑Agent orchestration pattern: the main Agent plans tasks and aggregates results, while sub‑agents handle specific domains such as code review, test execution, documentation generation, or security scanning, each with its own tool permission set to avoid over‑privilege.
6. Hook Mechanism: System‑Level Behavior Interception
Hooks provide extensibility for enterprise scenarios and are divided into two categories:
Blocking Hooks – can interrupt or modify Agent behavior. PreToolUse fires before tool execution and can deny dangerous operations (e.g., intercepting rm -rf); Stop / SubagentStop fire when the Agent finishes, forcing continuation.
Informational Hooks – only record events. PostToolUse logs after tool execution; SessionStart / SessionEnd manage session lifecycle; Notification routes Agent messages to Slack or other channels.
A typical security Hook detects a destructive Shell command, returns a deny decision with a reason, and does not rely on the model’s understanding—ensuring deterministic enforcement.
7. CLAUDE.md and Context Engineering
CLAUDE.md acts as Claude Code’s “project memory” file. It is reread on every Agent loop iteration, making it a dynamic architectural contract rather than a static note.
CLAUDE.md defines five scopes ordered by priority (low to high): enterprise → user → project root → subdirectory → environment variable injection. More specific scopes override broader ones.
The file also uses lazy loading: the root file loads at session start, while subdirectory instruction files load only when the Agent actually accesses that directory, another token‑saving trade‑off.
Effective CLAUDE.md writing follows a “WHAT/WHY/HOW” framework: describe the project, explain decisions, then list coding standards and style conventions. Placing security rules here (instead of in the dialogue) keeps them safe from Compaction, which only trims dialogue content.
8. Conclusion
Claude Code offers a rare production‑grade reference for Agent system design. Its two core insights are: (1) the Agent’s core loop can be extremely simple, with complexity pushed to surrounding infrastructure; (2) context is the scarcest resource, so every engineering decision revolves around “how to make the most of 200 K tokens”.
Teams building their own Agent systems can adopt proven patterns from Claude Code: progressive context compression instead of one‑shot truncation, deterministic Hooks rather than pure prompt constraints, and sub‑agent context isolation instead of a single ever‑growing dialogue window. These are not theoretical ideas but solutions validated at scale.
This article is compiled from Claude Code’s public architecture analysis, Anthropic’s official documentation, and community technical research. Corrections are welcome.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
TechVision Expert Circle
TechVision Expert Circle brings together global IT experts and industry technology leaders, focusing on AI, cloud computing, big data, cloud‑native, digital twin and other cutting‑edge technologies. We provide executives and tech decision‑makers with authoritative insights, industry trends, and practical implementation roadmaps, helping enterprises seize technology opportunities, achieve intelligent innovation, and drive efficient transformation.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
