Layer Diagram
The Four Main Layers
Entry Layer
cli.tsx parses CLI flags and version info, then delegates to main.tsx. From there, the app forks: interactive sessions render with React/Ink via REPL.tsx, while SDK/headless consumers go through QueryEngine.ts.Query Engine
The SDK-facing lifecycle engine.
submitMessage() returns an AsyncGenerator<SDKMessage> that drives the full agent loop — assembling prompts, handling slash commands, streaming tool execution, and compacting context.Three Pillars
Tool System — 40+ tools behind a uniform
Tool<Input, Output, Progress> interface. Service Layer — API client, compact engine, MCP manager, analytics. State Layer — AppStateStore providing React context for permissions, file history, and model settings.Task & Bridge Layer
Tasks represent long-running work:
local_bash, local_agent, remote_agent, in_process, dream, and workflow. The Bridge Layer (bridgeMain.ts) connects to Claude Desktop or remote containers via HTTP with JWT auth and backoff.Key Design Patterns
| Pattern | Where used | Purpose |
|---|---|---|
| AsyncGenerator streaming | QueryEngine, query() | Full-chain streaming from API response to consumer |
| Builder + Factory | buildTool() in Tool.ts | Safe defaults and uniform interface for all tools |
| Branded Types | SystemPrompt, asSystemPrompt() | Prevent string/array type confusion at compile time |
| Feature Flags + DCE | feature() from bun:bundle | Compile-time dead code elimination for 108 internal modules |
| Discriminated Unions | Message types in types/message.ts | Type-safe handling of user/assistant/progress/system messages |
| Observer + State Machine | StreamingToolExecutor | Tool execution lifecycle tracking with concurrent/serial partitioning |
| Snapshot State | FileHistoryState | Undo/redo capability for file operations |
| Ring Buffer | Error log | Bounded memory usage during long sessions |
| Fire-and-Forget Write | recordTranscript() | Non-blocking JSONL persistence with ordering guarantees |
| Lazy Schema | lazySchema() | Defer Zod schema evaluation for startup performance |
| Context Isolation | AsyncLocalStorage | Per-agent context in a shared process for multi-agent runs |
Directory Reference
The 12 Progressive Harness Mechanisms
Claude Code layers 12 production mechanisms on top of the basic agent loop. Each builds on the previous:| # | Mechanism | Description |
|---|---|---|
| s01 | The Loop | query.ts: the while-true loop that calls the Claude API, checks stop_reason, executes tools, appends results |
| s02 | Tool Dispatch | Tool.ts + tools.ts: every tool registers into the dispatch map; buildTool() factory provides safe defaults |
| s03 | Planning | EnterPlanModeTool / TodoWriteTool: list steps first, then execute |
| s04 | Sub-Agents | AgentTool + forkSubagent.ts: each child gets fresh messages[], keeping the main conversation clean |
| s05 | Knowledge on Demand | SkillTool + memdir/: inject knowledge via tool_result, not system prompt; CLAUDE.md loaded lazily |
| s06 | Context Compression | services/compact/: three-layer strategy — autoCompact (summarize) + snipCompact (trim) + contextCollapse |
| s07 | Persistent Tasks | TaskCreate/Update/Get/List: file-based task graph with status tracking and persistence |
| s08 | Background Tasks | DreamTask + LocalShellTask: daemon threads run slow commands; agent keeps thinking |
| s09 | Agent Teams | TeamCreate/Delete + InProcessTeammateTask: persistent teammates with async mailboxes |
| s10 | Team Protocols | SendMessageTool: one request-response pattern for all agent-to-agent negotiation |
| s11 | Autonomous Agents | coordinator/coordinatorMode.ts: idle cycle + auto-claim; no lead assignment required |
| s12 | Worktree Isolation | EnterWorktreeTool/ExitWorktreeTool: tasks manage goals, worktrees manage directories |