|
| 1 | +# CLAUDE.md |
| 2 | + |
| 3 | +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. |
| 4 | + |
| 5 | +## Project Overview |
| 6 | + |
| 7 | +This is a **reverse-engineered / decompiled** version of Anthropic's official Claude Code CLI tool. The goal is to restore core functionality while trimming secondary capabilities. Many modules are stubbed or feature-flagged off. The codebase has ~1341 tsc errors from decompilation (mostly `unknown`/`never`/`{}` types) — these do **not** block Bun runtime execution. |
| 8 | + |
| 9 | +## Commands |
| 10 | + |
| 11 | +```bash |
| 12 | +# Install dependencies |
| 13 | +bun install |
| 14 | + |
| 15 | +# Dev mode (runs cli.tsx with MACRO defines injected via -d flags) |
| 16 | +bun run dev |
| 17 | + |
| 18 | +# Dev mode with debugger (set BUN_INSPECT=9229 to pick port) |
| 19 | +bun run dev:inspect |
| 20 | + |
| 21 | +# Pipe mode |
| 22 | +echo "say hello" | bun run src/entrypoints/cli.tsx -p |
| 23 | + |
| 24 | +# Build (code splitting, outputs dist/cli.js + ~450 chunk files) |
| 25 | +bun run build |
| 26 | + |
| 27 | +# Test |
| 28 | +bun test # run all tests |
| 29 | +bun test src/utils/__tests__/hash.test.ts # run single file |
| 30 | +bun test --coverage # with coverage report |
| 31 | + |
| 32 | +# Lint & Format (Biome) |
| 33 | +bun run lint # check only |
| 34 | +bun run lint:fix # auto-fix |
| 35 | +bun run format # format all src/ |
| 36 | + |
| 37 | +# Health check |
| 38 | +bun run health |
| 39 | + |
| 40 | +# Check unused exports |
| 41 | +bun run check:unused |
| 42 | + |
| 43 | +# Docs dev server (Mintlify) |
| 44 | +bun run docs:dev |
| 45 | +``` |
| 46 | + |
| 47 | +详细的测试规范、覆盖状态和改进计划见 `docs/testing-spec.md`。 |
| 48 | + |
| 49 | +## Architecture |
| 50 | + |
| 51 | +### Runtime & Build |
| 52 | + |
| 53 | +- **Runtime**: Bun (not Node.js). All imports, builds, and execution use Bun APIs. |
| 54 | +- **Build**: `build.ts` 执行 `Bun.build()` with `splitting: true`,入口 `src/entrypoints/cli.tsx`,输出 `dist/cli.js` + chunk files。默认启用 `AGENT_TRIGGERS_REMOTE` feature。构建后自动替换 `import.meta.require` 为 Node.js 兼容版本(产物 bun/node 都可运行)。 |
| 55 | +- **Dev mode**: `scripts/dev.ts` 通过 Bun `-d` flag 注入 `MACRO.*` defines,运行 `src/entrypoints/cli.tsx`。默认启用 `BUDDY`、`TRANSCRIPT_CLASSIFIER`、`BRIDGE_MODE`、`AGENT_TRIGGERS_REMOTE` 四个 feature。 |
| 56 | +- **Module system**: ESM (`"type": "module"`), TSX with `react-jsx` transform. |
| 57 | +- **Monorepo**: Bun workspaces — internal packages live in `packages/` resolved via `workspace:*`. |
| 58 | +- **Lint/Format**: Biome (`biome.json`)。`bun run lint` / `bun run lint:fix` / `bun run format`。 |
| 59 | +- **Defines**: 集中管理在 `scripts/defines.ts`。当前版本 `2.1.888`。 |
| 60 | + |
| 61 | +### Entry & Bootstrap |
| 62 | + |
| 63 | +1. **`src/entrypoints/cli.tsx`** — True entrypoint。`main()` 函数按优先级处理多条快速路径: |
| 64 | + - `--version` / `-v` — 零模块加载 |
| 65 | + - `--dump-system-prompt` — feature-gated (DUMP_SYSTEM_PROMPT) |
| 66 | + - `--claude-in-chrome-mcp` / `--chrome-native-host` |
| 67 | + - `--daemon-worker=<kind>` — feature-gated (DAEMON) |
| 68 | + - `remote-control` / `rc` / `bridge` — feature-gated (BRIDGE_MODE) |
| 69 | + - `daemon` — feature-gated (DAEMON) |
| 70 | + - `ps` / `logs` / `attach` / `kill` / `--bg` — feature-gated (BG_SESSIONS) |
| 71 | + - `--tmux` + `--worktree` 组合 |
| 72 | + - 默认路径:加载 `main.tsx` 启动完整 CLI |
| 73 | +2. **`src/main.tsx`** (~4680 行) — Commander.js CLI definition。注册大量 subcommands:`mcp` (serve/add/remove/list...)、`server`、`ssh`、`open`、`auth`、`plugin`、`agents`、`auto-mode`、`doctor`、`update` 等。主 `.action()` 处理器负责权限、MCP、会话恢复、REPL/Headless 模式分发。 |
| 74 | +3. **`src/entrypoints/init.ts`** — One-time initialization (telemetry, config, trust dialog)。 |
| 75 | + |
| 76 | +### Core Loop |
| 77 | + |
| 78 | +- **`src/query.ts`** — The main API query function. Sends messages to Claude API, handles streaming responses, processes tool calls, and manages the conversation turn loop. |
| 79 | +- **`src/QueryEngine.ts`** — Higher-level orchestrator wrapping `query()`. Manages conversation state, compaction, file history snapshots, attribution, and turn-level bookkeeping. Used by the REPL screen. |
| 80 | +- **`src/screens/REPL.tsx`** — The interactive REPL screen (React/Ink component). Handles user input, message display, tool permission prompts, and keyboard shortcuts. |
| 81 | + |
| 82 | +### API Layer |
| 83 | + |
| 84 | +- **`src/services/api/claude.ts`** — Core API client. Builds request params (system prompt, messages, tools, betas), calls the Anthropic SDK streaming endpoint, and processes `BetaRawMessageStreamEvent` events. |
| 85 | +- Supports multiple providers: Anthropic direct, AWS Bedrock, Google Vertex, Azure. |
| 86 | +- Provider selection in `src/utils/model/providers.ts`. |
| 87 | + |
| 88 | +### Tool System |
| 89 | + |
| 90 | +- **`src/Tool.ts`** — Tool interface definition (`Tool` type) and utilities (`findToolByName`, `toolMatchesName`). |
| 91 | +- **`src/tools.ts`** — Tool registry. Assembles the tool list; some tools are conditionally loaded via `feature()` flags or `process.env.USER_TYPE`. |
| 92 | +- **`src/tools/<ToolName>/`** — 61 个 tool 目录(如 BashTool, FileEditTool, GrepTool, AgentTool, WebFetchTool, LSPTool, MCPTool 等)。每个 tool 包含 `name`、`description`、`inputSchema`、`call()` 及可选的 React 渲染组件。 |
| 93 | +- **`src/tools/shared/`** — Tool 共享工具函数。 |
| 94 | + |
| 95 | +### UI Layer (Ink) |
| 96 | + |
| 97 | +- **`src/ink.ts`** — Ink render wrapper with ThemeProvider injection. |
| 98 | +- **`src/ink/`** — Custom Ink framework (forked/internal): custom reconciler, hooks (`useInput`, `useTerminalSize`, `useSearchHighlight`), virtual list rendering. |
| 99 | +- **`src/components/`** — 大量 React 组件(170+ 项),渲染于终端 Ink 环境中。关键组件: |
| 100 | + - `App.tsx` — Root provider (AppState, Stats, FpsMetrics) |
| 101 | + - `Messages.tsx` / `MessageRow.tsx` — Conversation message rendering |
| 102 | + - `PromptInput/` — User input handling |
| 103 | + - `permissions/` — Tool permission approval UI |
| 104 | + - `design-system/` — 复用 UI 组件(Dialog, FuzzyPicker, ProgressBar, ThemeProvider 等) |
| 105 | +- Components use React Compiler runtime (`react/compiler-runtime`) — decompiled output has `_c()` memoization calls throughout. |
| 106 | + |
| 107 | +### State Management |
| 108 | + |
| 109 | +- **`src/state/AppState.tsx`** — Central app state type and context provider. Contains messages, tools, permissions, MCP connections, etc. |
| 110 | +- **`src/state/AppStateStore.ts`** — Default state and store factory. |
| 111 | +- **`src/state/store.ts`** — Zustand-style store for AppState (`createStore`). |
| 112 | +- **`src/state/selectors.ts`** — State selectors. |
| 113 | +- **`src/bootstrap/state.ts`** — Module-level singletons for session-global state (session ID, CWD, project root, token counts, model overrides, client type, permission mode). |
| 114 | + |
| 115 | +### Bridge / Remote Control |
| 116 | + |
| 117 | +- **`src/bridge/`** (~35 files) — Remote Control / Bridge 模式。feature-gated by `BRIDGE_MODE`。包含 bridge API、会话管理、JWT 认证、消息传输、权限回调等。Entry: `bridgeMain.ts`。 |
| 118 | +- CLI 快速路径: `claude remote-control` / `claude rc` / `claude bridge`。 |
| 119 | + |
| 120 | +### Daemon Mode |
| 121 | + |
| 122 | +- **`src/daemon/`** — Daemon 模式(长驻 supervisor)。feature-gated by `DAEMON`。包含 `main.ts`(entry)和 `workerRegistry.ts`(worker 管理)。 |
| 123 | + |
| 124 | +### Context & System Prompt |
| 125 | + |
| 126 | +- **`src/context.ts`** — Builds system/user context for the API call (git status, date, CLAUDE.md contents, memory files). |
| 127 | +- **`src/utils/claudemd.ts`** — Discovers and loads CLAUDE.md files from project hierarchy. |
| 128 | + |
| 129 | +### Feature Flag System |
| 130 | + |
| 131 | +Feature flags control which functionality is enabled at runtime: |
| 132 | + |
| 133 | +- **在代码中使用**: 统一通过 `import { feature } from 'bun:bundle'` 导入,调用 `feature('FLAG_NAME')` 返回 `boolean`。**不要**在 `cli.tsx` 或其他文件里自己定义 `feature` 函数或覆盖这个 import。 |
| 134 | +- **启用方式**: 通过环境变量 `FEATURE_<FLAG_NAME>=1`。例如 `FEATURE_BUDDY=1 bun run dev` 启用 BUDDY 功能。 |
| 135 | +- **Dev 默认 features**: `BUDDY`、`TRANSCRIPT_CLASSIFIER`、`BRIDGE_MODE`、`AGENT_TRIGGERS_REMOTE`(见 `scripts/dev.ts`)。 |
| 136 | +- **Build 默认 features**: `AGENT_TRIGGERS_REMOTE`(见 `build.ts`)。 |
| 137 | +- **常见 flag**: `BUDDY`, `DAEMON`, `BRIDGE_MODE`, `BG_SESSIONS`, `PROACTIVE`, `KAIROS`, `VOICE_MODE`, `FORK_SUBAGENT`, `SSH_REMOTE`, `DIRECT_CONNECT`, `TEMPLATES`, `CHICAGO_MCP`, `BYOC_ENVIRONMENT_RUNNER`, `SELF_HOSTED_RUNNER`, `COORDINATOR_MODE`, `UDS_INBOX`, `LODESTONE`, `ABLATION_BASELINE` 等。 |
| 138 | +- **类型声明**: `src/types/internal-modules.d.ts` 中声明了 `bun:bundle` 模块的 `feature` 函数签名。 |
| 139 | + |
| 140 | +**新增功能的正确做法**: 保留 `import { feature } from 'bun:bundle'` + `feature('FLAG_NAME')` 的标准模式,在运行时通过环境变量或配置控制,不要绕过 feature flag 直接 import。 |
| 141 | + |
| 142 | +### Stubbed/Deleted Modules |
| 143 | + |
| 144 | +| Module | Status | |
| 145 | +|--------|--------| |
| 146 | +| Computer Use (`@ant/*`) | Stub packages in `packages/@ant/` | |
| 147 | +| `*-napi` packages (audio, image, url, modifiers) | Stubs in `packages/` (except `color-diff-napi` which is fully implemented) | |
| 148 | +| Analytics / GrowthBook / Sentry | Empty implementations | |
| 149 | +| Magic Docs / Voice Mode / LSP Server | Removed | |
| 150 | +| Plugins / Marketplace | Removed | |
| 151 | +| MCP OAuth | Simplified | |
| 152 | + |
| 153 | +### Key Type Files |
| 154 | + |
| 155 | +- **`src/types/global.d.ts`** — Declares `MACRO`, `BUILD_TARGET`, `BUILD_ENV` and internal Anthropic-only identifiers. |
| 156 | +- **`src/types/internal-modules.d.ts`** — Type declarations for `bun:bundle`, `bun:ffi`, `@anthropic-ai/mcpb`. |
| 157 | +- **`src/types/message.ts`** — Message type hierarchy (UserMessage, AssistantMessage, SystemMessage, etc.). |
| 158 | +- **`src/types/permissions.ts`** — Permission mode and result types. |
| 159 | + |
| 160 | +## Testing |
| 161 | + |
| 162 | +- **框架**: `bun:test`(内置断言 + mock) |
| 163 | +- **单元测试**: 就近放置于 `src/**/__tests__/`,文件名 `<module>.test.ts` |
| 164 | +- **集成测试**: `tests/integration/` — 4 个文件(cli-arguments, context-build, message-pipeline, tool-chain) |
| 165 | +- **共享 mock/fixture**: `tests/mocks/`(api-responses, file-system, fixtures/) |
| 166 | +- **命名**: `describe("functionName")` + `test("behavior description")`,英文 |
| 167 | +- **Mock 模式**: 对重依赖模块使用 `mock.module()` + `await import()` 解锁(必须内联在测试文件中,不能从共享 helper 导入) |
| 168 | +- **当前状态**: ~1623 tests / 114 files (110 unit + 4 integration) / 0 fail(详见 `docs/testing-spec.md`) |
| 169 | + |
| 170 | +## Working with This Codebase |
| 171 | + |
| 172 | +- **Don't try to fix all tsc errors** — they're from decompilation and don't affect runtime. |
| 173 | +- **Feature flags** — 默认全部关闭(`feature()` 返回 `false`)。Dev/build 各有自己的默认启用列表。不要在 `cli.tsx` 中重定义 `feature` 函数。 |
| 174 | +- **React Compiler output** — Components have decompiled memoization boilerplate (`const $ = _c(N)`). This is normal. |
| 175 | +- **`bun:bundle` import** — `import { feature } from 'bun:bundle'` 是 Bun 内置模块,由运行时/构建器解析。不要用自定义函数替代它。 |
| 176 | +- **`src/` path alias** — tsconfig maps `src/*` to `./src/*`. Imports like `import { ... } from 'src/utils/...'` are valid. |
| 177 | +- **MACRO defines** — 集中管理在 `scripts/defines.ts`。Dev mode 通过 `bun -d` 注入,build 通过 `Bun.build({ define })` 注入。修改版本号等常量只改这个文件。 |
| 178 | +- **构建产物兼容 Node.js** — `build.ts` 会自动后处理 `import.meta.require`,产物可直接用 `node dist/cli.js` 运行。 |
| 179 | +- **Biome 配置** — 大量 lint 规则被关闭(decompiled 代码不适合严格 lint)。`.tsx` 文件用 120 行宽 + 强制分号;其他文件 80 行宽 + 按需分号。 |
0 commit comments