Technical Documentation: icebear0828/codex-proxy
ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference
Overview (`README.md`)
Codex Proxy 是一个轻量级本地中转服务,将 Codex Desktop 的 Responses API 转换为多种标准协议接口(OpenAI /v1/chat/completions、Anthropic /v1/messages、Gemini、Codex /v1/responses 直通,以及可选 Ollama /api/chat 兼容桥接)。通过本项目,您可以在 Cursor、Claude Code、Continue、Pi 等任何兼容上述协议的客户端中直接使用 Codex 编程模型。
只需一个 ChatGPT 账号(或接入第三方 API 中转站),配合本代理即可在本地搭建一个专属的 AI 编程助手网关。
🚀 快速开始
前置条件:你需要一个 ChatGPT 账号(免费账号即可)。如果还没有,先去 chat.openai.com 注册一个。
方式一:桌面应用(推荐新手)
下载 → 安装 → 打开就能用。
下载安装包 — 打开 Releases 页面,根据系统下载:
| 系统 | 文件 |
|---|---|
| Windows | Codex Proxy Setup x.x.x.exe |
| macOS | Codex Proxy-x.x.x.dmg |
| Linux | Codex Proxy-x.x.x.AppImage |
安装后打开应用,点击登录按钮用 ChatGPT 账号登录。浏览器访问 http://localhost:8080 即可看到控制面板。
方式二:No-Node Lite(浏览器/服务器版,适合高级用户)
如果你已经安装 Node.js,或者需要在服务器、WSL 等没有桌面环境的机器上运行
Codex Proxy,可以选择 No-Node Lite。它使用与 Electron 版相同的后端和控制面板,
但不内置 Node.js,因此包更小,也方便你自行管理运行时;上面的 Electron 安装包不受影响。
正式制品使用 codex-proxy-<版本>-no-node-lite-all-platforms.zip,解压后在包根目录运行对应入口:
# Windows:双击 codex-proxy.exe(无控制台并驻留托盘);codex-proxy.cmd 始终作为脚本 fallback 保留
# macOS/Linux:
./codex-proxy.sh使用前请准备 Node.js 20 或更新版本。Lite 默认使用与 Electron 相同的系统用户数据目录;
只有显式传入 --portable(简写为 -p)时,才使用发行包目录下的 data/。
可以使用 --mode=server(-m server)只启动服务、--mode=browser 强制使用浏览器,
或在 Windows 上使用 --mode=webview2 强制使用 WebView2。--host、--port、--webview2-host、--node-path 的简写分别是 -H、-P、-w、-n。
Windows 启动器会优先尝试 WebView2;不可用时回退到系统浏览器。缺少 WebView2 运行时
而显式指定 --mode=webview2 时,会先询问,确认后自动下载并运行微软官方在线安装器
(约 2MB,已校验微软签名)安装 WebView2,超时或拒绝则退出。原生codex-proxy.exe 使用托盘运行,codex-proxy.cmd 作为诊断 fallback 保留。
找不到 Node.js 时会显示安装指引,不会静默下载或捆绑 Node。Lite 的“检查更新”打开最新
Releases 页面,暂不自动覆盖正在运行的包。
Linux x64 Lite 同时包含 glibc 和 musl 两种 TLS native addon,可用于常见 Linux 发行版
以及 Alpine Linux;目前不提供 Linux ARM 等其他架构的 native addon。
方式三:npm 安装(适合已有 Node 的开发者)
npm 官方仓库暂未上线,可先从 GitHub Release 下载离线包安装(免认证):
curl -L https://github.com/icebear0828/codex-proxy/releases/latest/download/codex-proxy-npm.zip -o codex-proxy-npm.zip
unzip codex-proxy-npm.zip -d codex-proxy-npm
cd codex-proxy-npm && node install.mjs
codex-proxy
# 打开 http://localhost:8080 登录Windows 用户直接下载并解压 codex-proxy-npm.zip,在解压目录中运行 node install.mjs 即可;
安装脚本会按系统自动选择平台组件,完成后全局可用 codex-proxy 命令。
要求 Node.js 22.13+。运行数据保存在用户数据目录
(Windows %APPDATA%\@codex-proxy\electron\data、Linux ~/.config/@codex-proxy/electron/data、
macOS ~/Library/Application Support/@codex-proxy/electron/data),更新包不会丢失;--portable 或 CODEX_PROXY_DATA_DIR 可自定义位置。更新:重新下载运行 install.mjs。
npm 仓库可用后将简化为 npm install @icebear0828/codex-proxy。
常用参数:--mode=server(纯服务器)、--mode=browser(强制浏览器)、--host / --port。完整参数见 codex-proxy --help。
方式四:Docker 部署
最简单的方式,一条命令即可启动:
docker run -d --name codex-proxy --restart unless-stopped \
-p 127.0.0.1:8080:8080 \
-v codex-proxy-data:/app/data \
-v codex-proxy-config:/app/config \
ghcr.io/icebear0828/codex-proxy:latest-lite
# 打开 http://localhost:8080 登录该镜像基于 Alpine Linux + Node.js,只包含应用本体、前端页面和运行必需的原生组件,编译工具链、依赖缓存等仅构建时使用的内容均已移除;功能完整,Web 面板、账号管理、Ollama 桥接等都可正常使用,目前提供 linux/amd64。压缩后拉取约 57MB(另一版本基于 Debian,约 722MB),空闲内存约 40MB。首次启动会自动在
codex-proxy-config卷中生成默认配置,账号数据保存在codex-proxy-data卷,更新镜像不丢失。需要让局域网其他设备访问时,把端口参数改成-p 8080:8080。
已经在用 docker-compose.yml(默认 :latest 基于 Debian,含编译工具链,便于在容器内调试或从源码构建)的用户无需迁移:两个镜像的目录布局与 ./data、./config 卷完全一致,把 compose 里的 image 换成 ghcr.io/icebear0828/codex-proxy:latest-lite 即可。
需要配置环境变量、自动更新等更多选项时,使用 compose 方式:
mkdir codex-proxy && cd codex-proxy
curl -O https://raw.githubusercontent.com/icebear0828/codex-proxy/main/docker-compose.yml
curl -O https://raw.githubusercontent.com/icebear0828/codex-proxy/main/.env.example
cp .env.example .env
docker compose up -d
# 打开 http://localhost:8080 登录账号数据保存在
data/文件夹,重启不丢失。其他容器连本服务用宿主机 IP(如192.168.x.x:8080),不要用localhost。
取消 docker-compose.yml 中 Watchtower 的注释即可自动更新。若要在 Docker 中启用 Ollama 兼容桥接,请参考下方 Ollama Bridge 配置。
内存设置:
docker-compose.yml默认使用MEM_LIMIT=768m和NODE_OPTIONS=--max-old-space-size=512。在.env中设置这两个变量即可按机器覆盖默认值。不设这两个参数时,Node/V8 会按宿主机全部内存(而不是这个容器实际该用多少)估算堆上限,在内存有限的机器上(尤其是和其他服务共享的 VPS)可能导致内存使用一路涨上去、GC 收得太晚,严重时能把整台宿主机拖垮。请按你机器的实际内存调整这两个值——mem_limit留够给其他服务的余量,--max-old-space-size要明显小于mem_limit(Node 进程的 RSS 不止是 V8 堆)。
方式四:源码运行
git clone https://github.com/icebear0828/codex-proxy.git
cd codex-proxy
npm install # 安装后端依赖
cd web && npm install && cd .. # 安装前端依赖
npm run dev # 开发模式(热重载)
# 或: npm run build && npm start # 生产模式需要 Rust 工具链(用于编译 TLS native addon):
bash# 1. 安装 Rust(如果没有的话) curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh # 2. 编译 TLS addon cd native && npm install && npm run build && cd ..Docker / 桌面应用已内置编译好的 addon,无需手动编译。
打开 http://localhost:8080 登录。
验证
登录后打开控制面板 http://localhost:8080,在 API Configuration 区域找到你的 API Key,然后:
# 把 your-api-key 替换成控制面板里显示的密钥
curl http://localhost:8080/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-api-key" \
-d '{"model":"gpt-5.6-sol","messages":[{"role":"user","content":"Hello!"}],"stream":true}'看到 AI 回复的文字流即部署成功。如果返回 401,请检查 API Key 是否正确。
🌟 核心功能
🔌 全协议兼容
兼容
/v1/chat/completions(OpenAI)、/v1/messages(Anthropic)、Gemini 格式及/v1/responses(Codex 直通)内置可选 Ollama 兼容桥接,默认监听
http://127.0.0.1:11434SSE 流式输出,可直接对接所有 OpenAI / Anthropic SDK 和客户端
自动完成 Chat Completions / Anthropic / Gemini ↔ Codex Responses API 双向协议转换
Structured Outputs —
response_format(json_object/json_schema)和 GeminiresponseMimeTypeFunction Calling — 原生
function_call/tool_calls支持(所有协议)WebSocket 接口 —
/v1/responses支持客户端 WebSocket 流式直连(Bearer 鉴权),HTTP POST + SSE 作为回退保留第三方 API Keys — 支持多协议、按模型直通
📖 完整接口定义与协议说明请查阅 API 文档。
🔐 账号管理与智能轮换
OAuth PKCE 登录 — 浏览器一键授权,无需手动复制 Token
多账号轮换 —
least_used(最少使用优先)、round_robin(轮询)、sticky(粘性)三种策略Plan Routing — 不同 plan(free/plus/team/business)的账号自动路由到各自支持的模型
Token 自动续期 — JWT 到期前自动刷新,指数退避重试
配额采集 — 默认从上游响应头和 WebSocket rate limit 事件被动更新账号额度;用户手动查询单账号额度时会调用
/backend-api/wham/usage,并把remaining_percent = 100 - used_percent写入缓存。封禁检测 — 上游 403 自动标记 banned;401 token 吊销自动过期并切换账号
API Key Provider 池 — 支持通过 Dashboard 管理第三方 API Key、模型列表、导入导出和启停状态。
Web 控制面板 — 账号管理、用量统计、批量操作,中英双语;远程访问需 Dashboard 登录门
后备上游 — 当所有账号均不可用时,自动启用一个可编辑的兜底 API Key
后备状态指示 — 日志与首页明确标注每条请求实际使用的账号,以及进入后备时的状态
🌐 代理池
Per-Account 代理路由 — 为不同账号配置不同的上游代理
四种分配模式 — Global Default / Direct / Auto / 指定代理
健康检查 — 定时 + 手动,通过 ipify 获取出口 IP 和延迟
不可达自动标记 — 代理不可达时自动排除
🛡️ 反检测与协议伪装
Rust Native TLS — 内置 reqwest + rustls native addon,TLS 指纹与真实 Codex 客户端精确一致,跨 Windows / macOS / Linux(含 Alpine)
客户端 Profile 预设 — 支持
codex_cli(默认,官方 CLI 纯净终端头)、codex_desktop(Desktop 完整头)、opencode、pi与custom,CLI 模式下自动剔除浏览器特定头(sec-ch-ua等)按账号 Device ID 隔离 — 为每个账号独立派生并持久化专属的
x-codex-installation-id,彻底杜绝多账号共享同一设备指纹完整请求头仿真 —
originator、User-Agent、x-openai-internal-codex-residency、x-codex-turn-state、x-client-request-id等头按选定 profile 真实模拟发送Cookie 持久化 — 自动捕获和回放 Cloudflare Cookie
指纹自动更新 — 轮询 Codex 更新源,自动同步
app_version和build_number
🏗️ 技术架构
/* Detailed source-code truncated for AI context efficiency. */📦 可用模型
| 模型 ID | 推理等级 | 当前上下文 | 最大上下文 | 最大输出 | 输出 | 说明 |
|---|---|---|---|---|---|---|
gpt-6-astra |
low / medium / high / xhigh / max / ultra | 1,050,000 | 1,050,000 | 128,000 | 文本 | GPT-6 前沿旗舰:复杂推理与端到端 Agent 编码(gpt-6 为其别名) |
gpt-6-astra-aeon |
low / medium / high / xhigh / max / ultra | 1,050,000 | 1,050,000 | 128,000 | 文本 | GPT-6 长程多 Agent 编排与深度推理变体 |
gpt-reserve |
low / medium / high / xhigh / max | 272,000 | 872,000 | 128,000 | 文本 | 快速高性价比 Agent 编码模型(全计划开放) |
gpt-5.6-sol |
low / medium / high / xhigh / max / ultra | 1,050,000 | 1,050,000 | 128,000 | 文本 | GPT-5.6 旗舰:复杂推理与编码(默认;gpt-5.6 为其别名) |
gpt-5.6-terra |
low / medium / high / xhigh / max / ultra | 1,050,000 | 1,050,000 | 128,000 | 文本 | GPT-5.6 智能与成本平衡 |
gpt-5.6-luna |
low / medium / high / xhigh / max / ultra | 1,050,000 | 1,050,000 | 128,000 | 文本 | GPT-5.6 高性价比 / 高吞吐 |
gpt-5.5 |
low / medium / high / xhigh | 272,000 | 272,000 | 128,000 | 文本 | 复杂编码、研究和真实工作流 |
gpt-5.4 |
low / medium / high / xhigh | 272,000 | 1,000,000 | 128,000 | 文本 | 日常编码强模型 |
gpt-5.4-mini |
low / medium / high / xhigh | 400,000 | — | 128,000 | 文本 | 5.4 轻量版 |
gpt-5.3-codex |
low / medium / high / xhigh | 400,000 | — | 128,000 | 文本 | 5.3 编程优化模型 |
gpt-5.2 |
low / medium / high / xhigh | 400,000 | — | 128,000 | 文本 | 专业工作 + 长时间代理 |
gpt-5-codex |
low / medium / high | 400,000 | — | 128,000 | 文本 | GPT-5 编程优化模型 |
gpt-5-codex-mini |
medium / high | — | — | — | 文本 | 轻量 Codex / CLI 编程模型 |
gpt-oss-120b |
low / medium / high | 131,072 | — | — | 文本 | 开源 120B 模型 |
gpt-oss-20b |
low / medium / high | 131,072 | — | — | 文本 | 开源 20B 模型 |
gpt-image-2 |
— | — | — | — | 图像 | 图像生成工具后端(通过 image_generation 调用) |
后缀:任意 chat 模型名后追加
-fast启用 Fast 模式,-high/-low/-max/-ultra切换推理等级。例如:gpt-5.6-sol-fast、gpt-5.6-sol-high-fast、gpt-5.6-sol-max、gpt-5.6-sol-ultra。图像模型(gpt-image-2)不支持后缀。Plan Routing:不同 plan(free/plus/team/business)的账号自动路由到各自支持的模型,模型可用性以登录账号对应的 Codex 后端返回为准,不要按旧的 Plus-only 表理解。模型列表由后端动态获取,自动同步;只要模型出现在 Dashboard /
/v1/models/catalog中,就可以作为请求里的model使用。前端模型选择 ≠ 配置文件:Dashboard 中切换模型只影响前端展示和 API 示例中的模型名,不会修改
config/default.yaml或data/local.yaml中的model.default。实际使用哪个模型取决于客户端请求中的model字段(如 Cursor、Claude Code 等自行指定),配置文件中的model.default仅在客户端未指定模型时作为兜底。Max token 说明:上表跟随当前
config/models.yaml和 Codex runtime/v1/models/catalog元数据;—表示当前目录未返回该字段,不代表模型不可用。运行时从 Codex 后端拉到的模型信息会覆盖静态值,并保留contextWindow、maxContextWindow、maxOutputTokens、truncationPolicyLimit。请求体里的context_window/max_context_window/truncation_policy/max_output_tokens都不是可用开关;直接转发给 Codex 原生接口会返回400 Unsupported parameter。富元数据:
/v1/models与/v1/models/:modelId在 OpenAI 标准字段之外附带 Codex 后端返回的富元数据(display_name、description、supported_reasoning_efforts、input_modalities、service_tiers、visibility、priority等,字段缺失时不输出)。OpenAI 客户端会忽略未知字段,行为不受影响。若下游 Codex CLI 需要完整模型目录,可在 provider 配置中把model_catalog_url指向/v1/models/catalog/codex,该端点返回 CLI 原生解码的{models: [ModelInfo]}富格式:toml[model_providers.codex-proxy] name = "codex-proxy" base_url = "http://127.0.0.1:8080/v1" wire_api = "responses" model_catalog_url = "http://127.0.0.1:8080/v1/models/catalog/codex"鉴权:CLI 会以 provider 的 API Key 调用
model_catalog_url。若代理设置了server.proxy_api_key,请在 provider 配置中提供同一 Key(如env_key = "CODEX_PROXY_KEY"并导出该环境变量),否则目录请求会返回 401。
🖼️ 图像生成
图像生成走 /v1/responses 的 image_generation 内置工具,后端固定为 gpt-image-2。
前提:ChatGPT Plus 及以上 账号(free 账号上游会静默剥掉工具,模型会降级用 SVG 文本假装画图)。
curl -N http://localhost:8080/v1/responses \
-H "Authorization: Bearer $PROXY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-5.6-sol",
"stream": true,
"input": [{"role":"user","content":"Draw a red circle on white background."}],
"tools": [{"type":"image_generation","size":"3840x2160"}]
}'常用参数:size(可请求 1024×1024 / 1024×1536 / 1536×1024 / 2048×2048 / 2048×3072 / 3072×2048 / 3840×2160 / auto)、output_format(png / jpeg / webp)、output_compression(jpeg / webp 可调)、background(auto / opaque)、moderation(auto / low)、partial_images(0–3)。一次只能出 1 张图(n 固定为 1);model 字段不管传什么都会被上游改写为图像工具的实际模型(当前响应回显为 gpt-image-2-codex)。详见 API_CN.md。
size不是固定像素保证。 Proxy 会保留并发送客户端填写的值,但当前上游会把2048x2048、2K、4K等请求归一化为size: "auto",再自行决定实际尺寸。2026-08-10 的真实请求中,size: "2048x2048"的工具配置回显为auto,最终image_generation_call.size和 PNG 像素均为1254x1254。因此不能依靠该字段获得原生、精确的 2K/4K 输出;请以结果 item 的size或解码后图片像素为准。若业务必须拿到精确2048x2048文件,需要在生成后使用插值或 AI 超分辨率进行后处理。
事件流里 image_generation_call item 的 result 字段即 base64 编码的图像;revised_prompt 是上游改写后的最终提示词。
编辑模式(带参考图):在 user message 的 content 里追加 {"type":"input_image","image_url":"data:image/png;base64,..."} 即可。
/v1/chat/completions兼容路径会接受image_generation工具,避免 OpenAI 客户端因 schema 失败;但图像 payload 只有/v1/responses会稳定透出image_generation_call.result。需要拿到图片字节时请使用/v1/responses。
🔗 客户端接入
所有客户端的 API Key 均从控制面板 (
http://localhost:8080) 获取。模型名填具体 ID(默认gpt-5.6-sol)或任意 可用模型 ID。
Claude Code (CLI)
export ANTHROPIC_BASE_URL=http://localhost:8080
export ANTHROPIC_API_KEY=your-api-key
# 切换模型: export ANTHROPIC_MODEL=gpt-5.6-sol / gpt-5.6-terra / gpt-5.6-luna / gpt-5.6-sol-fast ...
claude控制面板的 Anthropic SDK Setup 卡片可一键复制环境变量(含 Opus / Sonnet / Haiku 层级模型配置)。
推荐模型:Opus →
gpt-5.6-sol,Sonnet →gpt-5.6-terra,Haiku →gpt-5.6-luna。⚠️ 配置不生效?请参考 Claude Code 配置避坑指南(AUTH_TOKEN 劫持、API Key 黑名单等常见问题)。
Codex CLI
~/.codex/config.toml:
[model_providers.proxy_codex]
name = "Codex Proxy"
base_url = "http://localhost:8080/v1"
wire_api = "responses"
# 直接把 API Key 写进 config(推荐:本地单用户场景)
[model_providers.proxy_codex.http_headers]
Authorization = "Bearer your-api-key"
[profiles.default]
model = "gpt-5.6-sol"
model_provider = "proxy_codex"💡 也可以改用环境变量:把
[model_providers.proxy_codex.http_headers]这两行删掉,换成env_key = "PROXY_API_KEY",然后export PROXY_API_KEY=your-api-key && codex。需要避免密钥落到 config 文件(多人共享 / 开源仓库)时用这个。
Claude Desktop
开启开发者模式:点击菜单栏 Help → Troubleshooting → Enable Developer Mode。
配置第三方推理:点击菜单栏新出现的 Developer → Configure Third-Party Inference...。
填写配置:
Endpoint:
http://127.0.0.1:8080API Key: 你的 API Key
Model:
claude-opus-4-7/claude-sonnet-4-6/claude-haiku-4-5
或手动修改配置文件(Windows 下路径通常在
%APPDATA%\Claude-3p\configLibrary\目录下的 JSON 文件,Mac 为~/Library/Application Support/Claude-3p/configLibrary/),添加如下字段:
{
"disableDeploymentModeChooser": true,
"inferenceProvider": "gateway",
"inferenceGatewayBaseUrl": "http://127.0.0.1:8080",
"inferenceGatewayApiKey": "your-api-key",
"inferenceGatewayAuthScheme": "bearer",
"inferenceModels": [
"claude-opus-4-7",
"claude-sonnet-4-6",
"claude-haiku-4-5"
]
}内置 Claude 形态模型名会映射到 Codex 模型。自定义映射请写到 data/local.yaml,不要改 config/models.yaml:
model:
aliases:
claude-opus-4-7: gpt-5.6-sol
claude-sonnet-4-6: gpt-5.6-terra
claude-haiku-4-5: gpt-5.6-luna
my-openai: openai:gpt-4o
my-deepseek: deepseek-chatalias 左边是客户端请求里填写的模型名,右边是真正发给上游的模型名。右侧可以是 Codex 模型 ID、带 provider 前缀的模型(如 openai:gpt-4o / anthropic:claude-sonnet-4-5 / gemini:gemini-2.5-pro),也可以是已通过 model_routing 绑定到自定义 provider 的模型名(如 deepseek-chat)。别名会出现在 /v1/models,请求进入直连 provider 时会自动把模型名改写成映射目标。
💡 排查提示 (Windows): 如果使用
127.0.0.1时 Claude Desktop 提示ERR_CONNECTION_REFUSED(而使用localhost提示 URL 格式错误),说明 Node.js 在你的系统上默认只绑定了 IPv6。请进入 Codex Proxy 控制面板的设置页面,将 Host 修改为127.0.0.1,或在data/local.yaml中添加server: { host: "127.0.0.1" }后重启代理。💡 局域网使用提示 (LAN): Claude Desktop 强制校验 API 地址,只允许
https://开头或http://127.0.0.1。如果你将 Codex Proxy 部署在局域网另一台机器(如192.168.x.x),直接填入会报错。解决方法:
- SSH 隧道 (最简单):在客户端机器运行
ssh -L 8080:127.0.0.1:8080 [email protected],然后在 Claude 里填http://127.0.0.1:8080。- 反向代理:使用 Caddy 或 Nginx 配置局域网 HTTPS 证书。
Codex Desktop (官方应用)
官方客户端与 CLI 共用配置文件,修改后需重启客户端生效。
~/.codex/config.toml:
[model_providers.proxy_codex]
name = "Codex Proxy"
base_url = "http://localhost:8080/v1"
wire_api = "responses"
[model_providers.proxy_codex.http_headers]
Authorization = "Bearer your-api-key"
[profiles.default]
model = "gpt-5.6-sol"
model_provider = "proxy_codex"💡 为什么不用
env_key? macOS / Windows 的 GUI 应用不读 shell 的~/.zshrc/.bashrc,光export PROXY_API_KEY=...在终端里 GUI 进程根本看不到,启动会直接报Missing environment variable。http_headers把 Authorization 写在 config 里,重启 Codex 就能用,不用折腾launchctl setenv或 LaunchAgent。需要密钥从配置文件解耦时(共享机器 / 仓库提交)再换回env_key = "PROXY_API_KEY"走环境变量。⚠️ 如果你是通过"登录 ChatGPT 账号"方式使用的,客户端可能会忽略此配置——只要
[model_providers.proxy_codex]配上、profiles.default.model_provider = "proxy_codex",新会话就会走 proxy;登录会话仍可能直接走官方上游。
Claude for VSCode / JetBrains
打开 Claude 扩展设置,找到 API Configuration:
API Provider: 选择 Anthropic
Base URL:
http://localhost:8080API Key: 你的 API Key
或在 VS Code settings.json 中添加:
{
"claude.apiEndpoint": "http://localhost:8080",
"claude.apiKey": "your-api-key"
}Cursor
- 打开 Settings → Models
- 选择 OpenAI API
- 设置 Base URL:
http://localhost:8080/v1 - 设置 API Key: 你的 API Key
- 添加模型名
gpt-5.6-sol(或其他模型 ID)
Windsurf
- 打开 Settings → AI Provider
- 选择 OpenAI Compatible
- API Base URL:
http://localhost:8080/v1 - API Key: 你的 API Key
- Model:
gpt-5.6-sol
Cline (VSCode 扩展)
- 打开 Cline 侧边栏 → 设置齿轮
- API Provider: 选择 OpenAI Compatible
- Base URL:
http://localhost:8080/v1 - API Key: 你的 API Key
- Model ID:
gpt-5.6-sol
Continue (VSCode 扩展)
~/.continue/config.json:
{
"models": [{
"title": "Codex",
"provider": "openai",
"model": "gpt-5.6-sol",
"apiBase": "http://localhost:8080/v1",
"apiKey": "your-api-key"
}]
}aider
aider --openai-api-base http://localhost:8080/v1 \
--openai-api-key your-api-key \
--model openai/gpt-5.6-sol或设置环境变量:
export OPENAI_API_BASE=http://localhost:8080/v1
export OPENAI_API_KEY=your-api-key
aider --model openai/gpt-5.6-solCherry Studio
- 设置 → 模型服务 → 添加
- 类型: OpenAI
- API 地址:
http://localhost:8080/v1 - API Key: 你的 API Key
- 添加模型
gpt-5.6-sol
Pi Coding Agent (pi)
Pi Coding Agent (@earendil-works/pi-coding-agent) 可通过 ~/.pi/agent/models.json 配置自定义 Provider 接入 Codex Proxy。
方式一:OpenAI Completions 协议(推荐)
编辑 ~/.pi/agent/models.json:
{
"providers": {
"codex-proxy": {
"baseUrl": "http://localhost:8080/v1",
"api": "openai-completions",
"apiKey": "your-api-key",
"models": [
{
"id": "gpt-5.6-sol",
"name": "Codex GPT-5.6 Sol",
"contextWindow": 1050000,
"maxTokens": 128000,
"input": ["text", "image"]
},
{
"id": "gpt-5.6-terra",
"name": "Codex GPT-5.6 Terra",
"contextWindow": 1050000,
"maxTokens": 128000,
"input": ["text", "image"]
}
]
}
}
}💡
apiKey也可配置为"$PROXY_API_KEY",并在运行终端中通过export PROXY_API_KEY=your-api-key注入。
方式二:Anthropic Messages 协议
{
"providers": {
"codex-proxy-anthropic": {
"baseUrl": "http://localhost:8080",
"api": "anthropic-messages",
"apiKey": "your-api-key",
"models": [
{
"id": "gpt-5.6-sol",
"name": "Codex GPT-5.6 Sol",
"contextWindow": 1050000,
"maxTokens": 128000,
"input": ["text", "image"]
}
]
}
}
}方式三:Codex Responses 协议(直通)
{
"providers": {
"codex-proxy-responses": {
"baseUrl": "http://localhost:8080/v1",
"api": "openai-responses",
"apiKey": "your-api-key",
"models": [
{
"id": "gpt-5.6-sol",
"name": "Codex GPT-5.6 Sol",
"contextWindow": 1050000,
"maxTokens": 128000,
"input": ["text", "image"]
}
]
}
}
}启动运行:
pi --provider codex-proxy --model gpt-5.6-solOllama 兼容客户端
在 Dashboard → Settings → Ollama Bridge 中启用后,可使用 Ollama 默认地址:
| 设置项 | 值 |
|---|---|
| Base URL | http://localhost:11434 |
| API Key | 不需要,Bridge 内部会使用 Codex Proxy 的密钥访问主服务 |
| Model | gpt-5.6-sol(或其他模型 ID) |
curl http://localhost:11434/api/tags
curl http://localhost:11434/api/chat \
-H "Content-Type: application/json" \
-d '{"model":"gpt-5.6-sol","messages":[{"role":"user","content":"Hello!"}],"stream":true}'Ollama API 本身没有鉴权。默认仅监听
127.0.0.1,不建议暴露到公网或未信任的局域网。
通用 OpenAI 兼容客户端
任何支持自定义 OpenAI API Base 的客户端均可接入:
| 设置项 | 值 |
|---|---|
| Base URL | http://localhost:8080/v1 |
| API Key | 控制面板获取 |
| Model | gpt-5.6-sol(或其他模型 ID) |
Python
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8080/v1", api_key="your-api-key")
for chunk in client.chat.completions.create(
model="gpt-5.6-sol", messages=[{"role": "user", "content": "Hello!"}], stream=True
):
print(chunk.choices[0].delta.content or "", end="")Node.js
import OpenAI from "openai";
const client = new OpenAI({ baseURL: "http://localhost:8080/v1", apiKey: "your-api-key" });
const stream = await client.chat.completions.create({
model: "gpt-5.6-sol", messages: [{ role: "user", content: "Hello!" }], stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content || "");
}⚙️ 配置说明
重要:不要直接修改
config/default.yaml,该文件会在版本更新时被覆盖。自定义配置请通过 Dashboard 设置面板修改(自动保存到data/local.yaml),或手动创建data/local.yaml写入需要覆盖的字段。data/目录不受更新影响。
Docker 部署的差异:容器启动时只从镜像内的默认配置按文件补种缺失项(
cp -rn,只补不覆盖)。因此升级镜像后新增的默认配置文件(如model-pricing.yaml)会自动出现在已有配置卷中,而你改过的文件不会被覆盖;反过来说,config/卷里已存在的旧默认值也不会随镜像更新。无论哪种部署方式,自定义配置都请写入data/local.yaml。
CORS 允许主机
通过环境变量 CORS_ALLOWED_HOSTS 可以配置允许跨域访问的主机列表,对应配置文件中的 server.cors 字段。多个主机名用逗号分隔:
export CORS_ALLOWED_HOSTS="example.com,another-domain.com"或在 data/local.yaml 中配置:
server:
cors:
- "https://example.com"
- "https://another-domain.com"默认配置位于 config/default.yaml:
| 分类 | 关键配置 | 说明 |
|---|---|---|
server |
host, port, proxy_api_key |
监听地址与 API 密钥 |
api |
base_url, timeout_seconds |
上游 API 地址与超时 |
client |
profile, originator, app_version, build_number, platform, arch, chromium_version |
客户端指纹预设(codex_cli / codex_desktop / opencode / pi / custom)及版本参数 |
model |
default, default_reasoning_effort, default_service_tier, aliases, custom_models, inject_desktop_context |
默认模型、推理配置、模型映射与自定义模型目录 |
auth |
rotation_strategy, rate_limit_backoff_seconds |
轮换策略与限流退避 |
tls |
proxy_url, force_http11 |
TLS 代理与 HTTP 版本 |
quota |
refresh_interval_minutes, warning_thresholds, skip_exhausted |
用量快照、阈值配置与耗尽账号跳过 |
session |
ttl_minutes, cleanup_interval_minutes |
Dashboard session 管理 |
ollama |
enabled, host, port, version, disable_vision |
Ollama 兼容桥接 |
official_agent |
enabled, api_key, app_server_url, auth |
官方 Codex app-server 桥接,用于复用 Chrome/browser 插件 |
客户端 Profile 与指纹预设
client.profile 支持一键切换客户端身份,自动调整请求头组合与反检测特征:
client:
profile: codex_cli # 预设: codex_cli (默认), codex_desktop, opencode, pi, custom
# 预设说明:
# - codex_cli: 官方 Codex CLI 纯净终端头 (originator: codex_cli_rs),剔除所有浏览器特有头 (sec-ch-ua 等)
# - codex_desktop: 官方 Codex Desktop 完整头 (originator: Codex Desktop),包含 sec-ch-ua 与 Chromium 版本
# - opencode: opencode 终端头 (originator: opencode)
# - pi: pi 终端头 (originator: pi)
# - custom: 完全自定义模式,读取 client.originator 及 fingerprint.yaml 模板同时,代理为每个绑定的账号自动独立派生并持久化专属的 x-codex-installation-id(储存于 data/installation_ids/),确保多账号并发/轮换时各账号具有独立的客户端设备身份,避免上游根据设备 UUID 产生关联。
模型映射
model.aliases 用来把客户端里的模型名映射成真实上游模型,适合 Claude Desktop / Cursor / Continue 等客户端只能选择固定模型名、或你希望暴露更短别名的场景。
也可以直接在 Dashboard → Settings → 模型映射 中添加 / 删除映射。保存后会写入 data/local.yaml 并热加载到后端,不需要修改 config/default.yaml。
model:
aliases:
claude-opus-4-7: gpt-5.6-sol
sonnet-local: gpt-5.6-terra
openai-fast: openai:gpt-4o
deepseek-local: deepseek-chat
providers:
custom:
deepseek:
api_key: "sk-..."
base_url: "https://api.deepseek.com/v1"
models: ["deepseek-chat"]
model_routing:
deepseek-chat: deepseek映射解析发生在 model_routing 和内置 Claude/Gemini 自动路由之前。映射到 Codex 模型时仍支持 -fast / -high 等后缀;映射到第三方 provider 时,直连请求会把 model 字段改写成右侧目标值。
如果你还需要把完全自定义的 Codex-compatible 模型 ID 加入模型目录,可在 data/local.yaml 中配置 model.custom_models。简单字符串会使用默认 text/medium 元数据;对象写法可补 display name、推理等级、上下文和输出上限:
model:
custom_models:
- local-simple
- id: local-rich
display_name: Local Rich
description: Local rich model
supported_reasoning_efforts: [low, high]
default_reasoning_effort: high
input_modalities: [text, image]
output_modalities: [text]
context_window: 12345
max_context_window: 23456
max_output_tokens: 3456配额轮转
quota.skip_exhausted: true 时,账号池会在选择账号前跳过缓存额度已经耗尽的账号;这个过滤发生在 session affinity / preferredEntryId 之前,所以长对话也不会强行粘到已耗尽账号上。
当前跳过条件是缓存额度里的 rate_limit.limit_reached === true、secondary_rate_limit.limit_reached === true 或 code_review_rate_limit.limit_reached === true。如果只是 used_percent 接近 100(例如 99%)但上游还没标记 limit_reached,代理仍会继续使用该账号;真正打到上游 429 后,账号会进入 rate_limited 退避并切换到其他可用账号。secondary / code review 窗口自己的 reset_at 过期后会从缓存中清除,避免账号被永久跳过。
局域网访问
源码默认配置仅监听 127.0.0.1;Electron 也会传入 127.0.0.1,除非 data/local.yaml 显式覆盖。Docker 镜像会通过 CODEX_PROXY_HOST=0.0.0.0 在容器内监听所有接口,docker-compose.yml 默认仍只把宿主机端口绑定到 127.0.0.1。
需要仅本机访问时写入:
server:
host: "127.0.0.1"如需局域网内其他设备访问,在 data/local.yaml 中添加,并把 docker-compose.yml 的端口映射从 127.0.0.1:${PORT:-8080}:8080 改成 ${PORT:-8080}:8080:
server:
host: "0.0.0.0"Electron 桌面版的 data/local.yaml 路径:
当前 Electron 构建的实际 app.getPath("userData") 目录名为@codex-proxy/electron;下面路径以该目录为准。
| 系统 | 路径 |
|---|---|
| macOS | ~/Library/Application Support/@codex-proxy/electron/data/local.yaml |
| Windows | %APPDATA%/@codex-proxy/electron/data/local.yaml |
| Linux | ~/.config/@codex-proxy/electron/data/local.yaml |
⚠️ 绑定
0.0.0.0会将服务暴露到局域网,务必在 Dashboard → 密钥设置中配置强密钥。
TLS 配置
tls:
proxy_url: null # null = 自动检测本地代理;填写代理 URL 指定上游代理
force_http11: false # HTTP/2 失败时自动降级 HTTP/1.1;true = 强制 HTTP/1.1内置 Rust native addon(reqwest + rustls),TLS 指纹与真实 Codex Desktop 完全一致。源码运行需先编译:
cd native && npm install && npm run build。
API 密钥
server:
proxy_api_key: "pwd" # 自定义密钥,客户端用 Bearer pwd 访问
# proxy_api_key: null # null = 不配置全局密钥;已登录账号仍会生成 account-level codex-proxy-xxxx 密钥首次启动如果缺少 data/local.yaml,程序会自动创建 server.proxy_api_key: pwd。当前可用密钥显示在控制面板的 API Configuration 区域。
Ollama Bridge 配置
ollama:
enabled: false # true = 启动内置 Ollama 兼容监听器
host: 127.0.0.1 # 默认仅本机可访问
port: 11434 # Ollama 默认端口
version: "0.18.3" # /api/version 返回值
disable_vision: false # true = /api/show 不声明 vision 能力支持的 Ollama 端点:
| 端点 | 方法 | 说明 |
|---|---|---|
http://localhost:11434/api/version |
GET | Ollama 版本探测 |
http://localhost:11434/api/tags |
GET | 模型列表 |
http://localhost:11434/api/show |
POST | 模型元数据 |
http://localhost:11434/api/chat |
POST | 聊天补全,支持流式 NDJSON |
http://localhost:11434/v1/* |
任意 | OpenAI /v1 直通 |
Docker 部署时,如果希望宿主机访问 11434:
- 在 Dashboard 或
data/local.yaml中设置ollama.enabled: true和ollama.host: 0.0.0.0。 - 取消
docker-compose.yml中127.0.0.1:${OLLAMA_BRIDGE_PORT:-11434}:11434端口映射的注释。 - 保持宿主机绑定
127.0.0.1,除非你明确知道自己要把无鉴权 Ollama API 暴露到网络。
浏览器 CORS 访问仅允许 localhost、127.x.x.x、::1 等 loopback origin;非本机网页来源不能读取桥接响应。Bridge 会为 /v1/* 直通请求注入已配置的 Codex Proxy API Key,因此暴露到 localhost 之外时,相当于也把主代理 API 以无鉴权方式暴露出去。
Official Agent Bridge 配置
该桥接用于连接本机官方 codex app-server,从而复用 Codex app 的官方 Chrome/browser 插件、审批和 app mention 能力。默认关闭,不影响现有 /v1/* 模型代理。
先启动官方 app-server:
codex app-server --listen ws://127.0.0.1:4500然后在 data/local.yaml 启用:
server:
proxy_api_key: "your-api-key"
official_agent:
enabled: true
api_key: "your-official-agent-key"
app_server_url: ws://127.0.0.1:4500
auth:
type: none如果 app-server 使用 capability token:
codex app-server --listen ws://127.0.0.1:4500 \
--ws-auth capability-token \
--ws-token-file /absolute/path/to/token对应配置:
server:
proxy_api_key: "your-api-key"
official_agent:
enabled: true
api_key: "your-official-agent-key"
app_server_url: ws://127.0.0.1:4500
auth:
type: capability_token
token_file: /absolute/path/to/token可用端点:
curl http://localhost:8080/official-agent/apps \
-H "Authorization: Bearer your-official-agent-key"curl -N http://localhost:8080/official-agent/threads/{threadId}/turns \
-H "Authorization: Bearer your-official-agent-key" \
-H "Content-Type: application/json" \
-d '{"text":"Open localhost:8080 and inspect the dashboard","app":{"id":"chrome","name":"Chrome"}}'环境变量覆盖
| 环境变量 | 覆盖配置 |
|---|---|
PORT |
server.port |
CODEX_PROXY_HOST |
server.host(仅当 data/local.yaml 未显式设置 server.host 时生效) |
CODEX_PLATFORM |
client.platform |
CODEX_ARCH |
client.arch |
HTTPS_PROXY |
tls.proxy_url |
OLLAMA_BRIDGE_ENABLED |
ollama.enabled |
OLLAMA_BRIDGE_HOST |
ollama.host |
OLLAMA_BRIDGE_PORT |
ollama.port |
OLLAMA_BRIDGE_VERSION |
ollama.version |
OLLAMA_BRIDGE_DISABLE_VISION |
ollama.disable_vision |
📡 API 端点
协议端点
| 端点 | 方法 | 说明 |
|---|---|---|
/v1/chat/completions |
POST | OpenAI 格式聊天补全 |
/v1/responses |
POST | Codex Responses API 直通 |
/v1/responses/compact |
POST | Codex 远程 compact 响应代理 |
/v1/alpha/search |
POST | Codex standalone Web Search(codex-responses API-key wire) |
/v1/images/generations |
POST | Codex JSON 图片生成直通(codex-responses API-key wire) |
/v1/images/edits |
POST | Codex JSON 图片编辑直通(codex-responses API-key wire) |
/v1/messages |
POST | Anthropic 格式聊天补全 |
/v1/models |
GET | 可用模型列表(含 Codex 后端富元数据:描述、推理档位、模态、service tiers 等) |
/v1/models/catalog |
GET | Dashboard 使用的完整模型目录 |
/v1/models/catalog/codex |
GET | Codex CLI model_catalog_url 兼容的富目录({models: [ModelInfo]}) |
/v1/models/:modelId/info |
GET | 单个模型的推理等级等详情 |
/v1beta/models |
GET | Gemini 格式模型列表 |
/v1beta/models/:modelAction |
POST | Gemini generateContent / streamGenerateContent |
:11434/api/chat |
POST | Ollama 兼容聊天补全(需启用 Ollama Bridge) |
账号与认证
| 端点 | 方法 | 说明 |
|---|---|---|
/auth/login |
GET | OAuth 登录入口 |
/auth/accounts |
GET | 账号列表(含缓存额度) |
/auth/accounts |
POST | 添加单个账号(token 或 refreshToken) |
/auth/accounts/import |
POST | 批量导入账号(JSON / text/plain token 行) |
/auth/accounts/export |
GET | 导出账号(`?format=full |
/auth/accounts/batch-delete |
POST | 批量删除账号 |
/auth/accounts/batch-status |
POST | 批量修改账号状态 |
/auth/accounts/health-check |
POST | 批量检测账号可用性 |
/auth/accounts/:id/refresh |
POST | 刷新并探测单个账号 |
/auth/accounts/:id/quota |
GET | 主动查询单个账号额度 |
/auth/accounts/:id/cookies |
GET/POST/DELETE | 管理账号 Cloudflare cookies |
/auth/quota/warnings |
GET | 当前额度预警状态 |
第三方 API Keys
Antigravity OAuth 账号也可在 Dashboard 的 Provider 池中添加:输入 Google OAuth refresh_token,手动填写模型 ID;Google Cloud Project ID 可留空,由 loadCodeAssist 自动发现。若账号未返回项目 ID,请手动填写。OAuth client ID 和 secret 均有内置默认值,通常无需设置环境变量;如 refresh token 来自其他 OAuth client,可通过 ANTIGRAVITY_OAUTH_CLIENT_ID 和 ANTIGRAVITY_OAUTH_CLIENT_SECRET 覆盖。请求和 /v1/models 使用 antigravity:<model-id> 名称。
对于在标准 Responses API 上要求 Codex 官方客户端上下文的 API-key 上游,请在 Dashboard 中选择 Custom Provider 和 Codex Responses (client context) 协议。Base URL 应填写 API v1 根地址(例如 https://provider.example.com/v1,不要填写完整的 /responses 地址)。该协议的主 Responses 请求使用 HTTP SSE,并发送 Codex headers、installation/session/thread/window ID 与 client metadata;同时支持按请求 body 的 model 路由 standalone Web Search、远程 compact 和 Codex JSON 图片生成/编辑端点,不支持 Embeddings。若供应商没有提供兼容的 /models 接口,可在 Dashboard 中手动填写模型名。
| 端点 | 方法 | 说明 |
|---|---|---|
/auth/api-keys/catalog |
GET | 内置 Provider 与推荐模型目录 |
/auth/api-keys |
GET/POST | API Key 列表 / 添加 |
/auth/api-keys/models |
POST | 从自定义 OpenAI-compatible Provider 拉取模型 |
/auth/api-keys/export |
GET | 导出 API Key 配置 |
/auth/api-keys/import |
POST | 导入 API Key 配置 |
/auth/api-keys/batch-delete |
POST | 批量删除 API Key |
/auth/api-keys/:id |
DELETE | 删除单个 API Key |
/auth/api-keys/:id/label |
PATCH | 修改 API Key 标签 |
/auth/api-keys/:id/status |
PATCH | 启用或停用 API Key |
账号导入导出示例
# 导出所有账号(完整格式,含 token)
curl -s http://localhost:8080/auth/accounts/export \
-H "Authorization: Bearer your-api-key" > backup.json
# 导出精简格式(仅 refreshToken + label,适合分享)
curl -s "http://localhost:8080/auth/accounts/export?format=minimal" \
-H "Authorization: Bearer your-api-key" > backup-minimal.json
# 导出第三方兼容格式
curl -s "http://localhost:8080/auth/accounts/export?format=sub2api" \
-H "Authorization: Bearer your-api-key" > sub2api-accounts.json
# 批量导入(支持 token、refreshToken,或两者同时传)
curl -X POST http://localhost:8080/auth/accounts/import \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-api-key" \
-d '{
"accounts": [
{ "token": "eyJhbGciOi..." },
{ "refreshToken": "v1.abc..." },
{ "refreshToken": "v1.def...", "label": "备用账号" }
]
}'
# 返回: { "added": 2, "updated": 1, "failed": 0, "errors": [] }
# text/plain token 行导入(每行 access token 或 refresh token)
curl -X POST http://localhost:8080/auth/accounts/import \
-H "Content-Type: text/plain" \
-H "Authorization: Bearer your-api-key" \
--data-binary $'eyJhbGciOi...\noaistb_rt_...\n'
# 备份恢复一键操作(导出后直接导入到另一个实例)
curl -X POST http://localhost:8080/auth/accounts/import \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-api-key" \
-d @backup.json管理接口
| 端点 | 方法 | 说明 |
|---|---|---|
/admin/rotation-settings |
GET/POST | 轮换策略配置 |
/admin/quota-settings |
GET/POST | 额度刷新与预警配置 |
/admin/ollama-settings |
GET/POST | Ollama Bridge 配置 |
/admin/ollama-status |
GET | Ollama Bridge 运行状态 |
/admin/refresh-models |
POST | 手动刷新模型列表 |
/admin/usage-stats/summary |
GET | 用量统计汇总 |
/admin/usage-stats/history |
GET | 用量时间序列 |
/admin/logs |
GET | 请求日志列表 |
/admin/logs/state |
GET/POST | 日志采集开关与配置 |
/admin/update-status |
GET | 自更新状态 |
/admin/check-update |
POST | 检查更新 |
/admin/apply-update |
POST | 执行自更新 |
/health |
GET | 健康检查 |
代理池
| 端点 | 方法 | 说明 |
|---|---|---|
/api/proxies |
GET/POST | 代理池列表 / 添加代理 |
/api/proxies/:id |
PUT/DELETE | 更新 / 删除代理 |
/api/proxies/:id/check |
POST | 健康检查单个代理 |
/api/proxies/check-all |
POST | 全部代理健康检查 |
/api/proxies/assign |
POST | 为账号分配代理 |
/api/proxies/assignments |
GET | 查看账号代理分配 |
/api/proxies/assign-bulk |
POST | 批量分配代理 |
/api/proxies/assign-rule |
POST | 按规则分配代理 |
/api/proxies/export |
GET | 导出代理池 YAML |
/api/proxies/import |
POST | 导入代理池 YAML |
📋 系统要求
Node.js 18+(推荐 20+)
Rust — 源码运行需 Rust 工具链(编译 TLS native addon);Docker / 桌面应用已内置
ChatGPT 账号 — 免费账号即可
Docker(可选)
⚠️ 注意事项
Codex API 为流式输出专用,
stream: false时代理内部流式收集后返回完整 JSON本项目依赖 Codex Desktop 的公开接口,上游版本更新时会自动检测并更新指纹
Windows 下 native TLS addon 需 Rust 工具链编译;Docker 部署已预编译,无需额外配置
📝 最近更新
完整更新日志请查看 CHANGELOG.md。
☕ 赞赏 & 交流
觉得有帮助?请作者喝杯咖啡,或加入 Telegram 交流群获取使用帮助。二维码见 页面顶部。
🙏 贡献致谢
Codex Proxy 最初只是一个个人自用项目,一路走来收获了超乎预期的关注与支持。
特别感谢所有通过代码、文档、修复或 PR 参与建设的贡献者:
@SsuJojo · @TutuchanXD · @kanweiwei · @et2010 · @d-demand-priv · @hangox · @jarvisluk · @jeasonstudio · @JPClaw12 · @lezi-fun · @lookvincent · @pocper1 · @woai66 · @xsShuang · @yuwei5380 · @aeltorio · @williamjameshandley · @FlavienKlr · @zyycn
感谢所有在 Issues 里提交 bug 复现、日志、兼容性反馈和功能建议的用户。这些反馈直接推动了账号轮换、代理兼容、Dashboard、Ollama Bridge、模型兼容和错误观测等能力的迭代。
更要由衷感谢所有默默使用、关注和支持本项目的开发者朋友们。正是你们的认可与喜爱,让我一直坚持维护和迭代到现在。很高兴有这么多人喜欢 Codex Proxy! ❤️
⭐ Star History
📄 许可协议
本项目采用 非商业许可 (Non-Commercial):
允许:个人学习、研究、自用部署
禁止:任何形式的商业用途,包括但不限于出售、转售、收费代理、商业产品集成
本项目与 OpenAI 无关联。使用者需自行承担风险并遵守 OpenAI 的服务条款。
Overview (`bin/README.md`)
This directory is reserved for runtime helper binaries.
Electron packaging and path resolution expect bin/ to exist at the repo root,
even in source checkouts where the actual binaries are provided separately.
Overview (`tests/README.md`)
Test Suite
Quick Start
npm test # auto-detects Windows/Linux suite from the host OS
npm run test:windows # explicitly select Windows-compatible coverage
npm run test:linux # explicitly select POSIX/native Linux coverage
npm run test:unit # unit tests only
npm run test:e2e # e2e tests only
npm run test:integration # integration tests only
npm run test:stress # stress tests (separate config, 120s timeout)
npm run test:real # real upstream tests (requires running proxy)The Windows and Linux configs share vitest.shared-config.ts, test discovery, aliases, and test definitions. Add ordinary tests once under the existing shared, tests/unit, tests/integration, tests/contract, or tests/e2e trees; both platform suites discover them automatically. Wrap OS-native behavior in a shared describePosix or describeWindows block from tests/_helpers/platform-test.ts rather than copying the test cases. POSIX shell tests run on Linux; the Windows suite keeps shared tests and Windows-compatible coverage.
Structure
/* Detailed source-code truncated for AI context efficiency. */Vitest Configs
| Config | Scope | Platform | Notes |
|---|---|---|---|
vitest.shared-config.ts |
aliases + common test discovery | Shared | Factory consumed by both platform configs |
vitest.windows.config.ts |
shared unit + integration + e2e + portable Electron unit tests | Windows | Excludes native Electron build/pack/release integration; npm run test:windows |
vitest.linux.config.ts |
shared unit + integration + e2e + electron | Linux | Full POSIX/native suite; runs from npm run test:linux |
vitest.config.ts (root) |
host-selected suite | Windows/Linux auto-detect; full suite elsewhere | Used by npm test and ad hoc Vitest commands |
tests/vitest.config.ts |
stress | Any | 120s timeout; npm run test:stress |
tests/real/vitest.config.ts |
real | Any | 60s timeout; npm run test:real |
Real-Upstream Coverage Gaps (accepted risk)
The default npm run test:real suite only exercises free-tier accounts. The following paths have never been validated against a real Plus/Team upstream and are covered by mocks/fixtures only — documented as accepted risk (#377):
- Secondary rate-limit rotation —
secondary-quota.test.tsstress scenarios use mocks only. - Team/Plus plan model access — e.g.
gpt-5.4returns400on free accounts. - Credits balance management —
creditsisnullfor free accounts. - Rate-limit (429) fallback recovery — cannot trigger a real 429 to validate recovery.
- Prompt cache hit rates — upstream returns
cached_tokens=0for free accounts.
Mocks validate plumbing (field presence, type correctness) but cannot catch cross-plan behavioral differences. When a Plus/Team test account or recorded real-tier fixtures become available, revisit these paths and extend tests/real/.
Conventions
- All test imports use
@src/alias (never relative../intosrc/) - Helpers use
@helpers/alias, fixtures use@fixtures/ - E2E tests mock only external boundaries (TLS transport, fs, background tasks)
- Stress and real tests run serially (
maxForks: 1) - Zero
anytypes in test code
E2E Architecture
[Test] → Hono App → Route → translateRequest → handleProxyRequest → CodexApi → [Mock Transport]
↑ real ↑ real ↑ mockedMocked: @src/tls/transport.js, @src/config.js, @src/paths.js, fs (models.yaml only), background tasks.
Real: AccountPool, CookieJar, ProxyPool, CodexApi, all translation layers, all middleware.
Overview (`packages/npm/README.md`)
@icebear0828/codex-proxy
OpenAI-compatible proxy for the ChatGPT Codex Responses API, with a web dashboard, a multi-account key pool and an Ollama-compatible bridge. This is the full application — dashboard, account management and the Ollama bridge all work the same as the desktop and Docker versions.
Install
Requires Node.js 22.13+ (uses the built-in node:sqlite).
npm install @icebear0828/codex-proxyRun
codex-proxy # starts the server and opens the dashboard
codex-proxy --mode=server # headless server only
codex-proxy --mode=browser # force the system browser
codex-proxy --help # all optionsOn first start the dashboard opens at http://127.0.0.1:8080 (port configurable via --port or PORT). On Windows the dashboard opens in your system browser; the desktop app and the Lite zip ship a native WebView2 host, which the npm package does not include.
Runtime data (accounts, config, usage history) is stored in the per-user data directory (%APPDATA%\@codex-proxy\electron\data on Windows, ~/.config/@codex-proxy/electron/data on Linux, ~/Library/Application Support/@codex-proxy/electron/data on macOS), so it survives package updates. Set CODEX_PROXY_DATA_DIR or pass --portable to relocate it. Platform-specific TLS addons are installed automatically for your OS/architecture; binaries for other platforms are never downloaded.
Links
- GitHub repository
- Documentation & screenshots
- Desktop installers, the portable zip and Docker images are published on the releases page.
License
Non-commercial licence — see LICENCE.
Overview (`scripts/portable/README.md`)
No-Node Lite Browser/Server distribution
This distribution keeps the existing Electron package unchanged. It contains
the bundled backend and web assets, but does not contain Node.js. It uses the
same per-user data directory as Electron by default; pass --portable when
you explicitly want runtime data beside the package.
After extracting the zip archive, the top-level entry points are:
codex-proxy.exeon Windows when the native launcher was built;codex-proxy.cmdon Windows, always included as a script fallback;codex-proxy.shon macOS/Linux.
The launcher uses the system Node.js by default. Node.js 20 or newer is
required for this release. A custom path can be supplied before the
application arguments:
codex-proxy.exe -n C:\Tools\node.exe -m browser
./codex-proxy.sh -n /opt/node/bin/node -m serverIf no mode is supplied to the Windows native launcher, it checks for the
packaged WebView2 host and an installed WebView2 Runtime. When both are
available it starts the embedded WebView2 window; otherwise it starts the
server and opens the actual server URL in the default browser. The native
Windows launcher also stays in the notification area and provides Open
Dashboard and Quit actions. The URL is generated from the bound port, so a
configured port or an automatic port fallback is respected. The .cmd
launcher keeps the same Windows auto behavior for diagnostics. The POSIX
launcher uses browser mode by default, including when it is invoked from Git
Bash on Windows; pass --mode=auto explicitly when WebView2 selection is
desired. Supported modes are:
--mode, -m <mode> server, browser, auto, or webview2
--portable, -p Store runtime data in the package's data directory
--host, -H <host> Override the listen host
--port, -P <port> Override the listen port
--webview2-host, -w <path> Use a specific WebView2 host executable
--help, -h Show this helpWithout --portable, the launcher uses the Electron-compatible per-user data
directory (%APPDATA%/@codex-proxy/electron/data on Windows,~/.config/@codex-proxy/electron/data on Linux, and~/Library/Application Support/@codex-proxy/electron/data on macOS). This
allows the No-Node Lite package to reuse the existing Electron configuration.
With --portable, all runtime data is kept in the package's data/ directory.
The two modes must not be run concurrently against the same data directory.
The WebView2 host is a separate Windows native component. A development build
without that host fails clearly in webview2 mode; it does not silently fall
back to a browser. The repository provides a small host source that can be
built with MSYS2 MinGW-w64 (x86 and x64):
node scripts/portable/build-webview2-host.mjs --arch x64
node scripts/portable/build-webview2-host.mjs --arch x86The builder looks for MSYS2_ROOT, D:\DevTools\Tools\msys64, and thenC:\msys64. The MSYS2 UCRT64 environment must provide g++ and themingw-w64-ucrt-x86_64-webview package. A release package can provide the
compiled hosts with --webview2-host-x86 PATH and --webview2-host-x64 PATH.
The resulting package includes the MIT notice for the webview library.
The WebView2 Runtime is not bundled, and neither is an installer. If the
target machine does not have the Runtime, the default auto mode falls back
to the browser. Explicit --mode=webview2 reports the missing Runtime and
asks whether to download and run the official Evergreen Bootstrapper
(~2 MB) now. The question times out without downloading or installing
anything if there is no response:
WebView2 Runtime is not installed. Download and run the official installer (~2 MB) now? (15 seconds)After confirmation, the Bootstrapper is downloaded from Microsoft's official
endpoint (go.microsoft.com/fwlink/?linkid=2124703), checked as a Windows
executable, and verified with an Authenticode signature check (valid and
signed by Microsoft — the same standard the release CI applies) before it is
run with /silent /install. The downloaded installer is cached in the system
temporary directory and reused for later attempts. If the download or the
signature check fails, the official installation page is opened instead and
the launcher exits with guidance. For fully offline environments, a local
installer can be supplied through CODEX_PROXY_WEBVIEW2_BOOTSTRAPPER=/path/to/MicrosoftEdgeWebView2Setup.exe.
The Bootstrapper is an online downloader; it requires internet access and
does not replace the WebView2 host or install Node.js. Evergreen WebView2
supports Windows 10 SAC 1709 and later, supported Windows 10 LTSC/IoT
editions, Windows 11, and the supported Windows Server editions. Windows 7
and 8.1 are outside the current Evergreen support target.
The supported Windows Server targets are Windows Server 2016 LTSC, 2019 LTSC,
2022 LTSC, and supported Server SAC releases.
For local branch testing, set CODEX_PROXY_FORCE_NO_WEBVIEW2=1 before starting
the launcher. This forces the runtime-detection branch without uninstalling or
modifying the machine's WebView2 Runtime. In auto mode it should fall back to
the browser; in explicit --mode=webview2 mode it should show the installation
guidance and timeout behavior.
The Windows launcher shows a timed Node.js installation/help dialog when it
cannot start Node.js. The .cmd and POSIX launchers print the same guidance
and offer to open the official Node.js download page, also with a 15-second
timeout. They never silently download or install Node.js.
The launcher changes the child process working directory to the package root
before starting app/server.mjs. Resource paths for config/, public/,bin/, and native/ remain package-local in both modes; only mutable runtime
data switches between the Electron-compatible user directory and package-localdata/.
The package is intentionally bring-your-own-Node. It does not silently
download or execute Node.js. The WebView2 installer is downloaded from
Microsoft's official endpoint only after the user explicitly confirms the
timed prompt, checked as a Windows executable, and verified with an
Authenticode signature check before it runs.
Linux x64 packages include both the glibc and musl TLS native addons. The musl
variant is intended for Alpine and other musl-based distributions; the package
does not currently include Linux ARM native addons.
The Windows native launcher is a small x86 PE built with the MSYS2 MinGW-w64mingw32 toolchain and the Windows GUI subsystem. It statically links the
MinGW runtime and only imports normal Windows system DLLs, so the package does
not need to ship MinGW DLLs. It owns a small notification-area icon while the
Node server is running and captures the dynamically bound dashboard URL and
WebView2 host path. In WebView2 mode the native launcher owns the WebView2
window, so closing that window leaves the server and tray icon running; Open
Dashboard can create or focus the WebView2 window again. In browser/server mode
it opens the default browser instead. The tray also has a Check for Updates
item that opens the latest No-Node Lite release page for manual replacement. The
build keeps codex-proxy.cmd beside it in every package; if MSYS2 is not
available or the native build fails, the package still remains usable through
the script launcher.
Distribution tests
The archive-level test reads the generated zip, checks its layout and Unix
modes, and runs the package from an unrelated working directory. It also
checks the current host's native addon, the no-Node guidance, the server HTTP
smoke path, browser URL forwarding, and the non-Windows WebView2 error:
npm run test:lite -- --archive portable-release/codex-proxy-2.0.77-no-node-lite-all-platforms.zipOn an isolated Windows runner, add --test-native-launcher to also start the
native codex-proxy.exe. The native launcher uses a single-instance mutex, so
this option should not be run while another Lite/Electron launcher is active
for the same user session.
CI runs the same test on Windows, macOS, and Linux. The native build matrix
also checks the platform/architecture-specific .node files. Unsupported
architectures are covered by the loader contract test; they require a
matching native build or emulator before they can be promoted to runtime
smoke tests.
The Linux x64 musl artifact can also be tested directly after an Alpine build:
node scripts/native/test-linux-x64-musl.mjs native/codex-tls.linux-x64-musl.nodeThe packaged musl path is checked with:
node scripts/portable/test-linux-x64-musl.mjs --package-dir PATHOverview (`tests/netlab/README.md`)
Netlab — 弱网与流量压缩测试环境
隔离的传输层测试环境:在真实代理进程与本机 mock 上游之间注入网络损伤
(延迟/限速/断流/挂起),度量压缩率、TTFT、断传暴露时间,驱动
"流量压缩 + 弱网稳定性"优化的 TDD 闭环。
不消耗真实配额、不触碰 Cloudflare、完全可重复。
链路
测试客户端(lib/client.mjs)
→ codex-proxy 被测实例(127.0.0.1:8188, 隔离 runtime)
↑ tls.proxy_url 显式钉在注入点(禁用本地代理自动探测)
→ toxiproxy(127.0.0.1:28443, HTTP 代理语义 / absolute-form)
→ mock 上游(127.0.0.1:18443, 可编程 SSE 源)被测 wire 是 codex-responses(CodexResponsesUpstream → native rustls 传输
→ 指纹头),与账号/生产路径共用同一传输层。runtime 目录由 runner 生成:
tests/netlab/runtime/
config/ ← 仓库 config 副本(fingerprint.yaml 含上游 Accept-Encoding)
data/ ← local.yaml(端口+key)、api-keys.json(netlab-mock 条目)、proxy.log
native/ ← junction 到仓库 native/(rustls addon)用法
npm run netlab:baseline # 全部场景 + markdown/JSON 报告
node tests/netlab/run-baseline.mjs --filter break- # 只跑断传场景
node tests/netlab/run-baseline.mjs --keep # 保留 toxiproxy 进程
NETLAB_TOXIPROXY=docker node … # 容器模式(需要 Docker Desktop 的
# host.docker.internal;WSL2 引擎用 binary)toxiproxy 默认以原生二进制运行(host loopback,无容器网络依赖);
首次运行自动下载到 tests/netlab/.bin/。报告输出到 tests/netlab/reports/。
场景(scenarios.mjs)
| 场景 | 注入 | 度量目标 |
|---|---|---|
| baseline-plain | 无 | 明文字节基准(压缩对照) |
| baseline-gzip | mock 开 gzip | 上游腿压缩率 + 解压正确性 |
| baseline-gzip-large | 大负载 gzip | 大 JSON 场景压缩率 |
| break-prestream-persistent | reset_peer toxic 持续存在 | 有限重试后干净报错(status-0 重试,不无限循环) |
| break-midstream | mock 硬切 @25KB | 流中断开 → stream_disconnected 暴露延迟 |
| break-stall | mock 静默挂起 | 流空闲看门狗(streamIdleTimeoutMs 场景级覆写,默认 4s 预算)→ 半开连接提前暴露 + 连接回收 |
| cancel-client-abort | 客户端 ~20% 处主动 abort | abort 传播到原生层 httpCancel → 上游请求被终止(mock aborted:true)+ 连接回收 |
| weaknet-slow | latency+bandwidth+slicer | 弱网 TTFT/吞吐 + 心跳有效性 |
每个场景声明 documents 字段:区分"符合当前设计"与"已知待优化缺口"。
新增场景 = scenarios.mjs 加一条(mock env + toxics + 验收描述)。场景可选streamIdleTimeoutMs 字段会重启代理并写入 runtime local.yaml,用于验收
上游流空闲看门狗(tls.stream_idle_timeout_ms,生产默认 120s,0 关闭,
同时覆盖预 header 挂起阶段)。场景设 abortAfterMs 后客户端中途主动断开;
设 expectConnectionReclaim: true 时 runner 轮询 mock 的 openConnections
统计直到归零(5s 上限),报告标注 ✅ reclaimed / ❌ LEAKED——这是
"取消必须回收上游连接"的原生层验收。
开发循环
npm run netlab:baseline→ 拿基线报告- 改代理代码(src/)
- 重跑相关场景(--filter)→ 对比报告,验收标准见场景
documents - 全量回归
注意:跑 netlab 时若本机开着 Clash/v2ray 也不受影响——tls.proxy_url
已显式钉住注入点,自动探测被跳过;但不要在 netlab 运行期间手动改
runtime 的 local.yaml(runner 每次重建 runtime 目录)。
MULTI AGENT WORKFLOW (`docs/MULTI_AGENT_WORKFLOW.md`)
多 Agent 工作流
本文定义 Codex Proxy 项目在用户明确授权多 Agent,或任务明确要求该工作流时的协调、成本、权限和验收规则。普通任务不得默认加载本文,以免长期增加上下文成本。本文补充而不替代根 AGENTS.md、用户要求、版本化合同、开发/安全规则和 Git 纪律;发生冲突时采用更高权威或更严格的安全边界。
1. 目标与权威顺序
第一优化目标是在达到当前任务所需安全与验收阈值的前提下,减少整个任务的 token、产品 credits 和可归因费用。调度优先级为:
最小不可妥协安全边界
→ 达到当前任务所需的验收阈值
→ 最小化全任务 token、credits 和可归因费用
→ 减少重复阅读、返工和上下文搬运
→ 缩短墙钟时间质量以达到任务所需阈值为目标,不无限增加 Reviewer、Verifier 或高性能执行体。成本必须汇总 Coordinator、Explorer、Task Lead、Worker、Reviewer、Verifier、grader、重试、fallback、失败运行、上下文重读、冷启动和 Join,不能只比较最后一次成功调用。
权威顺序固定为:
当前用户要求
→ 项目 AGENTS.md 和活跃状态/票据文档
→ 当前源码、版本化合同和真实工件
→ 架构与历史设计文档
→ Agent 摘要和聊天记忆2. 项目开工审计
Coordinator 在分派前必须:
- 读取根
AGENTS.md、存在的CLAUDE.md、当前状态/票据、架构/开发文档及任务直接依赖。缺失文件要记录为缺失,不得虚构其约束。 - 若根目录存在
.codegraph/,理解或定位代码时先用 CodeGraph;不存在时使用rg/rg --files和最小范围源码读取。 - 检查 Git 分支、revision、暂存区、未提交和未跟踪文件,并识别当前唯一有界任务及停止条件。
- 区分用户修改、其他任务修改和本任务允许修改;范围外修改不得回退、覆盖、格式化、暂存、提交或吸收。
- 禁止
git add -A。未经用户明确要求,不 commit、不 push、不发布。 - 能由权威文档确定的事项直接执行;只有缺失信息会实质改变结果时才询问用户。
- 没有当前任务文档时,在会话中冻结 Task Capsule;除非用户要求,不为每个任务创建新票据。
本仓库共享工作树默认单写者。常用确定性门禁是聚焦 Vitest、必要时 npm run build、git diff --check 和目标路由的本地 mock/fixture 测试。test:real、供应商端点、用户提供的凭据、网络访问、桌面应用部署和其他外部副作用均需独立授权;成功构建不等于真实上游兼容性已验证。
3. Task Capsule
普通或复杂任务在调用实现 Agent 前冻结以下最小合同;不适用或不可观测项写 NONE、unknown 或 false,不得伪造为零:
/* Detailed source-code truncated for AI context efficiency. */delegation_reason 必须说明该 Agent 预计节省 token、重复阅读、返工或墙钟,或提供哪项必要的独立质量判断。无法说明时不启动。
4. 任务预分类
分派前从五个维度分类:
| 维度 | 低/局部/强 | 中/有界/部分 | 高/跨域/弱 |
|---|---|---|---|
semantic_difficulty |
LOW:规则明确、机械操作、简单检索或局部修改 |
MEDIUM:普通代码理解、调试或有限设计判断 |
HIGH:复杂根因、跨层语义、架构、身份、并发、状态、成本或合同推理 |
change_breadth |
LOCAL:单文件或单一局部模块 |
BOUNDED:少量相关文件,边界明确 |
CROSS_CUTTING:跨模块、共享合同或公共接口 |
verifiability |
STRONG:测试/schema/编译/静态检查可充分判断 |
PARTIAL:机械检查只能证明一部分 |
WEAK:主要依赖语义审查或缺少完整 oracle |
failure_impact |
LOW:易回滚且无外部副作用 |
MEDIUM:可能回归、返工或局部数据问题 |
HIGH:安全、权限、凭据、计费、生产、迁移、公共合同或不可逆结果 |
context_load |
SMALL:少量文件 |
MEDIUM:一个代码族或若干历史决定 |
LARGE:跨模块、长历史或多个证据域 |
文件多但规则机械不等于语义难度高;优先用低成本只读分区,不自动升级到高性能执行体。
任务等级:
S:通常为LOW + LOCAL + STRONG + LOW。Coordinator 或一个 ECONOMY Worker 完成,确定性验收通过即停止;默认无 Explorer、模型 Reviewer 或 STRONG。M:普通有界任务。可选 ECONOMY 扫描,BALANCED 单写实现,确定性测试,Coordinator 或 ECONOMY 验证。只有预分类已发现跨抽象层歧义、公共合同、部分验收或较高失败影响时,最多安排一个 STRONG 关键阶段。L:复杂或高后果任务。互不重叠的 ECONOMY 只读扫描,STRONG 冻结关键决策或 BALANCED Task Lead 承接清晰方案,BALANCED 单写实现,ECONOMY 机械门禁,再按剩余语义风险选择 BALANCED/STRONG Review。
5. 执行等级与初始路由
策略不写死模型、供应商或版本。运行时只在环境确实支持且已有能力证据时映射执行等级;不支持显式映射时,报告限制,并以角色范围、最小上下文和推理投入控制成本,不得假装已完成模型级路由。
ECONOMY:目录/源码搜索、日志归纳、schema/fixture/JSON 检查、测试执行、证据整理、局部机械修改、强机械验收。默认 ephemeral 和简短结构化输出。BALANCED:普通实现、局部根因、少量跨文件修改、已有清晰合同的实现。预计一次实现加一次修复时可保留 persistent Worker,后续仅发送增量证据。STRONG:高歧义架构/合同、跨层复杂根因、机械测试不足的关键正确性、高后果方案预审或语义审查。只接收最小关键切片,不承担扫描、批量读取、测试运行或机械实现。
推荐路由:
S: Coordinator 或 ECONOMY Worker → 确定性验收 → 停止
M: 可选 ECONOMY CAP_SCAN → BALANCED CAP_IMPLEMENT → 测试 → Coordinator/ECONOMY CAP_VERIFY → 停止
L: ECONOMY 互斥只读 CAP_SCAN → STRONG CAP_REASON 或 BALANCED Task Lead
→ BALANCED CAP_IMPLEMENT 单写者 → ECONOMY 门禁
→ BALANCED/STRONG CAP_REVIEW → Coordinator 放行M 中 STRONG 默认只负责 CAP_REASON 或 CAP_REVIEW 之一。L 默认只允许一个 STRONG 关键阶段:最大不确定性在实现前时用于 Reason;方案清晰但测试不足时用于 Review。只有安全、权限、计费或不可逆迁移等高后果任务,才可同时使用 STRONG Reason 和 Review。
6. STRONG 预算、升级与降级
默认 STRONG 阶段预算:S 为 0;M 默认 0,存在明确关键语义节点时最多 1;L 默认 1;高后果 L 最多 2,分别用于 Decision 和 Review。每阶段只收最小证据包,产出可执行决定/finding 后立即降回 ECONOMY 或 BALANCED。不得让 STRONG 重跑测试、重做扫描、重写已正确且已验收的实现;预算用完后不追加“再看一遍”。
允许升级的新证据:
- 任务跨越未识别模块/合同;
- ECONOMY/BALANCED 结论冲突且无法机械裁决;
- 一次有证据的实现失败并暴露更深语义问题;
- Reviewer 发现阻塞性高严重度 finding;
- 确定性验收不足以判断关键正确性;
- 实际失败后果高于初始分类。
允许降级的新证据:
- STRONG 已冻结清晰方案;
- 根因已由测试/最小复现确定;
- 剩余仅搜索、fixture、测试或证据整理;
- persistent 历史膨胀,最小交接包更便宜;
- 原弱验收语义已转换为确定性测试。
不得仅因 Agent 不自信、仓库大、用户要求质量、任务是 L、更强执行体可用、想增加信心或单次测试失败而全员升级。默认最多一次有新证据的修复或升级;第二次扩大预算前请求用户决定。
7. Agent 启动门
每次启动前,Coordinator 必须能简洁回答:
- Agent 负责哪个独立问题,为什么现有角色不能顺手完成?
- 它只需读取哪些文件/行和哪些稳定上下文?
- 输出由谁消费,失败是否仍产生可复用证据?
- 预计节省 token、重复阅读、返工或墙钟中的哪一项?
- 是否占用 STRONG 预算?
以下情况不启动:S 级机械任务;必须重读全部 Coordinator 上下文;无法独立分区;无输出消费者;调度/Join 成本高于工作;仅为形式;已有 persistent Worker 可继续;已达验收;预算不足以闭环。
8. 并发、所有权与状态
- 默认并发总数不超过 4(含 Coordinator),递归深度 1。
- 并发优先用于问题域、目录或证据互不重叠的只读扫描和独立核验。
- 同一工作树、合同域、共享 schema、价格/策略配置和基准结论保持单写者。默认仅一个 Worker 可写;多 Worker 只在文件完全不重叠、产物隔离且指定唯一集成者时允许。
- Reviewer/Verifier 默认只读。发现范围外修改返回
CONFLICT,不得回退、格式化、提交或吸收。 - 子 Agent 的 completed 仅表示本次执行结束;只有 Coordinator 能声明最终完成。
Agent 必须用以下状态之一交接:
DONE_FOR_REVIEW:授权工作完成,待审查/验证。BLOCKED_CONTEXT:缺少权威上下文。TOOL_FAILURE:工具/环境失败,结论未验证。CONFLICT:ownership 或工作树冲突。CONTRACT_VIOLATION:请求违反权限或门禁。BUDGET_EXHAUSTED:token、时间、费用或调用预算耗尽。UNVERIFIED:产物存在,但验收未闭合。
Reviewer 判断关键语义是否正确,Verifier 判断验收证据是否真实。低风险且机械门禁充分时,不为形式同时启动两者。
9. 上下文与缓存
- 不默认复制完整聊天历史;支持选择 fork 范围时传最少必要 turns。
- 扫描、日志、schema/fixture 使用 ephemeral;同一代码族的一次实现与一次修复可用 persistent Worker。
- persistent 后续仅接收新增 finding、diff、失败日志和变化后的权威事实;历史膨胀后制作短小可核验交接包再新开执行体。
- 并行 Explorer 的问题、目录或证据域必须互斥。输出只含结论、
file:line、命令、退出码、工件身份和未决问题;长日志留本地,成功只给摘要,失败只给相关上下文。 - 不要求冗长思维过程。
若底层支持 Prompt Cache,按以下稳定前缀组织:
稳定公共规则
→ 稳定工具、schema 和输出合同
→ Task Capsule 不变部分
→ 角色专属指令
→ revision、finding、文件和本轮问题等动态内容公共前缀不放时间戳、随机 ID、临时路径、完整 Git 状态或动态问题,并保持必要且精简。不假设缓存跨 Agent、模型、provider、线程或执行形态复用;只有可信 usage 明示 cached token 才报告命中,否则为 unknown。
10. 用量与费用
环境可观测时,对每个 Agent/attempt 记录:
role, executor_tier, context_mode, attempt_id,
input_tokens, cached_tokens, cache_write_tokens, output_tokens, reasoning_tokens,
total_tokens, usage_source, usage_completeness, wall_clock,
retry_or_fallback, actual_cost, accepted_contribution规则:
- 全部角色、重试、fallback、失败运行都计入总成本。
reasoning_tokens若是output_tokens子项,不重复计费;流式只用最终 usage。- API 美元与产品 credits 分开;无实测换算不得合并。未知 token/价格/credits/cache 写
unknown,不得猜为 0。 - 历史运行绑定当时价格版本;仅有同配置无缓存基线时才声明缓存净节省。
- cache hit 高但任务失败、返工或噪声增加不算有效节省。
- 无精确费用时,只比较可观测 token、轮次、Agent 启动数和重复阅读量,并标为代理指标。
- 任务未接受时报告已消耗成本,不包装为成功 ROI。
11. 权限与不可妥协边界
多 Agent 授权不自动授权网络、真实/付费 API、凭据读取、外部系统写入、发布、push、不可逆迁移或破坏性操作。每项都必须来自用户当前任务的明确授权并记录进 Task Capsule。
不得以节省 token 为由绕过:
- 未授权的破坏性/不可逆操作或外部副作用;
- 未授权的真实 API、网络、发布或付费调用;
- Secret、凭据或受限正文泄露;
- 修改测试/fixture/expected 掩盖错误;
- 未运行验收却声称通过;
- 覆盖或回退用户及其他 Agent 修改;
- 伪造 token、费用、缓存、测试、baseline 或完成状态。
非关键优化、风格争议和额外重构默认延后。允许如实返回 IMPLEMENTED_ONLY、UNVERIFIED 或带已知限制的结果;预算耗尽即停止,不自动扩权或扩预算。
12. 验收、停止与最终报告
达到当前有界任务验收阈值或停止条件后立即停止,不自动进入下一票据。Coordinator 最终状态必须是:
ACCEPTED:达到当前任务验收阈值。IMPLEMENTED_ONLY:实现存在但完整验收未闭合。UNVERIFIED:证据不足、工具失败或预算停止。REJECTED:Review 或关键验收发现阻塞问题。UNRUN:列出明确未运行的检查。
最终报告简洁区分并包含:
- 预分类五维结果和 S/M/L;
- 各角色初始等级、最低充分能力理由、实际启动/未启动候选;
- STRONG 关键节点、预算和实际阶段数,升级/降级及证据;
- 各角色 context mode、persistent 是否复用、如何避免重复读取;
- 修改文件、命令与退出结果、Review findings、Verify 证据;
- Agent 启动数、总轮次、重试数;
- 可观测 input/cached/cache-write/output/reasoning token;API 美元与 credits 分列;不可观测项为
unknown; - 可比基线是否存在;不存在时不声明节省比例或 ROI;
- 已知限制、遗留风险、回滚方式、commit 状态、范围外文件和停止条件命中情况。
未经用户授权,最终报告必须明确“未提交”“未 push”。
--- METRICS ---
- Files Extracted: 7
- Estimated Token Budget: ~16284 tokens
- Canonical Reference: https://codewiki.google/github.com/icebear0828/codex-proxy