Skip to content

Latest commit

 

History

History
263 lines (195 loc) · 16 KB

File metadata and controls

263 lines (195 loc) · 16 KB

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Project Overview

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.

Commands

# Install dependencies
bun install

# Dev mode (runs cli.tsx with MACRO defines injected via -d flags)
bun run dev

# Dev mode with debugger (set BUN_INSPECT=9229 to pick port)
bun run dev:inspect

# Pipe mode
echo "say hello" | bun run src/entrypoints/cli.tsx -p

# Build (code splitting, outputs dist/cli.js + chunk files)
bun run build

# Test
bun test                  # run all tests (2453 tests / 137 files / 0 fail)
bun test src/utils/__tests__/hash.test.ts   # run single file
bun test --coverage       # with coverage report

# Lint & Format (Biome)
bun run lint              # check only
bun run lint:fix          # auto-fix
bun run format            # format all src/

# Health check
bun run health

# Check unused exports
bun run check:unused

# Docs dev server (Mintlify)
bun run docs:dev

详细的测试规范、覆盖状态和改进计划见 docs/testing-spec.md

Architecture

Runtime & Build

  • Runtime: Bun (not Node.js). All imports, builds, and execution use Bun APIs.
  • Build: build.ts 执行 Bun.build() with splitting: true,入口 src/entrypoints/cli.tsx,输出 dist/cli.js + chunk files。Build 默认启用 19 个 feature(见下方 Feature Flag 段)。构建后自动替换 import.meta.require 为 Node.js 兼容版本(产物 bun/node 都可运行)。
  • Dev mode: scripts/dev.ts 通过 Bun -d flag 注入 MACRO.* defines,运行 src/entrypoints/cli.tsx。默认启用全部 feature。
  • Module system: ESM ("type": "module"), TSX with react-jsx transform.
  • Monorepo: Bun workspaces — 14 个 internal packages in packages/ resolved via workspace:*
  • Lint/Format: Biome (biome.json)。bun run lint / bun run lint:fix / bun run format
  • Defines: 集中管理在 scripts/defines.ts。当前版本 2.1.888
  • CI: GitHub Actions — ci.yml(构建+测试)、release-rcs.yml(RCS 发布)、update-contributors.yml(自动更新贡献者)。

Entry & Bootstrap

  1. src/entrypoints/cli.tsx (323 行) — True entrypoint。main() 函数按优先级处理多条快速路径:
    • --version / -v — 零模块加载
    • --dump-system-prompt — feature-gated (DUMP_SYSTEM_PROMPT)
    • --claude-in-chrome-mcp / --chrome-native-host
    • --computer-use-mcp — 独立 MCP server 模式
    • --daemon-worker=<kind> — feature-gated (DAEMON)
    • remote-control / rc / remote / sync / bridge — feature-gated (BRIDGE_MODE)
    • daemon [subcommand] — feature-gated (DAEMON)
    • ps / logs / attach / kill / --bg — feature-gated (BG_SESSIONS)
    • new / list / reply — Template job commands
    • environment-runner / self-hosted-runner — BYOC runner
    • --tmux + --worktree 组合
    • 默认路径:加载 main.tsx 启动完整 CLI
  2. src/main.tsx (~6970 行) — Commander.js CLI definition。注册大量 subcommands:mcp (serve/add/remove/list...)、serversshopenauthpluginagentsauto-modedoctorupdate 等。主 .action() 处理器负责权限、MCP、会话恢复、REPL/Headless 模式分发。
  3. src/entrypoints/init.ts — One-time initialization (telemetry, config, trust dialog)。

Core Loop

  • 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.
  • 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.
  • src/screens/REPL.tsx — The interactive REPL screen (React/Ink component). Handles user input, message display, tool permission prompts, and keyboard shortcuts.

API Layer

  • 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.
  • 7 providers: firstParty (Anthropic direct), bedrock (AWS), vertex (Google Cloud), foundry, openai, gemini, grok (xAI)。
  • Provider selection in src/utils/model/providers.ts。优先级:modelType 参数 > 环境变量 > 默认 firstParty。

Tool System

  • src/Tool.ts — Tool interface definition (Tool type) and utilities (findToolByName, toolMatchesName).
  • src/tools.ts (387 行) — Tool registry. Assembles the tool list; some tools are conditionally loaded via feature() flags or process.env.USER_TYPE.
  • src/tools/<ToolName>/ — 55 个 tool 目录。主要分类:
    • 文件操作: FileEditTool, FileReadTool, FileWriteTool, GlobTool, GrepTool
    • Shell/执行: BashTool, PowerShellTool, REPLTool
    • Agent 系统: AgentTool, TaskCreateTool, TaskUpdateTool, TaskListTool, TaskGetTool
    • 规划: EnterPlanModeTool, ExitPlanModeV2Tool, VerifyPlanExecutionTool
    • Web/MCP: WebFetchTool, WebSearchTool, MCPTool, McpAuthTool
    • 调度: CronCreateTool, CronDeleteTool, CronListTool
    • 其他: LSPTool, ConfigTool, SkillTool, EnterWorktreeTool, ExitWorktreeTool 等
  • src/tools/shared/ — Tool 共享工具函数。

UI Layer (Ink)

  • src/ink.ts — Ink render wrapper with ThemeProvider injection.
  • packages/@ant/ink/ — Custom Ink framework(forked/internal),包含 components、core、hooks、keybindings、theme、utils。注意:不是 src/ink/
  • src/components/ — 149 个组件目录/文件,渲染于终端 Ink 环境中。关键组件:
    • App.tsx — Root provider (AppState, Stats, FpsMetrics)
    • Messages.tsx / MessageRow.tsx — Conversation message rendering
    • PromptInput/ — User input handling
    • permissions/ — Tool permission approval UI
    • design-system/ — 复用 UI 组件(Dialog, FuzzyPicker, ProgressBar, ThemeProvider 等)
  • Components use React Compiler runtime (react/compiler-runtime) — decompiled output has _c() memoization calls throughout.

State Management

  • src/state/AppState.tsx — Central app state type and context provider. Contains messages, tools, permissions, MCP connections, etc.
  • src/state/AppStateStore.ts — Default state and store factory.
  • src/state/store.ts — Zustand-style store for AppState (createStore).
  • src/state/selectors.ts — State selectors.
  • src/bootstrap/state.ts — Module-level singletons for session-global state (session ID, CWD, project root, token counts, model overrides, client type, permission mode).

Workspace Packages

Package 说明
packages/@ant/ink/ Forked Ink 框架(components、hooks、keybindings、theme)
packages/@ant/computer-use-mcp/ Computer Use MCP server(截图/键鼠/剪贴板/应用管理)
packages/@ant/computer-use-input/ 键鼠模拟(dispatcher + darwin/win32/linux backend)
packages/@ant/computer-use-swift/ 截图 + 应用管理(dispatcher + per-platform backend)
packages/@ant/claude-for-chrome-mcp/ Chrome 浏览器控制(通过 --chrome 启用)
packages/remote-control-server/ 自托管 Remote Control Server(Docker 部署,含 Web UI)
packages/swarm/ Swarm 解耦模块
packages/shell/ Shell 抽象
packages/audio-capture-napi/ 原生音频捕获(已恢复)
packages/color-diff-napi/ 颜色差异计算(完整实现,11 tests)
packages/image-processor-napi/ 图像处理(已恢复)
packages/modifiers-napi/ 键盘修饰键检测(stub)
packages/url-handler-napi/ URL scheme 处理(stub)

Bridge / Remote Control

  • src/bridge/ (~37 files) — Remote Control / Bridge 模式。feature-gated by BRIDGE_MODE。包含 bridge API、会话管理、JWT 认证、消息传输、权限回调等。Entry: bridgeMain.ts
  • packages/remote-control-server/ — 自托管 RCS,支持 Docker 部署,含 Web UI 控制面板。通过 bun run rcs 启动。
  • CLI 快速路径: claude remote-control / claude rc / claude bridge
  • 详见 docs/features/remote-control-self-hosting.md

Daemon Mode

  • src/daemon/ — Daemon 模式(长驻 supervisor)。feature-gated by DAEMON。包含 main.ts(entry)和 workerRegistry.ts(worker 管理)。

Context & System Prompt

  • src/context.ts — Builds system/user context for the API call (git status, date, CLAUDE.md contents, memory files).
  • src/utils/claudemd.ts — Discovers and loads CLAUDE.md files from project hierarchy.

Feature Flag System

Feature flags control which functionality is enabled at runtime. 代码中统一通过 import { feature } from 'bun:bundle' 导入,调用 feature('FLAG_NAME') 返回 boolean

启用方式: 环境变量 FEATURE_<FLAG_NAME>=1。例如 FEATURE_BUDDY=1 bun run dev

Build 默认 features(19 个,见 build.ts):

  • 基础: BUDDY, TRANSCRIPT_CLASSIFIER, BRIDGE_MODE, AGENT_TRIGGERS_REMOTE, CHICAGO_MCP, VOICE_MODE
  • 统计/缓存: SHOT_STATS, PROMPT_CACHE_BREAK_DETECTION, TOKEN_BUDGET
  • P0 本地: AGENT_TRIGGERS, ULTRATHINK, BUILTIN_EXPLORE_PLAN_AGENTS, LODESTONE
  • P1 API 依赖: EXTRACT_MEMORIES, VERIFICATION_AGENT, KAIROS_BRIEF, AWAY_SUMMARY, ULTRAPLAN
  • P2: DAEMON

Dev mode 默认: 全部启用(见 scripts/dev.ts)。

类型声明: src/types/internal-modules.d.ts 中声明了 bun:bundle 模块的 feature 函数签名。

新增功能的正确做法: 保留 import { feature } from 'bun:bundle' + feature('FLAG_NAME') 的标准模式,在运行时通过环境变量或配置控制,不要绕过 feature flag 直接 import。

Multi-API 兼容层

所有兼容层均采用流适配器模式:将第三方 API 格式转为 Anthropic 内部格式,下游代码完全不改。

OpenAI 兼容层

通过 CLAUDE_CODE_USE_OPENAI=1 启用,支持 Ollama/DeepSeek/vLLM 等任意 OpenAI Chat Completions 协议端点。含 DeepSeek thinking mode 支持。

  • src/services/api/openai/ — client、消息/工具转换、流适配、模型映射
  • 关键环境变量:CLAUDE_CODE_USE_OPENAIOPENAI_API_KEYOPENAI_BASE_URLOPENAI_MODEL

Gemini 兼容层

通过 CLAUDE_CODE_USE_GEMINI=1 启用。独立环境变量体系。

  • src/services/api/gemini/ — client、模型映射、类型定义
  • 关键环境变量:GEMINI_API_KEY(必填)、GEMINI_MODEL(直接指定)、GEMINI_DEFAULT_SONNET_MODEL/GEMINI_DEFAULT_OPUS_MODEL(按能力映射)
  • 模型映射优先级:GEMINI_MODEL > GEMINI_DEFAULT_*_MODEL > ANTHROPIC_DEFAULT_*_MODEL(已废弃) > 原样返回

Grok 兼容层

通过 CLAUDE_CODE_USE_GROK=1 启用。自定义模型映射支持 xAI Grok API。

  • src/services/api/grok/ — client、模型映射

详见各兼容层的 docs 文档。

Stubbed/Deleted Modules

Module Status
Computer Use (@ant/*) Restored — macOS + Windows + Linux(后端完整度不一)
*-napi packages audio-capture-napiimage-processor-napi 已恢复;color-diff-napi 完整;modifiers-napiurl-handler-napi 仍为 stub
Voice Mode Restored — Push-to-Talk 语音输入(需 Anthropic OAuth)
OpenAI/Gemini/Grok 兼容层 Restored
Remote Control Server Restored — 自托管 RCS + Web UI
Analytics / GrowthBook / Sentry Empty implementations
Magic Docs / LSP Server Removed
Plugins / Marketplace Removed
MCP OAuth Simplified

Key Type Files

  • src/types/global.d.ts — Declares MACRO, BUILD_TARGET, BUILD_ENV and internal Anthropic-only identifiers.
  • src/types/internal-modules.d.ts — Type declarations for bun:bundle, bun:ffi, @anthropic-ai/mcpb.
  • src/types/message.ts — Message type hierarchy (UserMessage, AssistantMessage, SystemMessage, etc.).
  • src/types/permissions.ts — Permission mode and result types.

Testing

  • 框架: bun:test(内置断言 + mock)
  • 当前状态: 2453 tests / 137 files / 0 fail / 4015 expect() calls
  • 单元测试: 就近放置于 src/**/__tests__/,文件名 <module>.test.ts
  • 集成测试: tests/integration/ — 4 个文件(cli-arguments, context-build, message-pipeline, tool-chain)
  • 共享 mock/fixture: tests/mocks/(api-responses, file-system, fixtures/)
  • 命名: describe("functionName") + test("behavior description"),英文
  • Mock 模式: 对重依赖模块使用 mock.module() + await import() 解锁(必须内联在测试文件中,不能从共享 helper 导入)
  • 包测试: packages/ 下各包也有独立测试(如 color-diff-napi 11 tests)

Working with This Codebase

  • Don't try to fix all tsc errors — they're from decompilation and don't affect runtime.
  • Feature flags — 默认全部关闭(feature() 返回 false)。Dev/build 各有自己的默认启用列表。不要在 cli.tsx 中重定义 feature 函数。
  • React Compiler output — Components have decompiled memoization boilerplate (const $ = _c(N)). This is normal.
  • bun:bundle importimport { feature } from 'bun:bundle' 是 Bun 内置模块,由运行时/构建器解析。不要用自定义函数替代它。
  • src/ path alias — tsconfig maps src/* to ./src/*. Imports like import { ... } from 'src/utils/...' are valid.
  • MACRO defines — 集中管理在 scripts/defines.ts。Dev mode 通过 bun -d 注入,build 通过 Bun.build({ define }) 注入。修改版本号等常量只改这个文件。
  • 构建产物兼容 Node.jsbuild.ts 会自动后处理 import.meta.require,产物可直接用 node dist/cli.js 运行。
  • Biome 配置 — 大量 lint 规则被关闭(decompiled 代码不适合严格 lint)。.tsx 文件用 120 行宽 + 强制分号;其他文件 80 行宽 + 按需分号。
  • Ink 框架在 packages/@ant/ink/ — 不是 src/ink/(该目录不存在)。Ink 相关的组件、hooks、keybindings 都在 packages 中。
  • Provider 优先级modelType 参数 > 环境变量 > 默认 firstParty。新增 provider 需在 src/utils/model/providers.ts 注册。

Type Safety Guidelines

本代码库经过系统性类型修复,已消除非测试代码中的所有 as any。后续开发应遵守以下规则:

  • 禁止在非测试代码中使用 as any — 测试文件中 as any 用于 mock 数据是可以接受的。生产代码中如果遇到类型不匹配,优先用以下方式解决:
    • 补充缺失的类型声明或 interface
    • 使用 as unknown as SpecificType 双重断言(比 as any 安全,至少表达了目标类型)
    • 使用 Record<string, unknown> 替代 any 访问未知结构的对象
    • 用类型守卫(type guard)收窄联合类型
  • msg.request 模式 — SDK control request 的某些子类型不在 Zod schema 中,访问其属性时使用 const req = msg.request as Record<string, unknown> 然后通过 req.propertyName as string 访问。
  • Ink 颜色类型 — Text 组件的 color prop 是有限联合类型,需要强转时用 as keyof Theme 而非 as any
  • API 兼容层类型 — OpenAI/Gemini/Grok 兼容层的 stream、request body、error 等使用对应的 SDK 类型(如 ChatCompletionChunkChatCompletionCreateParamsStreaming),已在各 index.ts 中导入。
  • Transport 消息类型 — Bridge 的 transport.write() / transport.writeBatch() 使用 StdoutMessage 类型,已在 src/bridge/ 中导入。