{"repo": "chenpu17/cc-gw", "files": {"README.md": {"5e3648138063b065e445d8bd3b07aa65e7a63783": {"t": 1785674079.807004, "n": 22128, "h": "beab77401e95052d", "c": "# cc-gw\n\n> **中文** | [English](#english)\n\ncc-gw 是一个面向 Claude Code 与同类客户端的本地多模型网关,负责:\n\n- 归一化 `/v1/messages` 请求并映射到不同 Provider / 模型\n- 复刻 Claude API 的流式与工具调用语义\n- 记录请求日志、Token(含缓存命中)、TTFT/TPOT 等运行指标\n- 提供可视化 Web 管理台与守护进程 CLI\n- 在同一个 OpenAI 接入点聚合多 Provider / 多模型,兼容 Responses 与 Chat Completions 双协议\n\n> **提示(2025-10)**:OpenAI 接入点仍为实验特性,我们会尝试将请求转换为 Anthropic `/v1/messages` 并推断所需 beta 头,但部分专为 Claude Code 适配的代理可能仍返回“暂不支持”。此类模型请直接使用 `/anthropic/v1/messages` 端点。\n\n核心组件:\n\n| 模块 | 说明 |\n| ---- | ---- |\n| `@cc-gw/server` | Fastify 服务,实现协议转换、模型路由、Provider 适配与日志存储(支持 Anthropic 原生 payload/headers 透传与缓存统计) |\n| `@cc-gw/web` | React + Vite Web UI,包含仪表盘、日志面板、模型管理、系统设置 |\n| `@cc-gw/cli` | CLI 守护工具,封装 start/stop/restart/status 并托管 PID/日志 |\n\n## 🚀 快速开始\n\n### 完整配置指南(新手必读)\n\n以下是完整的配置流程,请按照步骤顺序操作:\n\n#### 步骤 1: 安装并启动服务\n\n```bash\n# 方式一:npm 全局安装(推荐)\nnpm install -g @chenpu17/cc-gw\ncc-gw start --daemon --port 4100\n\n# 方式二:从源码构建(开发者)\ngit clone \ncd cc-gw\npnpm install\npnpm --filter @cc-gw/server build\npnpm --filter @cc-gw/web build\npnpm --filter @cc-gw/cli exec tsx index.ts start --daemon --port 4100\n```\n\n启动后访问 Web 管理界面:`http://127.0.0.1:4100/ui`\n\n#### 步骤 2: 配置模型提供商\n\n1. 在 Web UI 中进入 **模型管理** 页面\n2. 点击 **添加提供商**,配置至少一个 Provider:\n - **Anthropic Claude**:\n ```\n Base URL: https://api.anthropic.com\n API Key: sk-ant-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n 默认模型: claude-3-5-sonnet-20241022\n ```\n Roo Code / Claude CLI 可通过 OpenAI 接入点访问 Anthropic 模型,但部分第三方代理可能拒绝该路径;若收到“暂不支持”或类似错误,请改用 `/anthropic/v1/messages`。\n - **Moonshot Kimi**:\n ```\n Base URL: https://api.moonshot.cn/v1\n API Key: sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n 默认模型: kimi-k2-0905-preview\n ```\n - **DeepSeek**:\n ```\n Base URL: https://api.deepseek.com/v1\n API Key: sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n 默认模型: deepseek-chat\n ```\n3. 配置完成后使用 **测试连接** 验证连通性\n\n#### 步骤 3: 生成网关 API Key\n\n1. 在 Web UI 中进入 **系统设置 → API Key 管理**\n2. 点击 **生成新密钥**,为不同客户端创建独立的密钥:\n - Claude Code IDE: `sk-gw-ide-xxxxxxxx`\n - Codex CLI: `sk-gw-codex-xxxxxxxx`\n - 其他工具: `sk-gw-other-xxxxxxxx`\n\n#### 步骤 4: 配置环境变量(关键步骤)\n\n将以下命令添加到 `~/.bashrc`、`~/.zshrc` 等 shell 启动脚本,或使用 `direnv` 等工具统一管理:\n\n```bash\n# Claude Code / VS Code\nexport ANTHROPIC_BASE_URL=http://127.0.0.1:4100/anthropic\nexport ANTHROPIC_API_KEY=sk-gw-ide-xxxxxxxxxxxxxxxx\n\n# Codex CLI(Responses API)\nexport OPENAI_BASE_URL=http://127.0.0.1:4100/openai/v1\nexport OPENAI_API_KEY=sk-gw-codex-xxxxxxxxxxxxxxxx\nexport CC_GW_KEY=sk-gw-codex-xxxxxxxxxxxxxxxx\n\n# Roo Code / 旧式 OpenAI Chat Completions\nexport OPENAI_CHAT_BASE_URL=http://127.0.0.1:4100/openai/v1\nexport OPENAI_CHAT_PATH=/chat/completions\n```\n\n更新完毕后执行 `source ~/.bashrc`(或 `source ~/.zshrc`)让环境变量立即生效。完成后可以马上做一次快速连通性测试:\n\n```bash\nclaude \"你好,请简短回应\"\ncodex ask \"你好,请介绍一下自己\"\n```\n\n若命令能够正常返回,同时可在 Web UI 的 **请求日志** 页面看到对应记录,即表明环境变量已经正确生效。\n\n#### 步骤 5: 配置客户端\n\n- **Claude Code / VS Code**:在设置中选择自定义 API,填入 `http://127.0.0.1:4100/anthropic` 与 `sk-gw-ide-xxxxxxxxxxxxxxxx`。\n- **Codex CLI**:编辑 `~/.codex/config.toml`,内容示例:\n\n ```toml\n model = \"gpt-5-codex\"\n model_provider = \"cc_gw\"\n model_reasoning_effort = \"high\"\n disable_response_storage = true\n\n [model_providers.cc_gw]\n name = \"cc_gw\"\n base_url = \"http://127.0.0.1:4100/openai/v1\"\n wire_api = \"responses\"\n env_key = \"cc_gw_key\"\n ```\n\n配置完成后,建议运行 `codex status` 或 `codex chat \"测试\"` 再确认一次终端输出。\n\n##### 5.1 OpenAI 接入点接入说明\n\n- **Responses API**:推荐给支持新版 OpenAI Responses(例如 Codex CLI、最新 Agent 工具)的客户端,直接指向 `http://127.0.0.1:4100/openai/v1/responses`,即可自动在下游 Provider 间路由并返回标准 `response` 结构。\n- **Chat Completions API**:针对 Roo Code、OpenAI CLI 等仍使用传统 `POST /v1/chat/completions` 的客户端,现可通过 `http://127.0.0.1:4100/openai/v1/chat/completions` 接入;工具仅需设置 Base URL(例如 Roo Code 的 “OpenAI Compatible” 配置)和 API Key 即可。\n- **注意兼容性**:OpenAI 入口为实验性最佳实践。若下游服务只支持 Claude Code 专用头部,可能仍返回“暂不支持”,此时改用 `/anthropic/v1/messages`。\n- **Anthropic Beta Header**:若上游模型需要 beta 头(例如 Claude 4.5 预览),可设置环境变量 `CC_GW_ANTHROPIC_BETA_`(如 `CC_GW_ANTHROPIC_BETA_CLAUDE_SONNET_4_5_20250929`)或全局 `CC_GW_ANTHROPIC_BETA_ALL`;网关会在转发至 Anthropic 时尝试附加,也会针对 4.5 系列模型进行默认推断。\n- **多模型聚合**:无论使用 Responses 还是 Chat Completions,两种接口都会按配置聚合所有 Provider 模型,`GET /openai/v1/models` 将返回当前可用模型列表及默认 Provider。\n\n#### 步骤 6: 高级配置(可选)\n\n##### 6.1 模型路由配置\n\n在 **模型管理 → 路由配置** 中,可以设置模型映射:\n```json\n{\n \"claude-3-5-sonnet-20241022\": \"kimi:kimi-k2-0905-preview\",\n \"claude-opus-4-1-20250805\": \"anthropic:claude-3-5-sonnet-20241022\"\n}\n```\n\n##### 6.2 环境变量持久化\n\n推荐使用 `direnv` 管理环境变量,在项目目录创建 `.envrc`:\n```bash\n# .envrc\nexport ANTHROPIC_BASE_URL=http://127.0.0.1:4100/anthropic\nexport ANTHROPIC_API_KEY=sk-gw-ide-xxxxxxxxxxxxxxxx\nexport OPENAI_BASE_URL=http://127.0.0.1:4100/openai/v1\nexport OPENAI_API_KEY=sk-gw-codex-xxxxxxxxxxxxxxxx\nexport CC_GW_KEY=sk-gw-codex-xxxxxxxxxxxxxxxx\n# 若需兼容旧版 Chat Completions,可继续暴露聊天端点\nexport OPENAI_CHAT_BASE_URL=http://127.0.0.1:4100/openai/v1\nexport OPENAI_CHAT_PATH=/chat/completions\n# 针对 Anthropic 新模型可设置 Beta Header(示例)\nexport CC_GW_ANTHROPIC_BETA_CLAUDE_SONNET_4_5_20250929=claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14\nexport CC_GW_ANTHROPIC_BETA_ALL=claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14\n\n```\n\n然后运行 `direnv allow` 自动加载。\n\n##### 6.3 HTTPS 配置\n\ncc-gw 支持同时启动 HTTP 和 HTTPS 服务。\n\n**默认配置**:\n- HTTP: 端口 `4100`(**默认启用**,推荐用于本地开发)\n- HTTPS: 端口 `4443`(**默认关闭**)\n- 两个协议可独立启用/禁用,但**至少要保持一个启用**\n\n⚠️ **重要提示:关于 HTTPS 证书**\n\n- **自签名证书无效**:Claude Code 和大多数 AI 工具无法信任自签名证书,会导致 \"Unable to connect to API\" 错误\n- **推荐方案**:本地开发环境建议使用 HTTP 协议(`127.0.0.1` 本地访问非常安全)\n- **如需 HTTPS**:请使用受信任 CA(如 Let's Encrypt)签发的正式证书,或配置反向代理(如 Nginx/Caddy)处理 HTTPS\n\n**手动配置 HTTPS(通过配置文件)**:\n\n编辑 `~/.cc-gw/config.json`:\n\n```json\n{\n \"http\": {\n \"enabled\": true,\n \"port\": 4100,\n \"host\": \"127.0.0.1\"\n },\n \"https\": {\n \"enabled\": true,\n \"port\": 4443,\n \"host\": \"127.0.0.1\",\n \"keyPath\": \"/path/to/your/ssl/key.pem\",\n \"certPath\": \"/path/to/your/ssl/cert.pem\",\n \"caPath\": \"\"\n }\n}\n```\n\n**使用 HTTPS 访问**:\n\n```bash\n# 重启服务使配置生效\ncc-gw restart --daemon\n\n# 访问 HTTPS 端点\ncurl https://127.0.0.1:4443/health\n\n# Web UI HTTPS 访问\nopen https://127.0.0.1:4443/ui\n```\n\n**环境变量配置**:\n\n```bash\n# 推荐:使用 HTTP(默认)\nexport ANTHROPIC_BASE_URL=http://127.0.0.1:4100/anthropic\nexport OPENAI_BASE_URL=http://127.0.0.1:4100/openai/v1\n\n# 如果使用 HTTPS(需要受信任的证书)\nexport ANTHROPIC_BASE_URL=https://127.0.0.1:4443/anthropic\nexport OPENAI_BASE_URL=https://127.0.0.1:4443/openai/v1\n```\n\n**证书路径说明**:\n- `keyPath`: 私钥文件路径(必需)\n- `certPath`: 证书文件路径(必需)\n- `caPath`: CA 证书路径(可选,用于证书链)\n\n##### 6.4 自定义接入点(Custom Endpoints)\n\ncc-gw 支持创建额外的自定义 API 端点,每个端点可以:\n- 使用不同的协议(Anthropic、OpenAI)\n- 配置独立的路由规则\n- 支持多路径注册(一个端点支持多种协议)\n- **自动路径扩展**:只需配置基础路径(如 `/my-endpoint`),系统会根据协议自动注册完整的 API 路径\n\n**快速示例**:\n\n通过 Web UI 或配置文件创建自定义端点:\n```json\n{\n \"customEndpoints\": [\n {\n \"id\": \"claude-api\",\n \"label\": \"Claude 专用接入点\",\n \"path\": \"/claude\",\n \"protocol\": \"anthropic\",\n \"enabled\": true\n }\n ]\n}\n```\n\n配置后,客户端可以通过 `http://127.0.0.1:4100/claude/v1/messages` 访问(路径自动扩展)。\n\n**主要特性**:\n- **协议自动路径扩展**:配置 `/claude` + `anthropic` 协议,自动注册 `/claude/v1/messages`\n- **多协议支持**:同时支持 Anthropic 和 OpenAI(Chat Completions / Responses API)\n- **独立路由**:每个端点可以配置独立的模型路由规则\n- **路由模板**:支持保存和应用路由预设,快速切换不同的 Provider 配置\n\n**详细文档**:[docs/custom-endpoints.md](docs/custom-endpoints.md)\n\n> ⚠️ 如果 OpenAI 接入点仍返回“暂不支持”,请将客户端改用 `/anthropic/v1/messages` 端点并直接配置 Anthropic Provider。\n\n#### 常见问题排查\n\n1. **连接失败**:\n - 检查 cc-gw 服务状态:`cc-gw status`\n - 验证环境变量:`echo $ANTHROPIC_BASE_URL`\n - 查看请求日志确认错误信息\n\n2. **认证错误**:\n - 确认 API Key 正确且未过期\n - 检查环境变量是否正确加载\n - 验证 Provider 的 API Key 配置\n\n3. **模型不可用**:\n - 在\"模型管理\"中测试 Provider 连接\n - 检查模型路由配置\n - 确认上游服务模型名称正确\n\n4. **HTTPS 连接问题**:\n - ⚠️ **Claude Code 无法连接**: 自签名证书会导致 \"Unable to connect to API\" 错误,建议使用 HTTP 协议(本地 127.0.0.1 访问安全)\n - **证书路径错误**: 检查配置文件中的 `keyPath` 和 `certPath` 是否正确\n - **需要受信任证书**: 如必须使用 HTTPS,请配置 Let's Encrypt 等受信任 CA 签发的证书\n - **两个协议都禁用**: 至少要启用 HTTP 或 HTTPS 中的一个\n\n> ✅ 完成以上 6 个步骤后,你的 cc-gw 网关就完全配置好了!所有 AI 客户端都可以通过统一的网关访问不同的模型服务。\n\n### 推荐方式:npm 全局安装\n\n```bash\nnpm install -g @chenpu17/cc-gw\ncc-gw start --daemon --port 4100\n```\n\n首启会在 `~/.cc-gw/config.json` 生成配置模板,推荐直接通过 Web UI (`http://127.0.0.1:4100/ui`) 完成所有后续配置与调整。`cc-gw status`、`cc-gw stop`、`cc-gw restart` 可用于日常运维。\n\n> ⚠️ **Linux 安装提示**:本项目依赖 `better-sqlite3`;该库已为 Node 20/22/24 在 glibc/musl(x64/arm64/arm)提供预编译二进制,通常无需额外工具。如果你的环境未命中预编译(例如更早版本的 Node 或稀有架构),请先安装 `build-essential python3 make g++`,再运行 `npm install -g @chenpu17/cc-gw --unsafe-perm --build-from-source`。\n\n### 从源码构建(开发者)\n\n前置:Node.js 18.18+(推荐 20 LTS)、pnpm 8+\n\n```bash\npnpm install\npnpm --filter @cc-gw/server build\npnpm --filter @cc-gw/web build\npnpm --filter @cc-gw/cli exec tsx index.ts start --daemon --port 4100\n```\n\n> ✅ 首次启动后推荐直接使用 Web 管理台完成 Provider、模型、日志等设置;仅在自动化或高级场景下再手动编辑配置文件。\n\n如需以 CLI 启动后配合本地脚本使用,可在 shell 中补充以下变量:\n\n```bash\nexport ANTHROPIC_BASE_URL=http://127.0.0.1:4100/anthropic\nexport ANTHROPIC_API_KEY=$(cc-gw keys current)\n```\n\n将其写入 `direnv`/shell profile,即可让后续工具自动读取。\n\n## Web 管理台\n\n强烈建议以 Web 管理台作为主要的配置入口,可视化界面涵盖仪表盘、请求日志、模型管理与系统设置,所见即所得,避免手工改动 JSON 引入错误。\n\n访问 `http://:/ui`,主要页面:\n\n- **Dashboard**:展示请求量、Token 使用、缓存命中、各模型 TTFT(Time To First Token)/TPOT(Total Processing Time)、SQLite 数据库占用。\n- **请求日志**:多条件筛选(时间、Provider、模型、状态),查看压缩日志详情,支持分页导出与清理。\n- **模型管理**:维护 Provider 列表、预置模型、路由策略;一键测试连通性(发送诊断 PROMPT),支持保存并应用 Anthropic 路由模板,实现不同 Provider 方案的“一键切换”。\n- **系统设置**:端口、日志保留策略、是否存储请求 payload、日志级别与访问日志开关、日志清理工具。\n- **安全控制**:在“系统设置 → 安全”中可启用 Web UI 登录校验,自定义用户名及密码并自动保护所有 `/api/*` 管理接口(模型请求端点仍保持开放)。\n- **使用指南**:提供图文步骤、常见问题与排查提示,帮助团队成员快速熟悉配置流程。\n\nUI 支持中英文、深色/浅色主题以及移动端响应式布局,提供键盘可达性(Skip Link、焦点管理)。\n\n#### 界面预览\n\n![Dashboard Overview](docs/images/dashboard.png)\n\n![Request Logs](docs/images/logs.png)\n\n### 连接 Claude Code\n1. 启动 cc-gw 并在“模型管理”完成 Provider 配置。\n2. 确认第 4 步环境变量已写入当前 shell 或系统(`ANTHROPIC_BASE_URL` / `ANTHROPIC_API_KEY`)。\n3. 在 Claude Code 终端或 VS Code 插件中选择“自定义 API”,填入 `http://127.0.0.1:4100/anthropic` 并粘贴密钥。\n4. 运行 `claude \"hello\"` 或在 VS Code 新建对话,若能在 Web UI 的“请求日志”看到记录即成功。\n\n### 连接 Codex(原 Claude Code for Repo)\n1. 在 Web UI “路由配置”页设定 `/openai` 端点默认模型。\n2. 设置环境变量 `OPENAI_BASE_URL=http://127.0.0.1:4100/openai/v1` 与 `OPENAI_API_KEY=<第 3 步生成的密钥>`。\n3. 在 `~/.codex/config.toml` 按前文示例声明 `model_providers.cc_gw`,或在 CLI `codex config set` 中写入相同配置。\n4. 执行 `codex status` / `codex ask` 验证连通性;如遇 404,请确认是否调用了 `/openai/v1/responses`。\n\n### 环境变量与客户端配置示例\n\n(段落保留,已在上方详细说明,可用于快速复制粘贴。)\n\n### 使用场景 / Usage Scenarios\n\n1. **双端点适配 / Dual Endpoint Support**:通过 `/anthropic` 与 `/openai` 端点,分别兼容 Claude Code 与 Codex 客户端。无需重启 cc-gw,即可在 Web UI 中为两个端点配置独立的默认模型与路由策略。\n2. **日志追踪 / Request Auditing**:在“请求日志”页按端点、Provider、API Key 等维度筛选记录,可直接查看和复制完整的请求/响应 payload,辅助排查联调问题。\n3. **模型切换 / Cross-Provider Routing**:利用“模型管理”页的路由映射,将 Claude Code 请求透明地转发到 GLM、Kimi K2、DeepSeek 等任意 OpenAI 兼容模型,实现一套 IDE 客户端、多家大模型的快速切换;对 Anthropic 端点可保存当前映射为模板(例如“fox”“glm”),后续一键切换整套路由。\n4. **操作指引 / Built-in Guidance**:左侧“Help”导航提供分步配置、日常运维建议及 FAQ,可作为新人上手或问题排查的快速参考。\n\n## 配置说明\n\n大多数场景请通过 Web 管理台调整设置,以下仅作为 `~/.cc-gw/config.json` 结构参考,便于脚本化或排查:\n\n```json\n{\n \"http\": {\n \"enabled\": true,\n \"port\": 4100,\n \"host\": \"127.0.0.1\"\n },\n \"https\": {\n \"enabled\": true,\n \"port\": 4443,\n \"host\": \"127.0.0.1\",\n \"keyPath\": \"~/.cc-gw/certs/key.pem\",\n \"certPath\": \"~/.cc-gw/certs/cert.pem\",\n \"caPath\": \"\"\n },\n \"host\": \"127.0.0.1\",\n \"port\": 4100,\n \"providers\": [\n {\n \"id\": \"kimi\",\n \"label\": \"Moonshot Kimi\",\n \"type\": \"kimi\",\n \"baseUrl\": \"https://api.moonshot.cn/v1\",\n \"apiKey\": \"sk-...\",\n \"models\": [\n { \"id\": \"kimi-k2-0905-preview\", \"label\": \"Kimi K2\" }\n ]\n },\n {\n \"id\": \"anthropic\",\n \"label\": \"Claude\",\n \"type\": \"anthropic\",\n \"baseUrl\": \"https://api.anthropic.com\",\n \"apiKey\": \"sk-ant-...\",\n \"models\": [\n { \"id\": \"claude-3-5-sonnet-latest\" }\n ]\n }\n ],\n \"defaults\": {\n \"completion\": \"kimi:kimi-k2-0905-preview\",\n \"reasoning\": \"anthropic:claude-3-5-sonnet-latest\",\n \"background\": \"kimi:kimi-k2-0905-preview\",\n \"longContextThreshold\": 60000\n },\n \"modelRoutes\": {\n \"claude-sonnet-4-5-20250929\": \"kimi:kimi-k2-0905-preview\",\n \"claude-opus-4-1-20250805\": \"anthropic:claude-3-5-sonnet-latest\"\n },\n \"logRetentionDays\": 30,\n \"storeRequestPayloads\": true,\n \"storeResponsePayloads\": true,\n \"logLevel\": \"info\",\n \"requestLogging\": true,\n \"responseLogging\": true\n}\n```\n\n字段要点(建议仍以 Web UI \"系统设置 / 模型管理\" 进行操作,下列仅便于理解结构):\n\n- `http` / `https`:协议配置,支持独立启用/禁用,但至少要保持一个启用。\n - `enabled`:是否启用该协议\n - `port`:监听端口\n - `host`:监听地址\n - `keyPath` / `certPath`(仅 HTTPS):SSL/TLS 证书路径\n - `caPath`(可选):CA 证书链路径\n- `host` / `port`:旧格式向后兼容字段,新配置会自动迁移到 `http` / `https` 格式。\n- `providers`:定义上游服务;`type` 支持 `openai | anthropic | kimi | deepseek | custom`。\n- 模型标识使用 `providerId:modelId` 形式供路由引用。\n- `modelRoutes`:将 Claude 发起的模型名映射到上游模型;支持在源模型名中使用 `*` 通配符匹配,匹配度更高(字符更多)的规则优先,同等情况下按配置顺序取第一条;若希望直接透传请求的模型名,可将目标写成 `providerId:*`,此时会将源请求中的模型名原样发送给对应 Provider。\n- `routingPresets`:可选字段,保存多个 `anthropic`(或其他端点)路由模板,供 Web UI “一键切换”;每个模板仅包含 `name` 与 `modelRoutes`。\n- `storeRequestPayloads` / `storeResponsePayloads`:是否分别在 SQLite 中压缩保存请求原文与响应内容;关闭可减少敏感数据落盘。\n- `bodyLimit`:单次请求允许的最大请求体大小(字节),默认 10 MiB。`/compact` 等场景会发送较大上下文,如遇 413 可按需增大。\n- `logLevel`:控制 Fastify/Pino 控制台日志级别(`fatal`/`error`/`warn`/`info`/`debug`/`trace`)。\n- `providers[].authMode`:仅在 `type: \"anthropic\"` 时生效,可选 `apiKey`(默认,发送 `x-api-key`)或 `authToken`(发送 `Authorization: Bearer`)。配置 Claude Code 使用 `ANTHROPIC_AUTH_TOKEN` 时,请选择 `authToken` 并在 `apiKey` 输入框填入该值。\n- `requestLogging`:是否输出每个 HTTP 请求的进入日志。\n- `responseLogging`:是否输出每个 HTTP 请求完成的日志,可独立于 `requestLogging` 控制。\n- 推荐通过 Web UI 的“模型管理 / 系统设置”在线编辑并热加载,无需手工修改文件。\n\n#### Anthropic Provider 额外说明\n\n- 当 Provider `type` 设置为 `anthropic` 时,网关会保留 Claude Code 发来的完整 payload,并将其原样转发到 `/v1/messages`,无需转换工具调用或 metadata 字段。\n- 所有自定义 Header(如 `x-stainless-*`、`anthropic-beta`、`anthropic-dangerous-direct-browser-access`)会自动透传到下游,确保 Claude Code 的诊断与调试能力不受影响。\n- usage 统计会解析 `cache_read_input_tokens` / `cache_creation_input_tokens`,从而在日志与 Web UI 的 Token 指标中显示缓存命中或写入量;Moonshot / Anthropic 若未返回上述字段,则 `cached` 会继续显示为空。\n\n### 环境变量\n\n| 变量 | 说明 |\n| ---- | ---- |\n| `PORT` | CLI 启动时临时覆盖监听端口 |\n| `CC_GW_UI_ROOT` | 指定 Web UI 静态目录(默认自动检测 `@cc-gw/web` build 结果) |\n| `CC_GW_DEBUG_ENDPOINTS` | 设为 `1` 可在日志中输出下游请求 URL |\n\n## CLI 守护\n\n```bash\npnpm --filter @cc-gw/cli exec tsx index.ts start [--daemon] [--port 4100]\npnpm --filter @cc-gw/cli exec tsx index.ts stop\npnpm --filter @cc-gw/cli exec tsx index.ts restart [--daemon] [--port 4100]\npnpm --filter @cc-gw/cli exec tsx index.ts status\n```\n\n- 守护模式下 PID/日志存放于 `~/.cc-gw/cc-gw.pid` 与 `~/.cc-gw/logs/cc-gw.log`。\n- `status` 会回显配置与日志路径,便于排查。\n- `cc-gw version`(或 `cc-gw --version`)可输出与 npm 包同步的版本号,便于核对升级情况。\n\n## 数据与日志\n\n- 数据库:`~/.cc-gw/data/gateway.db`(`better-sqlite3` 管理的嵌入式 SQLite)。\n - `request_logs`:请求摘要、路由结果、耗时、TTFT/TPOT。\n - `request_payloads`:压缩的请求/响应正文(Brotli)。\n - `daily_metrics`:按日聚合的调用次数与 Token 统计。\n- 日志:`~/.cc-gw/logs/cc-gw.log`,包含请求生命周期、Provider 调用与 usage 摘要(`event: usage.metrics`)。\n\n## 常见问题\n\n- **Web UI 404**:请确认执行过 `pnpm --filter @cc-gw/web build`,并在 CLI 启动时自动或手动设置 `CC_GW_UI_ROOT`。\n- **usage 中无 `cached_tokens`**:部分 Provider(如火山 DeepSeek)需开启 `stream_options.include_usage` 或提供专有缓存参数;cc-gw 已在支持的适配器中自动注入,如仍为 `null` 需确认上游是否支持。\n- **日志数据库过大**:可在“系统设置”关闭 payload 保存或缩短保留天数;Web UI 亦提供手动清理工具。\n\n---\n\n## English\n\ncc-gw is a local gateway tailored for Claude Code and similar Anthropic-compatible clients. It normalizes `/v1/messages`, routes traffic across heterogeneous providers, mirrors Claude’s streaming & tool semantics, and records detailed metrics that surface in a bilingual Web console and CLI daemon.\n\n### Highlights\n\n| Feature | Details |\n| ------- | ------- |\n| Protocol adaptation | Converts Claude-style payloads into OpenAI-, Anthropic-, Kimi-, and DeepSeek-compatible requests while preserving tool calls and reasoning blocks. |\n| Model routing | Maps incoming model IDs to configured upstream providers with fallbacks for long-context/background tasks, plus Anthropic routing presets for one-click provider swaps. |\n| Observability | Persists request logs, token usage (including cache hits), TTFT, TPOT, and daily aggregates via better-sqlite3 with Brotli-compressed payloads; request/response bodies can be stored independently. |\n| Web console | React + Vite UI with dashboards, filters, provider CRUD, bilingual copy, and responsive layout. |\n| CLI daemon | `cc-gw` command wraps start/stop/restart/status, manages PID/log files, and scaffolds a default config on first launch. |\n\n### Standard Onboarding Checklist\n\n1. **Install & launch**: `npm install -g @chenpu17/cc-gw && cc-gw start --daemon --port 4100`. The first run scaffolds `~/.cc-gw/config.json` and makes the Web UI available at `http://127.0.0.1:4100/ui`.\n2. **Add providers**: In *Model Management*, create at least one provider by entering its base URL/API key and selecting default models. Templates for Anthropic, Kimi, DeepSeek, etc., are provided in the sidebar.\n3. **Issue gateway API keys**: Navigate to *System Settings → API Keys* and mint a key for each client (IDE, Codex CLI, automation). This is what clients will send to cc-gw.\n4. **Export environment variables (required)**:\n ```bash\n export ANTHROPIC_BASE_URL=http://127.0.0.1:4100/anthropic\n export ANTHROPIC_API_KEY=sk-ant-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\n # Optional: OpenAI-compatible endpoint (Codex, Open Interpreter, ...)\n export OPENAI_BASE_URL=http://127.0.0.1:4100/openai/v1\n export OPENAI_API_KEY=$ANTHROPIC_API_KEY\n ```\n Drop these lines into your shell profile (or `direnv`) so that IDEs inherit them automatically.\n5. **Point your clients**:\n - **Claude Code / VS Code extension**: enable custom API mode, paste `http://127.0.0.1:4100/anthropic`, and use the key from step 3. The extension appends `/v1/messages?beta=true` automatically.\n - **Codex CLI**: update `~/.codex/config.toml`:\n ```toml\n model = \"gpt-5-codex\"\n model_provider = \"cc_gw\"\n model_reasoning_effort = \"high\"\n disable_response_storage = true\n\n [model_providers.cc_gw]\n name = \"cc_gw\"\n base_url = \"http://127.0.0.1:4100/openai/v1\"\n wire_api = \"responses\"\n env_key = \"cc_gw_key\"\n ```\n Then export `CC_GW_KEY=`.\n6. **Smoke test**: run a short prompt (`claude \"hello\"`, `codex ask`, etc.) and confirm a matching entry appears in *Request Logs*. If not, re-check the environment variables and provider routing.\n\n> Once these six steps are complete, any Anthropic/OpenAI-style client can pivot to cc-gw. All further tweaks (providers, routing, logging) can be handled from the Web UI.\n\n### Quick reinstall / binary upgrade\n\n```bash\nnpm install -g @chenpu17/cc-gw\ncc-gw start --daemon --port 4100\n```\n\n`cc-gw status`, `cc-gw stop`, and `cc-gw restart` manage the daemon. The Web UI remains at `http://127.0.0.1:4100/ui`.\n\n> ⚠️ **Linux build note**: cc-gw relies on `better-sqlite3`. Prebuilt binaries cover Node 20/22/24 on glibc & musl (x64/arm64/arm). For other combos install `build-essential python3 make g++`, then rerun `npm install -g @chenpu17/cc-gw --unsafe-perm --build-from-source`.\n\n### From Source (contributors)\n\n```bash\npnpm install\npnpm --filter @cc-gw/server build\npnpm --filter @cc-gw/web build\npnpm --filter @cc-gw/cli exec tsx index.ts start --daemon --port 4100\n```\n\nConnect Claude Code after completing the onboarding steps above—the CLI and editor automatically append `/v1/messages`, and cc-gw will forward `?beta=true` samples or tool metadata upstream. For Codex or other OpenAI-style integrations, use `http://127.0.0.1:4100/openai/v1` (or the equivalent value from step 4) and hit `POST /openai/v1/responses` if the client requires an explicit path.\n\n### Configuration Snapshot\n\n- Providers include `type`, `baseUrl`, `apiKey`, and `models` descriptions.\n- When `type` is `anthropic`, cc-gw forwards the original Claude payload and all headers to `/v1/messages`, so tool calls/metadata remain intact.\n- Model routes use `providerId:modelId` syntax to remap Claude requests.\n- `storeRequestPayloads` / `storeResponsePayloads` control whether prompts and completions are persisted; disable either switch to avoid storing sensitive data.\n- `bodyLimit`: maximum request body size (in bytes). Defaults to 10 MiB—raise this if clients like Claude Code `/compact` hit HTTP 413.\n- `logLevel` adjusts Fastify/Pino verbosity (`fatal` → `trace`).\n- `requestLogging` controls whether per-request access logs are emitted to the console.\n- `responseLogging` toggles completion logs separately so you can keep the console quieter while preserving metrics.\n- Web UI allows editing without restarting; CLI restart will pick up bundle changes after rebuilds.\n\n### Observability & Storage\n\n- SQLite file under `~/.cc-gw/data/gateway.db` tracks logs and aggregated metrics.\n- Dashboard surfaces per-model TTFT/TPOT, cache hits(including Anthropic `cache_read_input_tokens` / `cache_creation_input_tokens`), and DB size.\n- Logs can be filtered/exported/cleaned directly from the UI.\n\n### CLI Reference\n\n| Command | Description |\n| ------- | ----------- |\n| `cc-gw start [--daemon] [--port]` | Launch the Fastify server, auto-creating config if missing. |\n| `cc-gw stop` | Send SIGTERM and remove stale PID files. |\n| `cc-gw restart` | Convenience wrapper for stop + start. |\n| `cc-gw status` | Show running status, PID, log directory, config path. |\n\n### Environment\n\n| Variable | Purpose |\n| -------- | ------- |\n| `PORT` | Override listening port at launch. |\n| `CC_GW_UI_ROOT` | Manually point to the built web assets. |\n| `CC_GW_DEBUG_ENDPOINTS=1` | Log upstream provider endpoints for debugging. |\n\n### Tips\n\n- Always rebuild `@cc-gw/server` and `@cc-gw/web` before restarts to ensure the daemon picks up new code.\n- If cache statistics remain zero, verify whether the upstream provider exposes `cached_tokens` or equivalent details.\n- Back up `~/.cc-gw/` (config, logs, SQLite DB) for migrations or disaster recovery.\n- Use the **Help** page in the Web UI to review setup steps, troubleshooting tips, and FAQs whenever a teammate needs a refresher.\n\n---\n\n欢迎通过 Issue / PR 反馈改进意见,也可以在 Web UI 的“关于”页查看贡献者信息与致谢。\n"}}}}