InkdownInkdown
Start writing

Claude-Code

62 files·4 subfolders

Shared Workspace

Claude-Code
codex

00-overview

Shared from "Claude-Code" on Inkdown

Claude Code — Architecture Overview

Written like a senior engineer giving KT to a junior. Read this first, then dive into the per-module docs.


What Is This?

This is Claude Code — Anthropic's agentic coding assistant that runs in your terminal. It's a TypeScript/Bun application that:

  1. Provides an interactive TUI (terminal UI) built with a custom React renderer called Ink
  2. Connects to Anthropic's API to stream AI responses with tool-use capabilities
  3. Can execute shell commands, read/write/edit files, search codebases, and more
  4. Supports multi-agent orchestration (coordinator mode, swarms)
  5. Can be controlled remotely via mobile/web (bridge system)
  6. Extends via plugins and skills

High-Level Architecture

Plain text
0000_start_here_index_and_recommended_reading_order.md
0100_project_overview_tech_stack_runtime_modes_and_folder_map.md
0200_startup_flow_entry_points_and_cold_start_sequence.md
0300_codebase_modules_layers_state_models_and_schemas.md
0400_system_architecture_and_design_rationale.md
0500_interactive_repl_request_flow_end_to_end.md
0600_headless_sdk_and_print_mode_request_flow_end_to_end.md
0700_mcp_integration_connection_and_tool_call_flow.md
0800_external_services_sdks_storage_and_local_dependencies.md
0900_environment_variables_settings_feature_flags_and_failure_modes.md
1000_non_obvious_patterns_gotchas_and_debugging_traps.md
1100_full_codebase_file_inventory_grouped_by_directory.md
kimi
00-overview.md
01-entrypoints.md
02-state-management.md
03-query-system.md
04-tools-system.md
05-tasks-system.md
06-ui-components.md
07-bridge-remote.md
08-services.md
09-skills-plugins.md
10-commands.md
11-testing-architecture.md
12-permission-system.md
13-build-system.md
14-ink-internals.md
15-git-internals.md
16-context-compaction.md
17-vim-mode.md
18-mailbox-notifications.md
19-session-persistence.md
20-hooks-system.md
21-error-recovery.md
README.md
qwen
00-overview.md
01-entry-points.md
02-query-engine.md
03-tools-and-tasks.md
04-commands-and-skills.md
05-state-management.md
06-ink-rendering.md
07-bridge-remote.md
08-mcp-services.md
09-services-overview.md
10-multi-agent.md
11-system-prompt-constants.md
12-tool-interface.md
13-memory-system.md
14-buddy-companion.md
15-keybindings.md
16-stop-hooks.md
17-vim-mode.md
18-upstreamproxy.md
19-cost-tracking-history.md
20-contexts-styles-onboarding.md
21-hooks.md
22-screens.md
tweets-explain
claude-code-memory-analysis.md
compact
memory-system
agentic-architecture
┌─────────────────────────────────────────────────────────────────┐
│                        USER (Terminal)                          │
└──────────────────────────┬──────────────────────────────────────┘
                           │
┌──────────────────────────▼──────────────────────────────────────┐
│                     CLI ENTRY POINT                              │
│  main.tsx → Commander.js CLI parser → run() → setup()           │
│  Handles: flags, args, migrations, init, feature flags           │
└──────────────────────────┬──────────────────────────────────────┘
                           │
        ┌──────────────────┼──────────────────┐
        │                  │                  │
┌───────▼───────┐  ┌──────▼───────┐  ┌───────▼───────┐
│   Interactive │  │  Headless    │  │   Remote      │
│   REPL (TUI)  │  │  (-p/--print)│  │   (Bridge)    │
│               │  │              │  │               │
│  Ink Renderer │  │  QueryEngine │  │  WebSocket/   │
│  + Screens    │  │  → API       │  │  SSE          │
└───────┬───────┘  └──────┬───────┘  └───────┬───────┘
        │                 │                  │
        └─────────────────┼──────────────────┘
                          │
              ┌───────────▼───────────┐
              │     QUERY ENGINE      │
              │  query.ts (the loop)  │
              │                       │
              │  1. Build messages    │
              │  2. Call model (API)  │
              │  3. Stream response   │
              │  4. Execute tools     │
              │  5. Loop if tool_use  │
              │  6. Compact if needed │
              └───────────┬───────────┘
                          │
        ┌─────────────────┼─────────────────┐
        │                 │                 │
┌───────▼──────┐  ┌──────▼──────┐  ┌───────▼──────┐
│   TOOLS      │  │  SERVICES   │  │   STATE      │
│              │  │             │  │              │
│ BashTool     │  │ MCP Servers │  │ AppState     │
│ FileEditTool │  │ Plugins     │ │ bootstrap/    │
│ FileReadTool │  │ Skills      │ │ state/        │
│ GrepTool     │  │ Analytics   │ │              │
│ AgentTool    │  │ Compact     │ │              │
│ ...40+ more  │  │ LSP, etc.   │ │              │
└──────────────┘  └─────────────┘  └──────────────┘

Key Concepts

1. The Query Loop (query.ts)

The heart of the system. Every time the user sends a message, a query loop starts:

Plain text
while (true) {
  1. Prepare messages (compact/snip/collapse if needed)
  2. Call the AI model (streaming)
  3. For each tool_use in response → execute the tool
  4. If no more tool_use → done, return
  5. If tool results → loop back to step 1
}

The loop handles recovery from errors (prompt too long, max output tokens, model fallback), context compaction, and streaming.

2. Tools

Tools are how the AI interacts with the world. Each tool has:

  • A JSON Schema definition (sent to the API)
  • An execution function
  • Permission checks (ask user, auto-allow, auto-deny)

Core tools: Bash, FileRead, FileEdit, FileWrite, Grep, Glob, WebSearch, WebFetch, TodoWrite, AskUserQuestion, Skill, and 30+ more.

3. Commands (Slash Commands)

User-facing commands typed as /command in the REPL: /compact, /model, /help, /clear, /plan, etc. Commands can be:

  • builtin — shipped with the app
  • skills — loaded from /skills/ directories
  • plugin — loaded from installed plugins
  • MCP — loaded from MCP servers
4. State Management

Two layers:

Bootstrap State (bootstrap/state.ts): A singleton module with getter/setter functions for global session state (session ID, cost, cwd, model, telemetry). This is the "global variables" layer.

AppState (state/): A Redux-like store using useSyncExternalStore. Holds all UI state (which panels are open, MCP connections, tasks, permissions, settings). Components subscribe to slices via useAppState(selector).

5. Ink Rendering

A custom React renderer that renders to the terminal instead of the DOM. Uses:

  • react-reconciler for the React fiber tree
  • Yoga (WASM) for flexbox layout
  • Double-buffered frame system for efficient terminal updates
  • ANSI escape sequences for output
6. Bridge (Remote Control)

Allows controlling a local Claude Code session from claude.ai/code (web) or the mobile app. Two modes:

  • Standalone bridge: claude remote-control — runs as a server, spawns child processes
  • REPL bridge: /remote-control — bridges an existing session

Uses WebSocket (v1) or SSE (v2) transport with JWT authentication.

7. Multi-Agent (Coordinator Mode)

The AI can act as a coordinator that spawns worker agents (sub-processes) to work on tasks in parallel. Workers report back via <task-notification> blocks.

8. Plugins & Skills
  • Plugins: Versioned packages that can add tools, commands, hooks, and MCP servers
  • Skills: Prompt-based capabilities discovered from /skills/ directories in the project

File Structure Map

Plain text
src/
├── main.tsx              — CLI entry point, Commander.js setup
├── setup.ts              — Session initialization (cwd, worktrees, hooks)
├── query.ts              — THE query loop (model calls, tool execution, compaction)
├── QueryEngine.ts        — Higher-level query orchestration
├── commands.ts           — All slash command definitions
├── tools.ts              — All tool definitions and assembly
├── tasks.ts              — Task type registry
├── context.ts            — System/user context (git status, CLAUDE.md)
├── Tool.ts               — Tool base type/interface
├── Task.ts               — Task base type/interface
│
├── bootstrap/            — Global singleton state (session ID, cost, model, etc.)
├── state/                — React store (AppState, selectors, side effects)
├── ink/                  — Custom React-to-terminal renderer
├── ink.ts                — Ink public API (render, createRoot, components)
├── screens/              — Top-level UI screens (REPL, setup, dialogs)
├── components/           — Shared UI components
├── hooks/                — React hooks
│
├── tools/                — Individual tool implementations (40+ tools)
├── tasks/                — Task implementations (LocalShell, LocalAgent, etc.)
├── commands/             — Slash command implementations
├── skills/               — Skill loading and bundled skills
├── plugins/              — Plugin system (bundled, versioned, lifecycle)
│
├── services/             — Business logic services
│   ├── api/              — Anthropic API client, streaming, retry
│   ├── mcp/              — Model Context Protocol servers
│   ├── compact/          — Context compaction (auto, micro, reactive)
│   ├── tools/            — Tool execution orchestration
│   ├── analytics/        — Telemetry, GrowthBook feature flags
│   └── ...               — Many more
│
├── bridge/               — Remote control (web/mobile connectivity)
├── coordinator/          — Coordinator mode (multi-agent orchestration)
├── server/               — Direct connect server
├── remote/               — Remote session management
├── cli/                  — CLI-specific utilities
├── entrypoints/          — Different entry modes (CLI, SDK, MCP, sandbox)
├── types/                — TypeScript type definitions
├── utils/                — Utility functions (hundreds of files)
└── migrations/           — Startup migrations (settings, model names, etc.)

How a Session Flows

  1. main.tsx starts → parses CLI args → runs migrations → calls init()
  2. setup.ts runs → sets cwd, restores terminal backups, initializes hooks, starts prefetches
  3. REPL renders → Ink renders the main screen with prompt, status bar, and message history
  4. User types a prompt → goes through processUserInput → enters the query loop
  5. query.ts builds messages → calls Anthropic API → streams response
  6. If AI uses a tool → tool execution runs → result goes back into messages → loop continues
  7. If context gets too large → compaction summarizes old messages
  8. When done → response renders in the TUI → user types next prompt

Read Next

Each module has its own deep-dive doc:

DocCovers
01-entry-points.mdmain.tsx, setup.ts, CLI parsing, entrypoints
02-query-engine.mdThe query loop, API calls, streaming, compaction
03-tools-and-tasks.mdTool system, task system, AgentTool, permissions
04-commands-and-skills.mdSlash commands, skills, plugins
05-state-management.mdBootstrap state, AppState store, selectors
06-ink-rendering.mdCustom React renderer, layout, terminal output
07-bridge-remote.mdRemote control, web/mobile connectivity
08-mcp-services.mdModel Context Protocol servers
09-services-overview.mdAll services (analytics, compact, tools, etc.)
10-multi-agent.mdCoordinator mode, swarms, sub-agents