···119119120120Execution paths converge on shared **state** (`state/`, `bootstrap/`), **permissions** (`utils/permissions/`), and **session storage** (`utils/sessionStorage.js`, hooks in `utils/sessionStart.js`). Non-interactive and SDK-style use share much of the same stack as the full-screen REPL, with different front-ends for I/O.
121121122122+## Documentation (GitHub Pages)
123123+124124+Full internals documentation (architecture, workflows, official-docs cross-reference, subsystem reference, appendices) is built with **MkDocs Material** from [`docs-site/`](docs-site/).
125125+126126+- **Live site:** after you enable GitHub Pages on the `gh-pages` branch, the site is served at
127127+ `https://<your-github-user>.github.io/claude-code-source-code/`
128128+ (replace with your fork’s user/org and repo name).
129129+- **Local preview:** `cd docs-site && python3 -m venv .venv && source .venv/bin/activate && pip install -r requirements.txt && mkdocs serve`
130130+- **Publish:** pushing to `main` runs [`.github/workflows/pages.yml`](.github/workflows/pages.yml) and deploys to `gh-pages`.
131131+132132+Update `site_url` and `repo_url` in [`docs-site/mkdocs.yml`](docs-site/mkdocs.yml) after the first deploy so canonical URLs match your fork.
133133+134134+**Contributing to docs:** edit Markdown under `docs-site/docs/`; keep the [official docs map](docs-site/docs/official-docs-map.md) in sync with [Anthropic’s docs index](https://code.claude.com/docs/llms.txt) when adding major features.
135135+136136+### Next steps (first-time publish)
137137+138138+1. **Commit and push** this repository to GitHub (`main` must contain `docs-site/` and `.github/workflows/pages.yml`).
139139+2. **Allow the workflow to run** — GitHub Actions → _Deploy documentation to GitHub Pages_ → confirm it completes (or run **Run workflow** manually).
140140+3. **Turn on Pages** — Repository **Settings → Pages** → **Build and deployment** → Source: **Deploy from a branch** → Branch **`gh-pages`** / folder **`/ (root)`**. (If you prefer the newer “GitHub Actions” source, switch the workflow to `actions/upload-pages-artifact` + `deploy-pages` instead of peaceiris.)
141141+4. **Set `site_url`** in [`docs-site/mkdocs.yml`](docs-site/mkdocs.yml) to your live URL (e.g. `https://YOUR_USER.github.io/claude-code-source-code/`) and push again so sitemaps and search use the correct base.
142142+5. **Fork-specific URLs** — Update `repo_url`, `edit_uri`, and the `extra.social` GitHub link in `mkdocs.yml` if this is not `marium/claude-code-source-code`.
143143+122144## Repository layout
123145124146- **`src/`** — Application source (thousands of modules) as recovered from the bundle map.
125125-- **`docs/`** — Human-readable layout reference ([directory-structure.md](docs/directory-structure.md)).
147147+- **`docs-site/`** — MkDocs source for the GitHub Pages documentation site.
148148+- **`docs/`** — Short pointer plus [`directory-structure.md`](docs/directory-structure.md) (`src/` layout reference).
149149+- **`scripts/`** — Optional helpers (e.g. `gen-appendices.sh`).
126150- There is **no `package.json` in this clone**; building would require the original toolchain (Bun, internal `bun:bundle` features, and private deps). Treat this tree as a **read-only architectural reference**.
···11+# Architecture
22+33+!!! warning "Recovered source"
44+Paths refer to `src/` in this repository. Line-level accuracy is best-effort from the source map reconstruction.
55+66+## High-level flow
77+88+```mermaid
99+flowchart LR
1010+ subgraph entry [Entry]
1111+ mainTsx[main.tsx]
1212+ end
1313+ subgraph modes [Modes]
1414+ repl[REPL.tsx]
1515+ print[cli/print.ts]
1616+ assistant[assistant KAIROS gate]
1717+ end
1818+ subgraph core [Core loop]
1919+ queryLoop[query.ts queryLoop]
2020+ qe[QueryEngine.ts]
2121+ toolsReg[tools.ts getTools]
2222+ end
2323+ subgraph services [Services]
2424+ api[services/api]
2525+ mcp[services/mcp]
2626+ compact[services/compact]
2727+ end
2828+ mainTsx --> repl
2929+ mainTsx --> print
3030+ mainTsx -.-> assistant
3131+ repl --> queryLoop
3232+ print --> qe
3333+ queryLoop --> api
3434+ qe --> api
3535+ toolsReg --> mcp
3636+ queryLoop --> compact
3737+ qe --> compact
3838+```
3939+4040+## Entry and startup
4141+4242+`src/main.tsx` is the **Commander**-based CLI. Before the command handler runs, module evaluation triggers:
4343+4444+- Startup profiling checkpoints (`utils/startupProfiler.ts`)
4545+- MDM raw reads in parallel (`utils/settings/mdm/rawRead.ts`)
4646+- macOS keychain prefetch (`utils/secureStorage/keychainPrefetch.ts`)
4747+4848+The `preAction` hook loads trust, settings, telemetry gates, MCP prefetch, policy limits, and related startup work before interactive or print mode begins.
4949+5050+## Interactive mode
5151+5252+- `replLauncher.tsx` mounts the Ink/React app.
5353+- `screens/REPL.tsx` owns the main session UI, input queue, model turns, tool execution UI, teammate hooks, voice (when compiled in), and scheduled-task integration.
5454+- `utils/queueProcessor.ts` drains slash commands, bash-mode lines, and batched prompts into `executeInput`.
5555+5656+## Headless / print / SDK-style I/O
5757+5858+- `cli/print.ts` implements structured stdin/stdout loops (`runHeadlessStreaming`, NDJSON-style control).
5959+- `QueryEngine.ts` supports non-REPL paths where messages are submitted programmatically and tool permission context is updated without full UI.
6060+6161+## Tools and MCP
6262+6363+- `tools.ts` aggregates built-in tools (filtered by permission context) and merges MCP-derived tools.
6464+- `services/mcp/` implements config parsing, transports, OAuth, channel permissions, and the in-process MCP client used by `MCPConnectionManager` in the UI.
6565+6666+## Compaction and memory
6767+6868+- `services/compact/` implements context window management aligned with user-facing [context window](https://code.claude.com/docs/en/context-window) and [costs](https://code.claude.com/docs/en/costs) documentation.
6969+7070+## Multi-agent (swarm / teammates)
7171+7272+- `utils/swarm/` contains backends (tmux, iTerm, in-process), spawn utilities, permission sync, and `inProcessRunner.ts` teammate loop.
7373+7474+## IDE integration
7575+7676+- `bridge/` plus hooks such as `hooks/useDiffInIDE.ts` connect to VS Code / JetBrains surfaces described in official [VS Code](https://code.claude.com/docs/en/vs-code) and [JetBrains](https://code.claude.com/docs/en/jetbrains) docs.
7777+7878+## Key files (quick index)
7979+8080+| Path | Role |
8181+| -------------------------------------------------- | ------------------------------------------- |
8282+| `main.tsx` | CLI entry, global options, `preAction` |
8383+| `screens/REPL.tsx` | Interactive session core |
8484+| `query.ts` | Streaming query loop, tool round-trips |
8585+| `QueryEngine.ts` | Headless query submission |
8686+| `cli/print.ts` | Print / stream-json / SDK control transport |
8787+| `tools.ts` / `Tool.ts` | Tool registry and types |
8888+| `services/api/client.ts`, `services/api/claude.ts` | HTTP / streaming API |
8989+| `utils/permissions/` | Permission modes and prompts |
9090+| `services/compact/` | Compaction pipeline |
9191+| `utils/sessionStart.ts` | Session / setup hooks |
9292+9393+See also [Workflows](workflows.md) and the [official docs map](official-docs-map.md).
+30
docs-site/docs/index.md
···11+# Claude Code — recovered source internals
22+33+!!! warning "Proprietary software / leaked reconstruction"
44+This repository contains **reconstructed TypeScript source** from a published npm bundle source map (March 2026). The software is **Anthropic’s proprietary product**. These docs are for **education and architecture study** only. Building or redistributing a competing product may violate law or Anthropic’s terms. This site is **not** official documentation and **not** Anthropic support.
55+66+This documentation maps the **`src/`** tree of the Claude Code CLI to **how the product behaves**, with cross-links to **[official Claude Code documentation](https://code.claude.com/docs/en/overview)**.
77+88+## What Claude Code is (official product)
99+1010+From the [product overview](https://code.claude.com/docs/en/overview):
1111+1212+> Claude Code is an agentic coding tool that reads your codebase, edits files, runs commands, and integrates with your development tools. Available in your terminal, IDE, desktop app, and browser.
1313+1414+The recovered codebase implements primarily the **terminal CLI** surface, plus shared logic for tools, MCP, permissions, compaction, IDE bridge hooks, and related services.
1515+1616+## How to use this site
1717+1818+| Section | Purpose |
1919+| ------------------------------------------- | -------------------------------------------------------------------------------------- |
2020+| [Installation](installation.md) | Build **this documentation** locally; install the **real** Claude Code from Anthropic. |
2121+| [Reproducibility](reproducibility.md) | Why you **cannot** rebuild the shipping npm package from this tree alone. |
2222+| [Architecture](architecture.md) | High-level components and data flow. |
2323+| [Workflows](workflows.md) | Interactive REPL, print/headless, swarm, compaction paths. |
2424+| [Official docs map](official-docs-map.md) | Every indexed doc page ↔ `src/` entry points. |
2525+| [Reference](reference/cli-entry.md) | Deeper dives per subsystem. |
2626+| [Appendix](appendix/directory-structure.md) | Directory layout, tool packages, environment variables. |
2727+2828+## Repository
2929+3030+Source code lives under `src/` in the GitHub repository. The published MkDocs site is built from `docs-site/` via GitHub Actions. After enabling Pages on the `gh-pages` branch, the URL is typically `https://<user>.github.io/<repo>/` (see the root `README.md`).
+36
docs-site/docs/installation.md
···11+# Installation
22+33+!!! warning "Two different things"
44+**A)** Building this **documentation site** (MkDocs) — instructions below.
55+ **B)** Installing **Claude Code** the product — use Anthropic’s official installers only.
66+77+## Install Claude Code (official product)
88+99+Follow the [Claude Code overview](https://code.claude.com/docs/en/overview): native install script, Homebrew, WinGet, VS Code extension, JetBrains plugin, desktop app, or web. This recovered repository **does not** ship a supported way to compile or install the product from source.
1010+1111+## Build this documentation site (local)
1212+1313+Requires Python 3.10+.
1414+1515+```bash
1616+cd docs-site
1717+python3 -m venv .venv
1818+source .venv/bin/activate # Windows: .venv\Scripts\activate
1919+pip install -r requirements.txt
2020+mkdocs serve
2121+```
2222+2323+Open `http://127.0.0.1:8000` to preview.
2424+2525+## Publish (GitHub Pages)
2626+2727+On push to `main`, the workflow `.github/workflows/pages.yml` builds the site and pushes to the `gh-pages` branch (also runs when `README.md` or the workflow file changes).
2828+2929+1. In the GitHub repo: **Settings → Pages → Build and deployment → Branch `gh-pages` / `/ (root)`**.
3030+2. After the first deploy, set `site_url` in `docs-site/mkdocs.yml` to your real Pages URL (e.g. `https://<user>.github.io/<repo>/`) so canonical links and search work correctly. Also update `repo_url` if your fork uses a different owner or name.
3131+3232+The deploy step sets **`enable_jekyll: false`** so GitHub Pages serves static files correctly (adds `.nojekyll`).
3333+3434+## Advanced setup (official)
3535+3636+For system requirements, updates, and uninstallation of the **product**, see [Advanced setup](https://code.claude.com/docs/en/setup) in the official docs.
···11+# API client and OAuth
22+33+**Primary paths:** `src/services/api/`, `src/services/oauth/`, `src/utils/api.ts`, `src/utils/auth.ts`
44+55+`services/api/client.ts` and `claude.ts` implement HTTP and streaming calls to Anthropic APIs (including retries, errors, session ingress, files API, usage, bootstrap). Provider-specific paths (Bedrock, Vertex, Foundry) are gated through auth and endpoint configuration in `utils/aws.ts`, `utils/auth.ts`, and related modules.
66+77+`services/oauth/` implements the browser-based OAuth flow (auth code listener, token exchange, crypto).
88+99+**See also:** [Authentication](https://code.claude.com/docs/en/authentication), [Amazon Bedrock](https://code.claude.com/docs/en/amazon-bedrock), [Google Vertex AI](https://code.claude.com/docs/en/google-vertex-ai).
+11
docs-site/docs/reference/cli-entry.md
···11+# CLI entry and parsing
22+33+**Primary paths:** `src/main.tsx`, `src/cli/*`, `src/commands.ts`
44+55+`main.tsx` registers the `claude` Commander program: global options (model, permissions, worktree, teammate flags, MCP, teleport, etc.), subcommands (MCP, plugins, agents, auth utilities), and a `preAction` hook that runs trust checks, settings load, telemetry initialization, prefetch (MCP URLs, referral, fast mode), and policy gates before any handler executes.
66+77+Side effects at **module top** intentionally run before other imports: startup profiler, MDM subprocess reads (`utils/settings/mdm/rawRead.ts`), and macOS keychain prefetch to overlap I/O with the rest of module evaluation.
88+99+Feature-gated dynamic `require()` loads `coordinator/coordinatorMode.js` when `COORDINATOR_MODE` is true in the Bun bundle, and `assistant/` when `KAIROS` is true.
1010+1111+**See also:** [CLI reference](https://code.claude.com/docs/en/cli-reference), [Architecture](../architecture.md).
+9
docs-site/docs/reference/compaction.md
···11+# Compaction and session memory
22+33+**Primary paths:** `src/services/compact/`, `src/services/SessionMemory/`, `src/utils/tokenBudget.ts`
44+55+Compaction reduces transcript size when approaching context limits: `compact.ts`, `autoCompact.ts`, `microCompact.ts`, `sessionMemoryCompact.ts`, grouping, prompts, and post-compact cleanup. Time-based and API microcompact paths support different strategies.
66+77+Session memory modules add long-lived summaries and structured memory aligned with product behavior described under [memory](https://code.claude.com/docs/en/memory) and [context window](https://code.claude.com/docs/en/context-window).
88+99+**See also:** [Context window](https://code.claude.com/docs/en/context-window), [Costs](https://code.claude.com/docs/en/costs), [Checkpointing](https://code.claude.com/docs/en/checkpointing).
+9
docs-site/docs/reference/lsp.md
···11+# LSP integration
22+33+**Primary paths:** `src/services/lsp/`, `src/tools/LSPTool/`
44+55+`LSPServerManager.ts`, `LSPClient.ts`, and related modules manage language server processes and diagnostics. The agent invokes LSP capabilities through `LSPTool`, which bridges model tool calls to LSP requests.
66+77+Passive feedback and config live alongside the manager (`passiveFeedback.ts`, `config.ts`).
88+99+**See also:** [Tools reference](https://code.claude.com/docs/en/tools-reference) (LSP tool), [Architecture](../architecture.md).
+11
docs-site/docs/reference/mcp.md
···11+# MCP (Model Context Protocol)
22+33+**Primary paths:** `src/services/mcp/`, `src/tools/MCPTool/`, `src/tools/McpAuthTool/`, `src/services/mcp/MCPConnectionManager.tsx`
44+55+The MCP subsystem parses config (files, env expansion, enterprise allowlists), establishes **stdio** and **in-process** transports, handles OAuth for MCP servers, normalizes server metadata, and exposes tools and resources to the model.
66+77+Channel-related files (`channelAllowlist`, `channelNotification`, `channelPermissions`) implement **push** notifications into a session, matching the [Channels](https://code.claude.com/docs/en/channels) documentation.
88+99+The React `MCPConnectionManager` wraps interactive sessions so the REPL can connect/disconnect servers and reflect status in the UI.
1010+1111+**See also:** [MCP](https://code.claude.com/docs/en/mcp), [Channels reference](https://code.claude.com/docs/en/channels-reference).
+9
docs-site/docs/reference/permissions.md
···11+# Permissions and modes
22+33+**Primary paths:** `src/utils/permissions/`, `src/utils/permissions/permissionSetup.ts`, `src/utils/permissions/PermissionMode.ts`
44+55+Permission modes (manual, auto with classifiers, plan-only, etc.) are parsed from CLI flags and settings, then stored in `toolPermissionContext` on app state. Tool execution consults this context before running bash, file writes, MCP calls, etc.
66+77+`permissionSetup.ts` and related modules implement gates for auto mode, dangerous permission stripping, and advisor integration.
88+99+**See also:** [Permissions](https://code.claude.com/docs/en/permissions), [Permission modes](https://code.claude.com/docs/en/permission-modes), [Sandboxing](https://code.claude.com/docs/en/sandboxing).
+9
docs-site/docs/reference/plugins-skills.md
···11+# Plugins and skills
22+33+**Primary paths:** `src/plugins/`, `src/skills/`, `src/utils/plugins/`, `src/utils/skills/`, `src/tools/SkillTool/`, `src/services/plugins/`
44+55+Bundled plugins ship under `plugins/bundled/`; `PluginInstallationManager` and CLI commands under `services/plugins/` support install/update scopes. Skills load from project and user directories; `skillChangeDetector` watches for changes.
66+77+`SkillTool` exposes skill invocation to the model. Hooks and commands defined by plugins align with [Plugins](https://code.claude.com/docs/en/plugins) and [Skills](https://code.claude.com/docs/en/skills).
88+99+**See also:** [Plugins reference](https://code.claude.com/docs/en/plugins-reference), [Discover plugins](https://code.claude.com/docs/en/discover-plugins).
+11
docs-site/docs/reference/print-sdk.md
···11+# Print mode, stream-json, and SDK control
22+33+**Primary paths:** `src/cli/print.ts`, `src/cli/structuredIO.ts`, `src/cli/transports/*`, `src/QueryEngine.ts`
44+55+`print.ts` implements non-interactive execution: structured stdin lines, streaming stdout (including partial messages), tool permission prompts bridged over the protocol, and verbose/debug modes.
66+77+`structuredIO.ts` parses and validates incoming events; transports (`WebSocketTransport`, `SSETransport`, `HybridTransport`, etc.) support remote SDK and CCR-style integrations.
88+99+This corresponds to [Headless](https://code.claude.com/docs/en/headless) and Agent SDK usage documented on the Anthropic platform.
1010+1111+**See also:** [Workflows](../workflows.md), [Query loop](query-engine.md).
+11
docs-site/docs/reference/query-engine.md
···11+# Query loop and streaming
22+33+**Primary paths:** `src/query.ts`, `src/QueryEngine.ts`, `src/utils/processUserInput/`
44+55+`query.ts` defines `queryLoop`, the async generator that drives a single conversation turn: streams assistant content, handles tool calls, merges tool results back into context, and coordinates with compaction and permission checks.
66+77+`QueryEngine.ts` exposes `submitMessage` for **non-interactive** flows: it prepares `processUserInputContext` with `isNonInteractiveSession: true`, runs skill/plugin caches, and streams SDK-style messages—used from headless and SDK control transports.
88+99+Shared input processing (slash commands embedded in prompts, tool permission context updates) lives under `utils/processUserInput/` and related modules.
1010+1111+**See also:** [How Claude Code works](https://code.claude.com/docs/en/how-claude-code-works), [Headless](https://code.claude.com/docs/en/headless).
+13
docs-site/docs/reference/remote-bridge.md
···11+# Remote sessions, teleport, IDE bridge, Chrome
22+33+**Primary paths:** `src/remote/`, `src/utils/teleport/`, `src/utils/deepLink/`, `src/bridge/`, `src/utils/claudeInChrome/`, `src/hooks/useDiffInIDE.ts`
44+55+**Remote / teleport:** `teleport/` handles session bundles, environment selection, and API calls to resume or hand off sessions—aligned with [Remote control](https://code.claude.com/docs/en/remote-control) and web/desktop flows.
66+77+**Deep links:** `deepLink/protocolHandler.ts` parses `claude-cli://` URIs and launches the binary in a terminal with the right cwd/repo context.
88+99+**IDE bridge:** `bridge/` communicates with VS Code and JetBrains extensions (diffs, context). Hooks like `useDiffInIDE.ts` open IDE-native diff UIs when available.
1010+1111+**Chrome:** `claudeInChrome/` implements native messaging and MCP servers for the [Chrome](https://code.claude.com/docs/en/chrome) beta workflow.
1212+1313+**See also:** [VS Code](https://code.claude.com/docs/en/vs-code), [JetBrains](https://code.claude.com/docs/en/jetbrains), [Desktop](https://code.claude.com/docs/en/desktop).
+11
docs-site/docs/reference/repl-ui.md
···11+# REPL and terminal UI
22+33+**Primary paths:** `src/screens/REPL.tsx`, `src/components/`, `src/ink/`, `src/replLauncher.tsx`, `src/interactiveHelpers.tsx`
44+55+The interactive session is a **React + Ink** application. `replLauncher.tsx` mounts the Ink root and wraps the tree with providers for app state, keybindings, MCP connections, and plugin context.
66+77+`REPL.tsx` is large and central: it manages the transcript, loading state, `onQuery` invocations, tool use UI, permission prompts, teammate inbox polling, mailbox bridge, voice integration when `VOICE_MODE` is compiled in, scheduled cron integration, and queue processing between turns.
88+99+`ink/` contains layout primitives, terminal I/O helpers, and event wiring specific to the TUI. `components/` holds feature UI (modals, tool output, plan mode, etc.).
1010+1111+**See also:** [Interactive mode](https://code.claude.com/docs/en/interactive-mode), [Fullscreen](https://code.claude.com/docs/en/fullscreen), [Workflows](../workflows.md).
+11
docs-site/docs/reference/settings-policy.md
···11+# Settings, policy, and remote management
22+33+**Primary paths:** `src/utils/settings/`, `src/services/policyLimits/`, `src/services/remoteManagedSettings/`, `src/schemas/`, `src/migrations/`
44+55+`settings.ts` and `settingsCache.ts` load merged global and project settings. `mdm/` contains macOS managed-device reads. `validation.ts` enforces schema and tool allowlists.
66+77+`policyLimits/` loads enterprise caps (models, spend, features). `remoteManagedSettings/` syncs server-delivered configuration described in [Server-managed settings](https://code.claude.com/docs/en/server-managed-settings).
88+99+`migrations/` upgrades on-disk settings between versions.
1010+1111+**See also:** [Settings](https://code.claude.com/docs/en/settings), [Environment variables](https://code.claude.com/docs/en/env-vars).
+7
docs-site/docs/reference/telemetry.md
···11+# Analytics and telemetry
22+33+**Primary paths:** `src/services/analytics/`, `src/utils/telemetry/`
44+55+Event logging, GrowthBook/feature flags, Datadog and first-party exporters, session tracing (including Perfetto-oriented paths), and plugin/skill load telemetry live here. Analytics respects disable flags and trust gating initialized after user consent.
66+77+**See also:** [Analytics](https://code.claude.com/docs/en/analytics), [Monitoring](https://code.claude.com/docs/en/monitoring-usage).
+11
docs-site/docs/reference/tools.md
···11+# Tools registry and execution
22+33+**Primary paths:** `src/tools.ts`, `src/Tool.ts`, `src/tools/*`, `src/services/tools/`
44+55+`tools.ts` exposes `getTools(permissionContext)` and helpers to merge **built-in** tools with **MCP-derived** tools. Built-ins live as one package per directory under `tools/` (e.g. `BashTool`, `FileReadTool`, `GlobTool`, `WebSearchTool`, `AgentTool`).
66+77+`services/tools/` contains orchestration: `toolExecution.ts`, `StreamingToolExecutor.ts`, `toolHooks.ts`, hooking tool lifecycle into analytics and permission systems.
88+99+Tool schemas and permission requirements align with the public [Tools reference](https://code.claude.com/docs/en/tools-reference); this tree is the implementation of those capabilities.
1010+1111+**See also:** [Tools reference](https://code.claude.com/docs/en/tools-reference), [Appendix: tool packages](../appendix/tool-packages.md).
+11
docs-site/docs/reference/voice-vim-output.md
···11+# Voice, Vim, and output styles
22+33+**Primary paths:** `src/voice/`, `src/vim/`, `src/outputStyles/`, `src/screens/REPL.tsx` (voice hook)
44+55+Voice dictation integrates through `useVoiceIntegration` in `REPL.tsx` when the bundle includes `VOICE_MODE`. `voice/` contains mode and streaming helpers.
66+77+`vim/` implements modal editing for the prompt (motions, operators, text objects) consistent with [Interactive mode](https://code.claude.com/docs/en/interactive-mode) keyboard behavior.
88+99+`outputStyles/` adapts presentation for non-default “output styles” described in the [Output styles](https://code.claude.com/docs/en/output-styles) doc.
1010+1111+**See also:** [Voice dictation](https://code.claude.com/docs/en/voice-dictation), [Keybindings](https://code.claude.com/docs/en/keybindings).
+32
docs-site/docs/reproducibility.md
···11+# Reproducibility and limits
22+33+!!! warning "You cannot rebuild the shipping CLI from this tree alone"
44+This folder is a **source reconstruction**, not a complete open-source project drop.
55+66+## What is missing for a full build
77+88+1. **No root `package.json`**
99+ The published npm package bundles dependencies internally. This repo does not declare versions or scripts to reproduce that bundle.
1010+1111+2. **Bun-specific build features**
1212+ The entry module uses `bun:bundle` APIs such as `feature('KAIROS')`, `feature('COORDINATOR_MODE')`, `feature('VOICE_MODE')`, etc. Those are compile-time gates in Anthropic’s **internal** bundling pipeline, not something you can flip in a stock TypeScript compile.
1313+1414+3. **Private or unpublished packages**
1515+ Imports may reference packages or paths that exist only inside Anthropic’s build graph.
1616+1717+4. **Native addons**
1818+ Some flows (keychain, protocol handlers, optional NAPI modules) assume native binaries shipped beside the real `claude` executable.
1919+2020+## What you _can_ do with this tree
2121+2222+- **Read and trace** control flow: `main.tsx` → REPL or `cli/print.ts` → `query.ts` / `QueryEngine.ts` → `services/api` → tools.
2323+- **Compare behavior** to the public [CLI reference](https://code.claude.com/docs/en/cli-reference) and [how Claude Code works](https://code.claude.com/docs/en/how-claude-code-works).
2424+- **Study** MCP, permissions, compaction, hooks, and IDE bridge code against [official feature docs](https://code.claude.com/docs/en/features-overview).
2525+2626+## “Infrastructure” in the sense of this codebase
2727+2828+There is **no** separate microservice repo here: the CLI is a **single process** (plus child processes for bash, MCP servers, etc.) that talks to **Anthropic’s cloud APIs** and optional **MCP** servers over stdio/WebSocket. Enterprise features (remote-managed settings, policy limits, OAuth) are implemented as **client-side** modules under `src/services/` and `src/utils/settings/`, not as deployable server code in this tree.
2929+3030+## Legal
3131+3232+Rebuilding or redistributing the product for end users is outside the scope of these docs and may infringe Anthropic’s rights. Use this material for **analysis** only unless you have explicit permission.
+77
docs-site/docs/workflows.md
···11+# End-to-end workflows
22+33+!!! warning "Recovered source"
44+Behavior described here is inferred from `src/`; the shipping product may differ by version or build flags.
55+66+## Interactive terminal session
77+88+1. **Process start** — `main.tsx` evaluates side-effect imports (profiler, MDM, keychain prefetch), then parses argv with Commander.
99+2. **`preAction` hook** — Trust dialog state, global config, remote-managed settings, policy limits, GrowthBook/feature flags, OAuth/API key paths, MCP official registry prefetch, plugin initialization, and similar steps run before the subcommand handler.
1010+3. **REPL launch** — `replLauncher.tsx` creates the Ink root and renders providers (`AppState`, keybindings, MCP manager, etc.) and mounts `screens/REPL.tsx`.
1111+4. **Input** — User typing, paste, voice (if `VOICE_MODE`), teammate messages, and task notifications enqueue work.
1212+5. **Queue** — `utils/queueProcessor.ts` dequeues slash commands and bash lines individually; batches other same-mode items and calls `executeInput`.
1313+6. **Query** — `query.ts` `queryLoop` streams model output, schedules tool calls, applies permission checks, and updates transcript state.
1414+7. **Tools** — `services/tools/toolExecution.ts` / `StreamingToolExecutor` and per-tool modules under `tools/*` perform filesystem, shell, web, MCP, and agent operations.
1515+8. **Compaction** — When context limits approach, `services/compact/*` reduces history per compaction policy.
1616+1717+**Official parallels:** [Interactive mode](https://code.claude.com/docs/en/interactive-mode), [How Claude Code works](https://code.claude.com/docs/en/how-claude-code-works).
1818+1919+## Print mode / stream-json / programmatic control
2020+2121+1. **Routing** — `main.tsx` selects the print/headless path instead of the full REPL when `-p` / related flags are used.
2222+2. **Structured I/O** — `cli/structuredIO.ts` parses lines into typed events; `cli/print.ts` `runHeadlessStreaming` runs the async loop that consumes user/control messages and emits stdout messages.
2323+3. **Engine** — `QueryEngine.submitMessage` builds `processUserInputContext` for non-interactive sessions and streams SDK-style messages.
2424+2525+**Official parallels:** [Run Claude Code programmatically](https://code.claude.com/docs/en/headless), [Agent SDK overview](https://platform.claude.com/docs/en/agent-sdk/overview) (external platform docs).
2626+2727+## Teammates / agent teams
2828+2929+1. **Spawn** — Swarm backends (`utils/swarm/backends/*`) create tmux panes, iTerm panes, or in-process runners.
3030+2. **Teammate loop** — `utils/swarm/inProcessRunner.ts` runs a `while` loop: build prompt messages, check compaction/token limits, call into shared query/tool paths, sync permissions via `leaderPermissionBridge`, etc.
3131+3. **REPL integration** — `REPL.tsx` wires `useInboxPoller`, `useMailboxBridge`, and `handleIncomingPrompt` so teammate messages become user turns.
3232+3333+**Official parallels:** [Agent teams](https://code.claude.com/docs/en/agent-teams), [Subagents](https://code.claude.com/docs/en/sub-agents).
3434+3535+## Hooks (user-configured)
3636+3737+1. **Session start** — `utils/sessionStart.ts` `processSessionStartHooks` / `processSetupHooks` run after configuration is known; wired from startup paths in `main.tsx` and related modules.
3838+2. **Per-event hooks** — Additional hook types align with the schema described in the official [Hooks reference](https://code.claude.com/docs/en/hooks); implementation is spread across hook runners and tool lifecycle code.
3939+4040+**Official parallels:** [Hooks guide](https://code.claude.com/docs/en/hooks-guide), [Hooks reference](https://code.claude.com/docs/en/hooks).
4141+4242+## Compaction and context
4343+4444+1. **Triggers** — Token estimation and session memory modules decide when to compact.
4545+2. **Pipeline** — `services/compact/compact.ts`, `autoCompact.ts`, `microCompact.ts`, and related files rewrite or summarize message history.
4646+3. **Post-compact** — Cleanup hooks update UI and storage.
4747+4848+**Official parallels:** [Context window](https://code.claude.com/docs/en/context-window), [Checkpointing](https://code.claude.com/docs/en/checkpointing), [Costs](https://code.claude.com/docs/en/costs).
4949+5050+## MCP and external tools
5151+5252+1. **Config** — `services/mcp/config.ts`, env expansion, enterprise allowlists.
5353+2. **Connection** — `MCPConnectionManager.tsx`, stdio and SDK transports.
5454+3. **Tool surface** — `tools/MCPTool`, `ReadMcpResourceTool`, `ListMcpResourcesTool`, `McpAuthTool`.
5555+5656+**Official parallels:** [MCP](https://code.claude.com/docs/en/mcp), [Channels](https://code.claude.com/docs/en/channels).
5757+5858+## Optional sequence (interactive turn)
5959+6060+```mermaid
6161+sequenceDiagram
6262+ participant User
6363+ participant REPL as REPL.tsx
6464+ participant Queue as queueProcessor
6565+ participant Query as queryLoop
6666+ participant API as services/api
6767+ participant Tool as tools/*
6868+ User->>REPL: input / slash command
6969+ REPL->>Queue: enqueue
7070+ Queue->>REPL: executeInput
7171+ REPL->>Query: onQuery messages
7272+ Query->>API: stream completion
7373+ API-->>Query: tool_use
7474+ Query->>Tool: execute
7575+ Tool-->>Query: result
7676+ Query-->>REPL: update transcript
7777+```