T
Token Pulse
Back to Home

Claude Code Agent Architecture Deep Analysis

2026-04-02
48 min read

Claude Code Agent Architecture Deep Analysis



Overview



This document provides a comprehensive architectural analysis of the Claude Code agent system, a sophisticated AI-powered coding assistant built with TypeScript/React. The codebase implements a full-featured code agent with multi-modal capabilities, tool execution, session management, and extensible plugin architecture.

---

1. Core Architecture Layers



1.1 Entry Points Layer (src/entrypoints/)



The system supports multiple execution modes:

- cli.tsx: Command-line interface entry point
- init.ts: Initialization and telemetry setup
- mcp.ts: MCP (Model Context Protocol) server entry
- sdk/: SDK mode for programmatic access
- agentSdkTypes.ts: SDK type definitions for external integrations

1.2 Main Application Layer



Entry Point: main.tsx
- CLI argument parsing with Commander.js
- Feature flag management via bun:bundle
- Startup optimization (profiling, prefetching, parallel initialization)
- Conditional module loading based on feature flags
- Plugin and skill registration

Setup: setup.ts
- Environment validation (Node.js version, permissions)
- Working directory initialization
- Git repository detection and worktree management
- UDS (Unix Domain Socket) messaging server setup
- Session memory and context collapse initialization
- Plugin hook registration and hot-reload setup
- Terminal backup restoration (iTerm2, Terminal.app)

---

2. State Management Architecture



2.1 AppState System (src/state/)



Core Files:
- AppState.tsx: React context provider and hooks
- AppStateStore.ts: Store definition and state shape
- store.ts: Store creation utilities
- selectors.ts: State selection utilities

Key State Components:
- Tool permission context (modes, rules, working directories)
- Message history and conversation state
- Task management (local/remote agents, shell tasks)
- MCP client connections
- File history and attribution state
- Fast mode and model configuration
- Team/swarm state for multi-agent collaboration

2.2 State Management Pattern



Uses external store pattern with React's useSyncExternalStore:

// Selector-based subscriptions (Object.is comparison)
const verbose = useAppState(s => s.verbose)

// Immutable updates via functional setState
setAppState(prev => ({ ...prev, mainLoopModel: newModel }))


---

3. Query Engine & Conversation Loop



3.1 QueryEngine Class (src/QueryEngine.ts)



Responsibilities:
- Manages conversation lifecycle (one QueryEngine per conversation)
- Message processing and persistence
- System prompt construction
- Tool execution context management
- Budget and turn limit enforcement
- Structured output handling
- Transcript recording and compaction

Key Methods:
- submitMessage(): Main async generator for processing user input
- interrupt(): Abort current query
- getMessages(): Retrieve conversation history

Query Lifecycle:
1. User input processing (slash commands, attachments)
2. System prompt assembly (tools, context, memory)
3. API query execution via query() function
4. Tool use coordination and permission checks
5. Message normalization and transcript recording
6. Result yield with usage/cost metrics

3.2 Core Query Loop (src/query.ts)



Features:
- Streaming API integration with Anthropic Claude
- Tool orchestration via StreamingToolExecutor
- Auto-compaction and context management
- Token budget tracking
- Error handling and retry logic
- Hook execution (pre/post tool use, stop hooks)
- Message normalization for API

Query Flow:
User Message → Process Input → Build System Prompt → API Call 
→ Tool Use Detection → Permission Check → Tool Execution
→ Result Integration → Continue/Stop Decision


---

4. Tool System Architecture



4.1 Tool Type System (src/Tool.ts)



Core Tool Interface:
type Tool = {
name: string
call(args, context, canUseTool, parentMessage, onProgress): Promise
description(input, options): Promise
inputSchema: Zod schema
checkPermissions(input, context): Promise
isConcurrencySafe(input): boolean
isReadOnly(input): boolean
isEnabled(): boolean
// ... 40+ optional methods for rendering, validation, progress, etc.
}


Tool Context (ToolUseContext):
- Access to AppState (get/set)
- Abort controller for cancellation
- Message history
- MCP clients and resources
- Agent definitions
- File state cache
- Notification system
- Progress tracking

4.2 Tool Categories (src/tools/)



Core Tools (42 tool directories):
- File Operations: FileReadTool, FileEditTool, FileWriteTool, NotebookEditTool
- Shell Execution: BashTool, PowerShellTool
- Search: GrepTool, GlobTool, ToolSearchTool
- Task Management: TaskCreateTool, TaskGetTool, TaskStopTool, TaskListTool, TaskOutputTool, TaskUpdateTool
- Team/Swarm: TeamCreateTool, TeamDeleteTool, SendMessageTool
- Agent/Skill: AgentTool, SkillTool
- Web: WebSearchTool, WebFetchTool
- MCP: MCPTool, ListMcpResourcesTool, ReadMcpResourceTool, McpAuthTool
- IDE Integration: LSPTool
- Workflow: EnterPlanModeTool, ExitPlanModeTool, EnterWorktreeTool, ExitWorktreeTool
- Utility: TodoWriteTool, AskUserQuestionTool, ConfigTool, BriefTool

Tool Factory (src/tools.ts):
- Assembles tool set based on feature flags
- Conditional tool loading (ant-only, experimental)
- Tool deduplication and filtering
- Agent-disallowed tool enforcement

4.3 Tool Permission System



Permission Context:
- Permission modes (default, auto, bypass, plan)
- Rule-based permissions (always allow/deny/ask)
- Tool-specific permission checks
- Hook-based permission interception
- Denial tracking and fallback logic

---

5. Command System (src/commands/)



5.1 Command Architecture



100+ slash commands organized by feature:
- Session Management: /clear, /compact, /resume, /share, /rename
- Configuration: /config, /model, /theme, /permissions, /mcp
- Development: /diff, /commit, /review, /status
- Tools: /cost, /usage, /stats, /tasks
- Plugins: /plugin, /skills, /memory
- Integration: /ide, /desktop, /mobile, /chrome
- Advanced: /worktree, /teleport, /agents, /hooks

5.2 Command Types



- Interactive Commands: Require REPL context, can show UI
- Non-Interactive Commands: Work in SDK/bare mode
- Local Commands: Execute immediately without API call
- Meta Commands: Modify session state or configuration

---

6. Task Management System



6.1 Task Types (src/Task.ts)



type TaskType = 
| 'local_bash' // Local shell execution
| 'local_agent' // Local sub-agent
| 'remote_agent' // Remote agent via bridge
| 'in_process_teammate' // In-process swarm teammate
| 'local_workflow' // Workflow execution
| 'monitor_mcp' // MCP monitoring
| 'dream' // Auto-dream mode


6.2 Task Implementations (src/tasks/)



- LocalMainSession.ts: Main session task
- LocalShellTask/: Shell command execution with I/O handling
- LocalAgentTask/: Local sub-agent spawning
- RemoteAgentTask/: Remote agent via bridge
- InProcessTeammateTask/: Swarm teammate management
- DreamTask/: Auto-dream task

Task Lifecycle:
Pending → Running → Completed/Failed/Killed


---

7. Bridge System (src/bridge/)



7.1 Bridge Architecture



Enables remote agent execution and IDE integration:

Core Components:
- bridgeMain.ts (112KB): Main bridge orchestrator
- replBridge.ts (98KB): REPL bridge implementation
- remoteBridgeCore.ts (38KB): Remote bridge core logic
- bridgeApi.ts: Bridge API interface
- bridgeUI.ts: Bridge UI components
- bridgeMessaging.ts: Message transport layer

Features:
- Session creation and management
- Permission callbacks
- Inbound message/attachment handling
- JWT authentication
- Polling configuration
- Trusted device management
- Work secret handling

7.2 Bridge Transport



- replBridgeTransport.ts: Transport layer for REPL bridge
- initReplBridge.ts: Bridge initialization
- replBridgeHandle.ts: Request handling

---

8. MCP (Model Context Protocol) Integration



8.1 MCP Service (src/services/mcp/)



Core Files:
- client.ts (116KB): MCP client implementation
- config.ts (49KB): MCP server configuration
- auth.ts (86KB): MCP authentication (OAuth, etc.)
- types.ts: MCP type definitions
- MCPConnectionManager.tsx: Connection lifecycle management

MCP Features:
- Server configuration and management
- OAuth authentication flows
- Resource discovery and reading
- Tool invocation
- Channel permissions and notifications
- Elicitation handling
- In-process and SDK control transports

8.2 MCP Tools



- MCPTool: Generic MCP tool invocation
- ListMcpResourcesTool: List available resources
- ReadMcpResourceTool: Read resource content
- McpAuthTool: Handle MCP authentication

---

9. Services Layer (src/services/)



9.1 API Services (src/services/api/)



- claude.ts (122KB): Core API client for Claude
- withRetry.ts (27KB): Retry logic with exponential backoff
- errors.ts (40KB): Error categorization and handling
- logging.ts (23KB): Request/response logging
- bootstrap.ts: Bootstrap data fetching
- sessionIngress.ts: Session data synchronization
- filesApi.ts: File upload/download

9.2 Analytics & Feature Flags



- analytics/: Event tracking and analytics
- growthbook.ts: Feature flag management
- policyLimits/: Policy-based rate limiting

9.3 Session Services



- SessionMemory/: Session-level memory management
- compact/: Context compaction strategies
- teamMemorySync/: Team memory synchronization
- contextCollapse/: Context optimization

9.4 Plugin & Skill Services



- plugins/: Plugin lifecycle management
- tools/: Tool orchestration services
- StreamingToolExecutor: Concurrent tool execution
- toolOrchestration.ts: Tool coordination logic

---

10. UI/UX Architecture



10.1 Component System (src/components/)



200+ React components organized by domain:

Core UI:
- App.tsx: Root application component
- Messages.tsx (144KB): Message rendering
- Message.tsx (77KB): Individual message component
- VirtualMessageList.tsx (145KB): Virtualized list
- FullscreenLayout.tsx (82KB): Main layout

Input & Interaction:
- PromptInput/: Prompt input system (21 files)
- TextInput.tsx: Text input handling
- VimTextInput.tsx: Vim mode input
- ScrollKeybindingHandler.tsx (145KB): Keyboard handling

Tool Rendering:
- Spinner.tsx (85KB): Tool execution spinner
- StructuredDiff.tsx: Diff visualization
- FileEditToolDiff.tsx: File edit display
- messageActions.tsx: Message action buttons

Dialogs & Overlays:
- GlobalSearchDialog.tsx: Search interface
- LogSelector.tsx (195KB): Session log browser
- MessageSelector.tsx (112KB): Message selection
- Settings/: Settings UI (4 files)

Specialized Components:
- CooperatorAgentStatus.tsx: Multi-agent status
- TaskListV2.tsx: Task management UI
- ContextVisualization.tsx (74KB): Context visualization
- Feedback.tsx (85KB): Feedback system

10.2 Component Organization



components/
├── agents/ # Agent-related UI
├── design-system/ # Reusable UI primitives
├── diff/ # Diff visualization
├── grove/ # Code graph visualization
├── hooks/ # Component-specific hooks
├── mcp/ # MCP UI components
├── memory/ # Memory UI
├── messages/ # Message rendering (34 files)
├── permissions/ # Permission UI (30 files)
├── sandbox/ # Sandbox UI
├── shell/ # Shell output rendering
├── skills/ # Skill UI
├── tasks/ # Task UI (12 files)
├── teams/ # Team UI
├── ui/ # Base UI components
└── wizard/ # Setup wizards


---

11. Hooks System (src/hooks/)



11.1 Core Hooks (83+ hooks)



Input & Interaction:
- useTextInput.ts: Text input state management
- useTypeahead.tsx (207KB): Autocomplete system
- useArrowKeyHistory.tsx: History navigation
- useGlobalKeybindings.tsx: Global keyboard shortcuts
- useVimInput.ts: Vim mode handling

Tool & Permission:
- useCanUseTool.tsx (39KB): Tool permission checking
- useCancelRequest.ts: Request cancellation

Session & State:
- useReplBridge.tsx (112KB): REPL bridge integration
- useRemoteSession.ts: Remote session handling
- useSessionBackgrounding.ts: Session backgrounding
- useInboxPoller.ts (33KB): Message polling

Task & Agent:
- useTasksV2.ts: Task state management
- useTaskListWatcher.ts: Task list updates
- useBackgroundTaskNavigation.ts: Task navigation
- useSwarmInitialization.ts: Swarm setup

UI & Rendering:
- useVirtualScroll.ts (34KB): Virtual scrolling
- useTerminalSize.ts: Terminal dimensions
- useDiffData.ts: Diff data management

Voice & Media:
- useVoice.ts (44KB): Voice input handling
- useVoiceIntegration.tsx (97KB): Voice integration

---

12. Agent & Swarm Architecture



12.1 Agent System



Agent Tool (src/tools/AgentTool/):
- Agent definition loading and parsing
- Built-in and custom agent support
- Agent color management
- Sub-agent spawning and lifecycle
- Agent-specific tool restrictions

Agent Types:
- Local agents (in-process)
- Remote agents (via bridge)
- In-process teammates (swarm)
- Workflow agents

12.2 Swarm Collaboration



Features:
- Multi-agent task delegation
- Inter-agent messaging (SendMessageTool)
- Team creation and management
- Permission polling for background agents
- Task output aggregation

---

13. Plugin & Extension System



13.1 Plugin Architecture (src/utils/plugins/)



Plugin Features:
- Dynamic plugin loading and caching
- Plugin hook system (pre/post tool use, session events)
- Hot-reload support
- Plugin marketplace integration
- Scoped installation (user/project/global)

13.2 Skill System (src/skills/)



Skills:
- Bundled skills registration
- Dynamic skill discovery
- Skill tool execution
- Skill search and prefetch

---

14. Memory & Context Management



14.1 Memory Systems



Session Memory (src/services/SessionMemory/):
- Session-scoped memory
- Memory attachment triggers
- Nested memory paths

Team Memory (src/services/teamMemorySync/):
- Cross-session memory sharing
- Memory synchronization watcher
- Team memory state management

CLAUDE.md Integration:
- Project-level memory files
- External includes support
- Memory file cache management

14.2 Context Management



Context Collapse (src/services/contextCollapse/):
- Context optimization
- Token usage reduction
- Intelligent context pruning

Compaction (src/services/compact/):
- Auto-compaction strategies
- Reactive compaction
- Snip-based compaction (HISTORY_SNIP)
- Post-compaction message building

---

15. File & Git Integration



15.1 File Operations



File State Cache (src/utils/fileStateCache.ts):
- LRU cache for file reads
- Cache invalidation
- Clone support for sub-agents

File History (src/utils/fileHistory.ts):
- Snapshot-based file history
- Per-message file state tracking
- File diff generation

15.2 Git Integration



Git Utilities (src/utils/git.ts):
- Git repository detection
- Worktree management
- Branch operations
- Commit attribution

Worktree System:
- Worktree creation for sessions
- Tmux session integration
- Worktree state persistence

---

16. Security & Permissions



16.1 Permission System



Permission Modes:
- default: Standard permission prompts
- auto: Automated permission decisions
- bypass: Skip permissions (sandbox only)
- plan: Plan mode restrictions

Permission Rules:
- Tool-based rules (always allow/deny/ask)
- Pattern matching (glob patterns)
- Path-based restrictions
- Hook-based permission interception

16.2 Security Features



Sandbox Integration:
- Docker sandbox detection
- Bubblewrap sandbox support
- Root/sudo restrictions
- Internet access validation

Security Hooks:
- Pre/post tool use hooks
- Session start/end hooks
- Compact hooks
- File change watcher

---

17. Configuration & Settings



17.1 Configuration System



Config Sources:
- Global config (~/.claude/)
- Project config (.claude/)
- Environment variables
- Remote managed settings
- MDM (Mobile Device Management)

Settings Management:
- Dynamic settings application
- Settings change detection
- Hot-reload support
- Validation and error handling

17.2 Feature Flags



Feature Flag System (bun:bundle):
- Conditional compilation
- Dead code elimination
- A/B testing support via GrowthBook
- Environment-based overrides

---

18. Analytics & Telemetry



18.1 Event Tracking



Analytics Service (src/services/analytics/):
- Event logging
- Usage metrics
- Performance tracking
- Error reporting (Sentry)

Key Events:
- tengu_started: Session start
- tengu_exit: Session end with metrics
- tengu_worktree_created: Worktree creation
- Tool invocation tracking
- Cost and token usage

18.2 Diagnostics



Diagnostic Tools:
- Startup profiler
- Query profiler
- Headless profiler
- In-memory error log
- Diagnostic display component

---

19. Terminal & IDE Integration



19.1 Terminal Integration



Terminal Features:
- REPL (Read-Eval-Print Loop)
- Ink.js rendering engine
- Terminal size detection
- Early input capture
- Terminal backup/restore (iTerm2, Terminal.app)

19.2 IDE Integration



IDE Support:
- Direct connection protocol
- Auto-connect dialogs
- Selection synchronization
- Logging integration
- Onboarding flow

---

20. Build & Runtime Architecture



20.1 Build System



Bun Runtime:
- Fast module evaluation
- Feature flag bundling
- Conditional imports
- Dead code elimination

20.2 Module Organization



src/
├── entrypoints/ # Application entry points
├── main.tsx # Main CLI entry
├── setup.ts # Environment setup
├── QueryEngine.ts # Query lifecycle
├── query.ts # Core query loop
├── Tool.ts # Tool type system
├── Task.ts # Task type system
├── commands.ts # Command registry
├── tools.ts # Tool registry
├── state/ # State management
├── services/ # Business logic services
├── tools/ # Tool implementations
├── commands/ # Command implementations
├── components/ # React UI components
├── hooks/ # React hooks
├── bridge/ # Remote bridge system
├── utils/ # Utility functions (300+ files)
├── types/ # TypeScript type definitions
├── constants/ # Constants and configuration
└── context/ # React contexts


---

21. Key Architectural Patterns



21.1 Async Generator Pattern



Query execution uses async generators for streaming:
async *submitMessage(prompt): AsyncGenerator {
// Process input
// Execute query loop
yield message // Stream messages
// Yield final result
}


21.2 External Store Pattern



State management without Redux/MobX:
const store = createStore(initialState, onChange)
const state = useAppState(selector)
setAppState(prev => ({ ...prev, ...updates }))


21.3 Feature Flag Pattern



Conditional compilation for different builds:
const feature = feature('VOICE_MODE') 
? require('./voice.js')
: null


21.4 Tool Factory Pattern



Consistent tool construction:
const MyTool = buildTool({
name: 'MyTool',
call: async (args, context) => { ... },
inputSchema: z.object({ ... }),
// Optional methods with sensible defaults
})


21.5 Context Injection Pattern



Rich context for tool execution:
type ToolUseContext = {
getAppState(): AppState
setAppState(updater): void
abortController: AbortController
messages: Message[]
// ... 40+ properties
}


---

22. Performance Optimizations



22.1 Startup Optimization



- Parallel prefetching (API keys, MCP resources, plugins)
- Lazy module loading
- Profile checkpointing
- Early input capture
- Background job deferral

22.2 Runtime Optimization



- LRU file state cache
- Virtualized message lists
- Message deduplication
- Context compaction
- Tool result budget management
- Transcript write batching

22.3 Memory Management



- Mutable message arrays (avoid copying)
- Compact boundary GC
- File cache eviction
- Content replacement state
- Ring buffer for error logs

---

23. Extensibility Points



23.1 Extension Mechanisms



1. Tools: Add new capabilities via Tool interface
2. Commands: Add slash commands
3. Plugins: Dynamic functionality loading
4. Skills: Bundled or custom skills
5. Hooks: Intercept lifecycle events
6. Agents: Define custom agent behaviors
7. MCP Servers: External tool/resource providers

23.2 Integration Points



- SDK: Programmatic access via async generators
- Bridge: Remote agent execution
- MCP: External service integration
- IDE: Editor synchronization
- CLI: Command-line interface
- Web: Remote session access

---

24. Technology Stack



Core Technologies



- Runtime: Bun (with Node.js compatibility)
- Language: TypeScript
- UI Framework: React 19 with React Compiler
- Terminal UI: Ink.js
- State Management: External store pattern
- CLI Parsing: Commander.js
- Schema Validation: Zod v4
- HTTP Client: Custom API client with retry
- Feature Flags: GrowthBook + bun:bundle

Key Dependencies



- @anthropic-ai/sdk: Claude API client
- @modelcontextprotocol/sdk: MCP protocol
- react: UI framework
- ink: Terminal rendering
- zod: Schema validation
- commander: CLI parsing
- chalk: Terminal colors
- lodash-es: Utility functions

---

25. Architecture Strengths



1. Modular Design: Clear separation of concerns across layers
2. Type Safety: Comprehensive TypeScript coverage
3. Extensibility: Rich plugin, tool, and command systems
4. Performance: Optimized startup and runtime behavior
5. Flexibility: Feature flags enable multiple product variants
6. Developer Experience: Hot-reload, diagnostics, profiling
7. Security: Permission system, sandbox integration
8. Scalability: Multi-agent swarm support
9. Integration: MCP, IDE, bridge, SDK support
10. Maintainability: Consistent patterns, factory functions

---

26. Architecture Complexity Metrics



- Total Source Files: ~1,500+ files
- Tools: 42 tool implementations
- Commands: 100+ slash commands
- Components: 200+ React components
- Hooks: 83+ custom React hooks
- Services: 30+ service modules
- Lines of Code: ~500,000+ lines (estimated)
- Largest Files:
- main.tsx: 4,684 lines
- LogSelector.tsx: 195KB
- useTypeahead.tsx: 207KB
- bridgeMain.ts: 112KB
- claude.ts: 122KB

---

Conclusion



The Claude Code agent architecture represents a sophisticated, production-grade AI coding assistant system. Key architectural highlights include:

1. Layered Architecture: Clear separation from entry points through services to UI
2. Query-Centric Design: Async generator-based conversation loop
3. Extensible Tool System: 40+ tools with rich type system and permission model
4. Multi-Modal Support: Terminal, IDE, web, voice, and SDK interfaces
5. Collaborative Features: Swarm/multi-agent support with team memory
6. Performance-First: Optimized startup, runtime, and memory management
7. Security-Conscious: Permission system, sandbox support, policy limits
8. Feature-Flagged: Conditional compilation for different product variants

The architecture successfully balances complexity with maintainability through consistent patterns, comprehensive typing, and clear module boundaries.