From e627a9388dcbbbf65349ed2300e76542ec5f1734 Mon Sep 17 00:00:00 2001 From: Roger Date: Wed, 1 Apr 2026 07:41:38 +0800 Subject: [PATCH] restructure: move docs to docs/, rewrite README in English - Move all .md documentation into docs/ directory - Rewrite README.md with English documentation covering: - All 22 missing source stubs added - Source code fixes (useEffectEvent, version check, auth, sandbox-runtime) - Bun compatibility shims (macro, bun-bundle) - 28 missing npm dependencies - Build and run instructions - Remove dist/ from tracking (users compile themselves) --- README.md | 365 ++++++--------- docs/API-CONFIG.md | 439 ++++++++++++++++++ .../ARCHITECTURE-BRIDGE-REMOTE.md | 0 .../ARCHITECTURE-COMMANDS.md | 0 .../ARCHITECTURE-COMPONENTS.md | 0 .../ARCHITECTURE-SERVICES.md | 0 .../ARCHITECTURE-TOOLS.md | 0 .../ARCHITECTURE-UTILS.md | 0 ARCHITECTURE.md => docs/ARCHITECTURE.md | 0 BUILD.md => docs/BUILD.md | 13 +- .../REFACTORING-ASSESSMENT.md | 0 11 files changed, 590 insertions(+), 227 deletions(-) create mode 100644 docs/API-CONFIG.md rename ARCHITECTURE-BRIDGE-REMOTE.md => docs/ARCHITECTURE-BRIDGE-REMOTE.md (100%) rename ARCHITECTURE-COMMANDS.md => docs/ARCHITECTURE-COMMANDS.md (100%) rename ARCHITECTURE-COMPONENTS.md => docs/ARCHITECTURE-COMPONENTS.md (100%) rename ARCHITECTURE-SERVICES.md => docs/ARCHITECTURE-SERVICES.md (100%) rename ARCHITECTURE-TOOLS.md => docs/ARCHITECTURE-TOOLS.md (100%) rename ARCHITECTURE-UTILS.md => docs/ARCHITECTURE-UTILS.md (100%) rename ARCHITECTURE.md => docs/ARCHITECTURE.md (100%) rename BUILD.md => docs/BUILD.md (97%) rename REFACTORING-ASSESSMENT.md => docs/REFACTORING-ASSESSMENT.md (100%) diff --git a/README.md b/README.md index 45db43e..6419a6e 100644 --- a/README.md +++ b/README.md @@ -1,257 +1,172 @@ -# Claude Code — Leaked Source (2026-03-31) +# Claude Code — Compiled & Fixed -> **On March 31, 2026, the full source code of Anthropic's Claude Code CLI was leaked** via a `.map` file exposed in their npm registry. +A working, buildable version of the [Claude Code](https://github.com/anthropics/claude-code) CLI, reconstructed from the leaked source (2026-03-31) with all missing files, broken imports, and runtime errors fixed. --- -## How It Leaked +## What This Is -[Chaofan Shou (@Fried_rice)](https://x.com/Fried_rice) discovered the leak and posted it publicly: +On March 31, 2026, the full source code of Anthropic's Claude Code CLI was leaked via a `.map` file in their npm registry. The original leak is **not buildable** — it's missing 22+ source files, has broken internal imports, uses Anthropic-internal packages, and relies on unreleased Bun features (`bun:bundle`). -> **"Claude code source code has been leaked via a map file in their npm registry!"** -> -> — [@Fried_rice, March 31, 2026](https://x.com/Fried_rice/status/2038894956459290963) - -The source map file in the published npm package contained a reference to the full, unobfuscated TypeScript source, which was downloadable as a zip archive from Anthropic's R2 storage bucket. +This repo fixes all of that. The result: a single `bun build` command that produces a working ~23MB bundle. --- -## Overview +## Changes From the Original Leak -Claude Code is Anthropic's official CLI tool that lets you interact with Claude directly from the terminal to perform software engineering tasks — editing files, running commands, searching codebases, managing git workflows, and more. +### Missing Source Files Added (22 stubs) -This repository contains the leaked `src/` directory. +The leaked source references files that don't exist in the package. These have been created as functional stubs: -- **Leaked on**: 2026-03-31 -- **Language**: TypeScript -- **Runtime**: Bun -- **Terminal UI**: React + [Ink](https://github.com/vadimdemedes/ink) (React for CLI) -- **Scale**: ~1,900 files, 512,000+ lines of code +| File | Purpose | +|------|---------| +| `src/global.d.ts` | TypeScript global declarations | +| `src/utils/protectedNamespace.ts` | Namespace protection | +| `src/utils/useEffectEvent.ts` | React `useEffectEvent` polyfill | +| `src/entrypoints/sdk/coreTypes.generated.ts` | SDK generated types | +| `src/entrypoints/sdk/runtimeTypes.ts` | SDK runtime types | +| `src/entrypoints/sdk/toolTypes.ts` | SDK tool types | +| `src/tools/REPLTool/REPLTool.ts` | REPL tool stub | +| `src/tools/SuggestBackgroundPRTool/` | PR suggestion stub | +| `src/tools/VerifyPlanExecutionTool/` | Plan verification stub | +| `src/tools/WorkflowTool/` | Workflow tool stub | +| `src/tools/TungstenTool/TungstenLiveMonitor.tsx` | Tungsten monitor stub | +| `src/commands/agents-platform/` | Agent platform command stub | +| `src/commands/assistant/` | Assistant command stub | +| `src/components/agents/SnapshotUpdateDialog.tsx` | Snapshot dialog stub | +| `src/assistant/AssistantSessionChooser.tsx` | Session chooser stub | +| `src/services/compact/snipCompact.ts` | Snip compact stub | +| `src/services/compact/cachedMicrocompact.ts` | Microcompact stub | +| `src/services/contextCollapse/` | Context collapse stub | +| `src/ink/devtools.ts` | Devtools stub | +| `src/skills/bundled/verify/` | Verify skill stub | +| `src/utils/filePersistence/types.ts` | File persistence types stub | + +### Source Code Fixes + +| Fix | File(s) | Description | +|-----|---------|---------| +| `useEffectEvent` import | `src/components/tasks/BackgroundTasksDialog.tsx`, `src/state/AppState.tsx` | React 19 experimental hook not available in `react-reconciler@0.31` — moved to local polyfill | +| Version check skip | `src/utils/autoUpdater.ts` | `assertMinVersion()` calls Anthropic servers — bypassed | +| Org validation skip | `src/main.tsx` | `validateForceLoginOrg()` requires Anthropic auth — commented out | +| Auth check skip | `src/main.tsx` | Login flow requires Anthropic OAuth — auto-execute enabled | +| `SandboxManager` stub | `node_modules/@anthropic-ai/sandbox-runtime/` | Replaced minimal 14-method stub with real implementation from [anthropic-experimental/sandbox-runtime](https://github.com/anthropic-experimental/sandbox-runtime) | + +### Shim Files (Bun compatibility) + +| File | Purpose | +|------|---------| +| `shims/macro.ts` | Provides `MACRO` global (VERSION, BUILD_TIME, etc.) — normally injected by Anthropic's Bun build | +| `shims/bun-bundle.ts` | Provides `feature()` function stub — replaces `bun:bundle` which is Anthropic-internal | + +### Missing Dependencies (28 packages added) + +The original `package.json` was incomplete. 28 missing dependencies have been added, including `@anthropic-ai/` SDKs, OpenTelemetry packages, and other required modules. + +### Internal Package Stubs + +Two Anthropic-internal packages that can't be installed from npm: + +- `@anthropic-ai/sandbox-runtime` — replaced with [real open-source implementation](https://github.com/anthropic-experimental/sandbox-runtime) +- `@ant/claude-for-chrome-mcp` — stubbed in `node_modules/` --- -## Directory Structure +## Quick Start +### Prerequisites + +- **Bun** 1.3+ — `curl -fsSL https://bun.sh/install | bash` +- **Node.js** 18+ (optional, Bun includes npm) + +### Build + +```bash +git clone git@github.com:roger2ai/Claude-Code-Compiled.git +cd Claude-Code-Compiled + +# Install dependencies +bun install + +# Patch Commander.js (multi-char short flags not supported upstream) +# See docs/BUILD.md §4.1 for details — needs re-apply after bun install + +# Build +bun build shims/macro.ts src/main.tsx --target=bun --outdir=./dist + +# Bundle into single file +cat dist/shims/macro.js dist/src/main.js > dist/bundle.js +echo 'if (typeof main === "function") main().catch(e => { console.error(e); process.exit(1); });' >> dist/bundle.js ``` -src/ -├── main.tsx # Entrypoint (Commander.js-based CLI parser) -├── commands.ts # Command registry -├── tools.ts # Tool registry -├── Tool.ts # Tool type definitions -├── QueryEngine.ts # LLM query engine (core Anthropic API caller) -├── context.ts # System/user context collection -├── cost-tracker.ts # Token cost tracking -│ -├── commands/ # Slash command implementations (~50) -├── tools/ # Agent tool implementations (~40) -├── components/ # Ink UI components (~140) -├── hooks/ # React hooks -├── services/ # External service integrations -├── screens/ # Full-screen UIs (Doctor, REPL, Resume) -├── types/ # TypeScript type definitions -├── utils/ # Utility functions -│ -├── bridge/ # IDE integration bridge (VS Code, JetBrains) -├── coordinator/ # Multi-agent coordinator -├── plugins/ # Plugin system -├── skills/ # Skill system -├── keybindings/ # Keybinding configuration -├── vim/ # Vim mode -├── voice/ # Voice input -├── remote/ # Remote sessions -├── server/ # Server mode -├── memdir/ # Memory directory (persistent memory) -├── tasks/ # Task management -├── state/ # State management -├── migrations/ # Config migrations -├── schemas/ # Config schemas (Zod) -├── entrypoints/ # Initialization logic -├── ink/ # Ink renderer wrapper -├── buddy/ # Companion sprite (Easter egg) -├── native-ts/ # Native TypeScript utils -├── outputStyles/ # Output styling -├── query/ # Query pipeline -└── upstreamproxy/ # Proxy configuration + +Output: `dist/bundle.js` (~23 MB, ~5,750 modules, ~300ms build time) + +### Run + +```bash +# Help (no API key needed) +bun dist/bundle.js --help + +# Interactive REPL (requires real terminal + API key) +export ANTHROPIC_API_KEY=your-key +bun dist/bundle.js + +# One-shot mode +bun dist/bundle.js -p "say hello" ``` --- -## Core Architecture +## Project Structure -### 1. Tool System (`src/tools/`) - -Every tool Claude Code can invoke is implemented as a self-contained module. Each tool defines its input schema, permission model, and execution logic. - -| Tool | Description | -|---|---| -| `BashTool` | Shell command execution | -| `FileReadTool` | File reading (images, PDFs, notebooks) | -| `FileWriteTool` | File creation / overwrite | -| `FileEditTool` | Partial file modification (string replacement) | -| `GlobTool` | File pattern matching search | -| `GrepTool` | ripgrep-based content search | -| `WebFetchTool` | Fetch URL content | -| `WebSearchTool` | Web search | -| `AgentTool` | Sub-agent spawning | -| `SkillTool` | Skill execution | -| `MCPTool` | MCP server tool invocation | -| `LSPTool` | Language Server Protocol integration | -| `NotebookEditTool` | Jupyter notebook editing | -| `TaskCreateTool` / `TaskUpdateTool` | Task creation and management | -| `SendMessageTool` | Inter-agent messaging | -| `TeamCreateTool` / `TeamDeleteTool` | Team agent management | -| `EnterPlanModeTool` / `ExitPlanModeTool` | Plan mode toggle | -| `EnterWorktreeTool` / `ExitWorktreeTool` | Git worktree isolation | -| `ToolSearchTool` | Deferred tool discovery | -| `CronCreateTool` | Scheduled trigger creation | -| `RemoteTriggerTool` | Remote trigger | -| `SleepTool` | Proactive mode wait | -| `SyntheticOutputTool` | Structured output generation | - -### 2. Command System (`src/commands/`) - -User-facing slash commands invoked with `/` prefix. - -| Command | Description | -|---|---| -| `/commit` | Create a git commit | -| `/review` | Code review | -| `/compact` | Context compression | -| `/mcp` | MCP server management | -| `/config` | Settings management | -| `/doctor` | Environment diagnostics | -| `/login` / `/logout` | Authentication | -| `/memory` | Persistent memory management | -| `/skills` | Skill management | -| `/tasks` | Task management | -| `/vim` | Vim mode toggle | -| `/diff` | View changes | -| `/cost` | Check usage cost | -| `/theme` | Change theme | -| `/context` | Context visualization | -| `/pr_comments` | View PR comments | -| `/resume` | Restore previous session | -| `/share` | Share session | -| `/desktop` | Desktop app handoff | -| `/mobile` | Mobile app handoff | - -### 3. Service Layer (`src/services/`) - -| Service | Description | -|---|---| -| `api/` | Anthropic API client, file API, bootstrap | -| `mcp/` | Model Context Protocol server connection and management | -| `oauth/` | OAuth 2.0 authentication flow | -| `lsp/` | Language Server Protocol manager | -| `analytics/` | GrowthBook-based feature flags and analytics | -| `plugins/` | Plugin loader | -| `compact/` | Conversation context compression | -| `policyLimits/` | Organization policy limits | -| `remoteManagedSettings/` | Remote managed settings | -| `extractMemories/` | Automatic memory extraction | -| `tokenEstimation.ts` | Token count estimation | -| `teamMemorySync/` | Team memory synchronization | - -### 4. Bridge System (`src/bridge/`) - -A bidirectional communication layer connecting IDE extensions (VS Code, JetBrains) with the Claude Code CLI. - -- `bridgeMain.ts` — Bridge main loop -- `bridgeMessaging.ts` — Message protocol -- `bridgePermissionCallbacks.ts` — Permission callbacks -- `replBridge.ts` — REPL session bridge -- `jwtUtils.ts` — JWT-based authentication -- `sessionRunner.ts` — Session execution management - -### 5. Permission System (`src/hooks/toolPermission/`) - -Checks permissions on every tool invocation. Either prompts the user for approval/denial or automatically resolves based on the configured permission mode (`default`, `plan`, `bypassPermissions`, `auto`, etc.). - -### 6. Feature Flags - -Dead code elimination via Bun's `bun:bundle` feature flags: - -```typescript -import { feature } from 'bun:bundle' - -// Inactive code is completely stripped at build time -const voiceCommand = feature('VOICE_MODE') - ? require('./commands/voice/index.js').default - : null +``` +claude-code/ +├── src/ # Source (~1,900 TypeScript files, 512K+ lines) +│ ├── main.tsx # CLI entrypoint +│ ├── QueryEngine.ts # LLM query engine +│ ├── Tool.ts # Tool type definitions +│ ├── tools/ # 43 tool implementations +│ ├── commands/ # 80+ slash commands +│ ├── components/ # 346 React/Ink UI components +│ ├── services/ # 21 service modules +│ ├── screens/ # Full-screen UIs (REPL, Doctor, etc.) +│ └── utils/ # 290+ utility files +├── shims/ # Bun compatibility shims +├── docs/ # Architecture & build documentation +├── dist/ # Build output (gitignored) +└── package.json # Dependencies (574 packages) ``` -Notable flags: `PROACTIVE`, `KAIROS`, `BRIDGE_MODE`, `DAEMON`, `VOICE_MODE`, `AGENT_TRIGGERS`, `MONITOR_TOOL` +--- + +## Documentation + +| Document | Content | +|----------|---------| +| [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | Full architecture overview | +| [docs/ARCHITECTURE-TOOLS.md](docs/ARCHITECTURE-TOOLS.md) | 43 tool implementations | +| [docs/ARCHITECTURE-SERVICES.md](docs/ARCHITECTURE-SERVICES.md) | 21 service modules | +| [docs/ARCHITECTURE-COMPONENTS.md](docs/ARCHITECTURE-COMPONENTS.md) | 346 UI components | +| [docs/ARCHITECTURE-COMMANDS.md](docs/ARCHITECTURE-COMMANDS.md) | Commands, skills, plugins | +| [docs/ARCHITECTURE-UTILS.md](docs/ARCHITECTURE-UTILS.md) | Utility layer | +| [docs/ARCHITECTURE-BRIDGE-REMOTE.md](docs/ARCHITECTURE-BRIDGE-REMOTE.md) | IDE bridge & remote sessions | +| [docs/API-CONFIG.md](docs/API-CONFIG.md) | API configuration (env vars, auth, proxies) | +| [docs/BUILD.md](docs/BUILD.md) | Detailed build guide & all patches | +| [docs/REFACTORING-ASSESSMENT.md](docs/REFACTORING-ASSESSMENT.md) | Refactoring feasibility analysis | --- -## Key Files in Detail +## Known Limitations -### `QueryEngine.ts` (~46K lines) - -The core engine for LLM API calls. Handles streaming responses, tool-call loops, thinking mode, retry logic, and token counting. - -### `Tool.ts` (~29K lines) - -Defines base types and interfaces for all tools — input schemas, permission models, and progress state types. - -### `commands.ts` (~25K lines) - -Manages registration and execution of all slash commands. Uses conditional imports to load different command sets per environment. - -### `main.tsx` - -Commander.js-based CLI parser + React/Ink renderer initialization. At startup, parallelizes MDM settings, keychain prefetch, and GrowthBook initialization for faster boot. +1. **TUI requires a real terminal** — silent exit in pipes or non-TTY environments +2. **API key required** — `ANTHROPIC_API_KEY` must be set for actual queries +3. **Some tools are stubs** — REPLTool, WorkflowTool, etc. have empty implementations +4. **macOS Keychain** — falls back to plaintext file on Linux +5. **Sandbox on WSL2** — requires `apt install bubblewrap socat` for sandbox features +6. **Commander.js patch** — multi-character short flags (`-d2e`) need a manual patch to `node_modules` after each `bun install` --- -## Tech Stack +## Original Source -| Category | Technology | -|---|---| -| Runtime | [Bun](https://bun.sh) | -| Language | TypeScript (strict) | -| Terminal UI | [React](https://react.dev) + [Ink](https://github.com/vadimdemedes/ink) | -| CLI Parsing | [Commander.js](https://github.com/tj/commander.js) (extra-typings) | -| Schema Validation | [Zod v4](https://zod.dev) | -| Code Search | [ripgrep](https://github.com/BurntSushi/ripgrep) (via GrepTool) | -| Protocols | [MCP SDK](https://modelcontextprotocol.io), LSP | -| API | [Anthropic SDK](https://docs.anthropic.com) | -| Telemetry | OpenTelemetry + gRPC | -| Feature Flags | GrowthBook | -| Auth | OAuth 2.0, JWT, macOS Keychain | - ---- - -## Notable Design Patterns - -### Parallel Prefetch - -Startup time is optimized by prefetching MDM settings, keychain reads, and API preconnect in parallel — before heavy module evaluation begins. - -```typescript -// main.tsx — fired as side-effects before other imports -startMdmRawRead() -startKeychainPrefetch() -``` - -### Lazy Loading - -Heavy modules (OpenTelemetry ~400KB, gRPC ~700KB) are deferred via dynamic `import()` until actually needed. - -### Agent Swarms - -Sub-agents are spawned via `AgentTool`, with `coordinator/` handling multi-agent orchestration. `TeamCreateTool` enables team-level parallel work. - -### Skill System - -Reusable workflows defined in `skills/` and executed through `SkillTool`. Users can add custom skills. - -### Plugin Architecture - -Built-in and third-party plugins are loaded through the `plugins/` subsystem. - ---- - -## Disclaimer - -This repository archives source code that was leaked from Anthropic's npm registry on **2026-03-31**. All original source code is the property of [Anthropic](https://www.anthropic.com). +Leaked by [@Fried_rice](https://x.com/Fried_rice) on 2026-03-31. All original source code is the property of [Anthropic](https://www.anthropic.com). This repo exists solely as a compilable reference — not for production use. diff --git a/docs/API-CONFIG.md b/docs/API-CONFIG.md new file mode 100644 index 0000000..49c4330 --- /dev/null +++ b/docs/API-CONFIG.md @@ -0,0 +1,439 @@ +# Claude Code API 配置指南 + +> 基于 2026-03-31 泄露的 Claude Code CLI 源码 +> 最后更新:2026-04-01 + +--- + +## 1. API 提供商概览 + +Claude Code 支持 **4 种 API 后端**,通过环境变量切换: + +| 提供商 | 启用变量 | 说明 | +|--------|----------|------| +| **Direct API** | 默认(无需设置) | Anthropic 官方 API | +| **AWS Bedrock** | `CLAUDE_CODE_USE_BEDROCK=1` | AWS 托管的 Claude | +| **Google Vertex AI** | `CLAUDE_CODE_USE_VERTEX=1` | GCP 托管的 Claude | +| **Azure Foundry** | `CLAUDE_CODE_USE_FOUNDRY=1` | Azure 托管的 Claude | + +优先级判断逻辑(`src/utils/model/providers.ts`): + +```typescript +export function getAPIProvider(): APIProvider { + return isEnvTruthy(process.env.CLAUDE_CODE_USE_BEDROCK) ? 'bedrock' + : isEnvTruthy(process.env.CLAUDE_CODE_USE_VERTEX) ? 'vertex' + : isEnvTruthy(process.env.CLAUDE_CODE_USE_FOUNDRY) ? 'foundry' + : 'firstParty' +} +``` + +--- + +## 2. Direct API(默认) + +### 2.1 认证 + +| 环境变量 | 必需 | 说明 | +|----------|------|------| +| `ANTHROPIC_API_KEY` | ✅ | Anthropic API 密钥 | +| `ANTHROPIC_AUTH_TOKEN` | — | Bearer token 替代方式 | + +**二选一**,`ANTHROPIC_API_KEY` 优先级更高。也支持 OAuth 登录(`/login` 命令),token 存储在 `~/.claude/` 配置目录。 + +### 2.2 端点配置 + +| 环境变量 | 默认值 | 说明 | +|----------|--------|------| +| `ANTHROPIC_BASE_URL` | `https://api.anthropic.com` | API 基础 URL | +| `ANTHROPIC_UNIX_SOCKET` | — | Unix socket 路径(替代 TCP) | + +自定义代理或本地网关时设置 `ANTHROPIC_BASE_URL`。代码中通过 `isFirstPartyAnthropicBaseUrl()` 判断是否为官方端点: + +```typescript +export function isFirstPartyAnthropicBaseUrl(): boolean { + const baseUrl = process.env.ANTHROPIC_BASE_URL + if (!baseUrl) return true + const host = new URL(baseUrl).host + return ['api.anthropic.com'].includes(host) +} +``` + +### 2.3 模型选择 + +| 环境变量 | 说明 | +|----------|------| +| `ANTHROPIC_MODEL` | 主循环模型(最高优先级的用户可配变量) | +| `ANTHROPIC_SMALL_FAST_MODEL` | 轻量模型(默认 Haiku,用于 token 估算等) | +| `ANTHROPIC_DEFAULT_OPUS_MODEL` | 覆盖默认 Opus 模型 | +| `ANTHROPIC_DEFAULT_SONNET_MODEL` | 覆盖默认 Sonnet 模型 | +| `ANTHROPIC_DEFAULT_HAIKU_MODEL` | 覆盖默认 Haiku 模型 | + +**模型选择优先级**(`getMainLoopModel()`): + +1. 会话中 `/model` 命令覆盖 — 最高 +2. `--model` CLI 参数 +3. `ANTHROPIC_MODEL` 环境变量 +4. 用户 settings 中保存的模型 +5. 内置默认值(Sonnet) + +### 2.4 Beta 功能 + +| 环境变量 | 说明 | +|----------|------| +| `ANTHROPIC_BETAS` | 追加 beta header(逗号分隔) | + +Claude Code 内部会自动附加多个 beta header,如 `files-api-2025-04-14`、`oauth-2025-04-20` 等。 + +### 2.5 请求自定义 + +| 环境变量 | 说明 | +|----------|------| +| `ANTHROPIC_CUSTOM_HEADERS` | 自定义 HTTP 头(JSON 格式) | +| `CLAUDE_CODE_EXTRA_BODY` | 请求体额外字段(JSON 格式) | + +--- + +## 3. AWS Bedrock + +### 3.1 启用 + +```bash +export CLAUDE_CODE_USE_BEDROCK=1 +``` + +### 3.2 认证 + +使用 AWS SDK 默认凭证链(`@aws-sdk/credential-provider-node`): + +- 环境变量:`AWS_ACCESS_KEY_ID` + `AWS_SECRET_ACCESS_KEY` + `AWS_SESSION_TOKEN` +- AWS CLI 配置:`~/.aws/credentials` +- IAM Role(EC2 / ECS / Lambda) +- SSO + +跳过 Bedrock 认证检查(开发/测试用): + +```bash +export CLAUDE_CODE_SKIP_BEDROCK_AUTH=1 +``` + +### 3.3 区域配置 + +| 环境变量 | 默认值 | 说明 | +|----------|--------|------| +| `AWS_REGION` / `AWS_DEFAULT_REGION` | `us-east-1` | 全局 AWS 区域 | +| `ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION` | — | 轻量模型独立区域 | + +### 3.4 端点 + +| 环境变量 | 说明 | +|----------|------| +| `ANTHROPIC_BEDROCK_BASE_URL` | 自定义 Bedrock 端点 | + +--- + +## 4. Google Vertex AI + +### 4.1 启用 + +```bash +export CLAUDE_CODE_USE_VERTEX=1 +``` + +### 4.2 认证 + +使用 `google-auth-library` 默认凭证链: + +- `GOOGLE_APPLICATION_CREDENTIALS` — 服务账号 JSON 路径 +- `gcloud auth application-default login` — 用户凭证 +- Workload Identity(GKE / Cloud Run) + +跳过 Vertex 认证检查: + +```bash +export CLAUDE_CODE_SKIP_VERTEX_AUTH=1 +``` + +### 4.3 项目与区域 + +| 环境变量 | 必需 | 说明 | +|----------|------|------| +| `ANTHROPIC_VERTEX_PROJECT_ID` | ✅ | GCP 项目 ID | +| `CLOUD_ML_REGION` | — | 默认区域(回退 `us-east5`) | +| `VERTEX_REGION_CLAUDE_3_5_HAIKU` | — | Claude 3.5 Haiku 专属区域 | +| `VERTEX_REGION_CLAUDE_HAIKU_4_5` | — | Claude Haiku 4.5 专属区域 | +| `VERTEX_REGION_CLAUDE_3_5_SONNET` | — | Claude 3.5 Sonnet 专属区域 | +| `VERTEX_REGION_CLAUDE_3_7_SONNET` | — | Claude 3.7 Sonnet 专属区域 | + +区域优先级:模型专属变量 > `CLOUD_ML_REGION` > 配置默认 > `us-east5`。 + +--- + +## 5. Azure Foundry + +### 5.1 启用 + +```bash +export CLAUDE_CODE_USE_FOUNDRY=1 +``` + +### 5.2 端点配置(二选一) + +| 环境变量 | 说明 | +|----------|------| +| `ANTHROPIC_FOUNDRY_RESOURCE` | Azure 资源名,自动生成端点 `https://{resource}.services.ai.azure.com/anthropic/v1/messages` | +| `ANTHROPIC_FOUNDRY_BASE_URL` | 完整端点 URL(优先级更高) | + +### 5.3 认证 + +| 方式 | 环境变量 | 说明 | +|------|----------|------| +| API Key | `ANTHROPIC_FOUNDRY_API_KEY` | 直接使用密钥 | +| Azure AD | — | 无 API key 时自动使用 `DefaultAzureCredential` | + +Azure AD 支持的凭证方式:环境变量、Managed Identity、Azure CLI、Visual Studio Code 等。 + +跳过 Foundry 认证检查: + +```bash +export CLAUDE_CODE_SKIP_FOUNDRY_AUTH=1 +``` + +--- + +## 6. 代理(Proxy) + +### 6.1 HTTP 代理 + +| 环境变量 | 优先级 | 说明 | +|----------|--------|------| +| `https_proxy` | 1 | 小写(最高优先级) | +| `HTTPS_PROXY` | 2 | 大写 | +| `http_proxy` | 3 | HTTP 代理 | +| `HTTP_PROXY` | 4 | HTTP 大写 | +| `no_proxy` / `NO_PROXY` | — | 代理排除列表 | + +### 6.2 代理行为 + +```typescript +export function getProxyUrl(): string | undefined { + return env.https_proxy || env.HTTPS_PROXY || env.http_proxy || env.HTTP_PROXY +} +``` + +`NO_PROXY` 支持逗号分隔的域名/IP 列表,支持通配符 `*`。 + +### 6.3 代理 DNS 解析 + +```bash +# 让代理端解析域名(适用于沙箱环境) +export CLAUDE_CODE_PROXY_RESOLVES_HOSTS=1 +``` + +--- + +## 7. mTLS 与 TLS 配置 + +| 环境变量 | 说明 | +|----------|------| +| `CLAUDE_CODE_CLIENT_CERT` | 客户端证书文件路径 | +| `CLAUDE_CODE_CLIENT_KEY` | 客户端私钥文件路径 | +| `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE` | 私钥密码 | +| `NODE_EXTRA_CA_CERTS` | 额外 CA 证书(Node.js 自动加载) | + +--- + +## 8. OAuth 认证 + +### 8.1 流程 + +Claude Code 实现了完整的 OAuth 2.0 流程(`src/services/oauth/`): + +1. 用户执行 `/login` +2. 浏览器打开 Anthropic 授权页面 +3. 用户授权后回调到本地监听端口 +4. 交换 access_token / refresh_token +5. Token 存储在 `~/.claude/` 安全存储中 + +### 8.2 OAuth Scopes + +| Scope | 用途 | +|-------|------| +| `user:inference` | API 推理调用 | +| `user:profile` | 用户信息读取 | +| `user:sessions:claude_code` | Claude Code 会话管理 | +| `user:mcp_servers` | MCP 服务器管理 | +| `user:file_upload` | 文件上传 | +| `org:create_api_key` | Console 端 API key 创建 | + +### 8.3 OAuth 环境变量 + +| 环境变量 | 说明 | +|----------|------| +| `CLAUDE_CODE_OAUTH_CLIENT_ID` | 自定义 OAuth client ID | +| `CLAUDE_CODE_OAUTH_TOKEN` | 直接注入 OAuth token | +| `CLAUDE_CODE_OAUTH_REFRESH_TOKEN` | 注入 refresh token | +| `CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR` | 从文件描述符读取 token | +| `CLAUDE_CODE_CUSTOM_OAUTH_URL` | 自定义 OAuth 端点 URL | + +--- + +## 9. 其他关键配置 + +### 9.1 会话与上下文 + +| 环境变量 | 默认值 | 说明 | +|----------|--------|------| +| `CLAUDE_CODE_MAX_CONTEXT_TOKENS` | — | 最大上下文 token 数 | +| `CLAUDE_CODE_MAX_OUTPUT_TOKENS` | — | 最大输出 token 数 | +| `CLAUDE_CODE_MAX_RETRIES` | — | API 重试次数 | +| `CLAUDE_CODE_AUTO_COMPACT_WINDOW` | — | 自动压缩窗口大小 | +| `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` | — | 压缩阈值百分比 | + +### 9.2 功能开关 + +| 环境变量 | 说明 | +|----------|------| +| `CLAUDE_CODE_DISABLE_THINKING` | 禁用 thinking 模式 | +| `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` | 禁用自适应 thinking | +| `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | 禁用非必要网络请求 | +| `CLAUDE_CODE_DISABLE_AUTO_MEMORY` | 禁用自动记忆提取 | +| `CLAUDE_CODE_DISABLE_CRON` | 禁用定时任务 | +| `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` | 禁用后台任务 | +| `CLAUDE_CODE_ALWAYS_ENABLE_EFFORT` | 始终启用 extended thinking | +| `CLAUDE_CODE_EFFORT_LEVEL` | thinking effort 级别 | +| `CLAUDE_CODE_SIMPLE` | 简化模式(减少输出) | +| `CLAUDE_CODE_BRIEF` | 简洁模式 | + +### 9.3 调试与诊断 + +| 环境变量 | 说明 | +|----------|------| +| `CLAUDE_DEBUG` | 调试模式 | +| `CLAUDE_CODE_DEBUG_LOGS_DIR` | 调试日志目录 | +| `CLAUDE_CODE_DEBUG_LOG_LEVEL` | 调试日志级别 | +| `CLAUDE_CODE_PROFILE_STARTUP` | 启动性能分析 | +| `CLAUDE_CODE_PROFILE_QUERY` | 查询性能分析 | +| `CLAUDE_CODE_DIAGNOSTICS_FILE` | 诊断输出文件 | +| `CLAUDE_CODE_JSONL_TRANSCRIPT` | JSONL 格式对话记录 | + +### 9.4 配置目录 + +| 环境变量 | 默认值 | 说明 | +|----------|--------|------| +| `CLAUDE_CONFIG_DIR` | `~/.claude` | 配置目录 | + +配置目录结构: + +``` +~/.claude/ +├── config.json # 全局配置(模型、设置) +├── settings.json # 用户设置 +├── oauth-tokens.json # OAuth token 存储 +├── mcp-servers.json # MCP 服务器配置 +├── projects/ # 项目级配置 +└── memory/ # 持久化记忆 +``` + +--- + +## 10. 自定义模型选项 + +允许在模型选择菜单中添加自定义模型: + +| 环境变量 | 说明 | +|----------|------| +| `ANTHROPIC_CUSTOM_MODEL_OPTION` | 自定义模型 ID | +| `ANTHROPIC_CUSTOM_MODEL_OPTION_NAME` | 显示名称 | +| `ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION` | 模型描述 | + +--- + +## 11. 完整配置示例 + +### 11.1 Direct API(最简) + +```bash +export ANTHROPIC_API_KEY=sk-ant-xxx +bun dist/bundle.js -p "hello" +``` + +### 11.2 自定义代理 + +```bash +export ANTHROPIC_API_KEY=sk-ant-xxx +export ANTHROPIC_BASE_URL=https://my-proxy.example.com +bun dist/bundle.js +``` + +### 11.3 AWS Bedrock + +```bash +export CLAUDE_CODE_USE_BEDROCK=1 +export AWS_REGION=us-west-2 +export AWS_ACCESS_KEY_ID=AKIAxxx +export AWS_SECRET_ACCESS_KEY=xxx +bun dist/bundle.js +``` + +### 11.4 Vertex AI + +```bash +export CLAUDE_CODE_USE_VERTEX=1 +export ANTHROPIC_VERTEX_PROJECT_ID=my-gcp-project +export CLOUD_ML_REGION=us-central1 +export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json +bun dist/bundle.js +``` + +### 11.5 Azure Foundry + API Key + +```bash +export CLAUDE_CODE_USE_FOUNDRY=1 +export ANTHROPIC_FOUNDRY_RESOURCE=my-azure-resource +export ANTHROPIC_FOUNDRY_API_KEY=xxx +bun dist/bundle.js +``` + +### 11.6 带代理 + mTLS + +```bash +export ANTHROPIC_API_KEY=sk-ant-xxx +export HTTPS_PROXY=http://proxy.corp.com:8080 +export NO_PROXY=localhost,127.0.0.1 +export CLAUDE_CODE_CLIENT_CERT=/path/to/client.pem +export CLAUDE_CODE_CLIENT_KEY=/path/to/client-key.pem +bun dist/bundle.js +``` + +### 11.7 调试模式 + +```bash +export ANTHROPIC_API_KEY=sk-ant-xxx +export CLAUDE_DEBUG=1 +export CLAUDE_CODE_DEBUG_LOGS_DIR=/tmp/claude-debug +export CLAUDE_CODE_DEBUG_LOG_LEVEL=verbose +bun dist/bundle.js +``` + +--- + +## 12. 认证优先级 + +Claude Code 的认证解析顺序(`src/utils/auth.ts`): + +1. **文件描述符注入** — `CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR` / `CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR` +2. **环境变量** — `ANTHROPIC_API_KEY` / `CLAUDE_CODE_OAUTH_TOKEN` +3. **macOS Keychain** — 安全存储的凭证 +4. **配置文件** — `~/.claude/config.json` 中的 API key +5. **API key helper** — `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` 控制的外部脚本 +6. **OAuth 登录** — `/login` 流程获取的 token + +--- + +## 13. 注意事项 + +1. **`isFirstPartyAnthropicBaseUrl()` 影响行为** — 只有指向 `api.anthropic.com` 时才被视为官方端点,影响 bootstrap 请求、模型默认值等 +2. **第三方提供商模型延迟** — Bedrock/Vertex/Foundry 的模型可用性滞后于 Direct API,代码中为它们保留了独立的默认模型分支 +3. **macOS Keychain 回退** — Linux 环境下安全存储回退到明文文件,注意权限控制 +4. **代理 + mTLS 同时使用** — 代码同时支持 HTTPS 代理 + 客户端证书认证,按需组合 +5. **OAuth token 自动刷新** — `withOAuth401Retry()` 会自动处理 401 错误并刷新 token diff --git a/ARCHITECTURE-BRIDGE-REMOTE.md b/docs/ARCHITECTURE-BRIDGE-REMOTE.md similarity index 100% rename from ARCHITECTURE-BRIDGE-REMOTE.md rename to docs/ARCHITECTURE-BRIDGE-REMOTE.md diff --git a/ARCHITECTURE-COMMANDS.md b/docs/ARCHITECTURE-COMMANDS.md similarity index 100% rename from ARCHITECTURE-COMMANDS.md rename to docs/ARCHITECTURE-COMMANDS.md diff --git a/ARCHITECTURE-COMPONENTS.md b/docs/ARCHITECTURE-COMPONENTS.md similarity index 100% rename from ARCHITECTURE-COMPONENTS.md rename to docs/ARCHITECTURE-COMPONENTS.md diff --git a/ARCHITECTURE-SERVICES.md b/docs/ARCHITECTURE-SERVICES.md similarity index 100% rename from ARCHITECTURE-SERVICES.md rename to docs/ARCHITECTURE-SERVICES.md diff --git a/ARCHITECTURE-TOOLS.md b/docs/ARCHITECTURE-TOOLS.md similarity index 100% rename from ARCHITECTURE-TOOLS.md rename to docs/ARCHITECTURE-TOOLS.md diff --git a/ARCHITECTURE-UTILS.md b/docs/ARCHITECTURE-UTILS.md similarity index 100% rename from ARCHITECTURE-UTILS.md rename to docs/ARCHITECTURE-UTILS.md diff --git a/ARCHITECTURE.md b/docs/ARCHITECTURE.md similarity index 100% rename from ARCHITECTURE.md rename to docs/ARCHITECTURE.md diff --git a/BUILD.md b/docs/BUILD.md similarity index 97% rename from BUILD.md rename to docs/BUILD.md index 3cfc0f7..78dd7a5 100644 --- a/BUILD.md +++ b/docs/BUILD.md @@ -319,9 +319,17 @@ bun dist/bundle.js mcp list --- -## 7. 架构文档 +## 7. 文档索引 -项目包含 7 份架构分析文档: +### 7.1 API 配置 + +完整的 API 配置指南(环境变量、认证方式、多云后端、代理、mTLS): + +→ **[API-CONFIG.md](./API-CONFIG.md)** + +### 7.2 架构文档 + +项目包含 8 份架构分析文档: | 文档 | 大小 | 内容 | |------|------|------| @@ -333,6 +341,7 @@ bun dist/bundle.js mcp list | `ARCHITECTURE-UTILS.md` | 12KB | 290+ 工具文件 | | `ARCHITECTURE-BRIDGE-REMOTE.md` | 12KB | Bridge/Remote/Coordinator | | `REFACTORING-ASSESSMENT.md` | 12KB | 重构可行性评估 | +| **`API-CONFIG.md`** | **10KB** | **API 配置完整参考** | --- diff --git a/REFACTORING-ASSESSMENT.md b/docs/REFACTORING-ASSESSMENT.md similarity index 100% rename from REFACTORING-ASSESSMENT.md rename to docs/REFACTORING-ASSESSMENT.md