Skip to content

A local plugin for image-heavy chats in Codex, Claude Code and other agents: earlier images stop going out with every message, and the model fetches the one it needs by its ID, also after compaction.

fix(proxy): API key 登录的 Codex 请求转去 api.openai.com

chipfightera7f8016d9cda
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c1ae603..7f49467 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,17 @@
When a version is released, its section here becomes the GitHub release notes.
+## [Unreleased]
+
+### Fixes
+
+- Codex logged in with an API key now connects with the plugin installed. Its requests went to ChatGPT's backend, which takes ChatGPT logins, not API keys. They now go to the OpenAI API, where Codex sends them without the plugin, and images are managed there as well.
+
+### Notes
+
+- Checked with the Codex command line and a fake API key: through a test engine, the request reached the OpenAI API, which answered "Incorrect API key provided". Managing images with a real API key has not been tried yet.
+- Codex set up with its own model provider, such as cc-switch or a third-party relay, still does not go through the plugin.
+
## [0.8.2] - 2026-10-21
The model notes where each image is set, not its "scene".
diff --git a/docs/design.md b/docs/design.md
index 97f9297..fa503b8 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -36,6 +36,7 @@
- **地址**:`config.toml` 顶层的 `openai_base_url = "http://localhost:17891/backend-api/codex"`。
- 必须以 `/backend-api/codex` 结尾,否则 Codex 会关掉后端专用的接口;引擎把同样的路径转发到 `https://chatgpt.com`。
+ - API key 登录的 Codex 也用这个地址(2026-10-22 用假 key 对着本机假服务实测):请求一样发到 `…/backend-api/codex/responses`,带 `Authorization: Bearer sk-…`,没有 ChatGPT 登录才有的 `chatgpt-account-id`。chatgpt.com 不认 API key,所以引擎认出这种请求(`proxy.ts` 的 `routeOf`)后,转给 `https://api.openai.com`,路径里的 `/backend-api/codex/` 换成 `/v1/`,正是没装工具时 Codex 的默认地址。请求体同样是 Responses 请求,改写照旧。WebSocket 升级也按同样的规则转发。Claude 订阅的令牌也以 `sk-` 开头(`sk-ant-oat…`),但它的路径是 `/v1/…`,不受影响。
- 写 `localhost` 不写 `127.0.0.1`:Windows 代理设置里的 `<local>` 只让不带点的主机名直连。
- **`features.respect_system_proxy = true`**:让 Codex 先看 Windows 的代理设置。否则用户环境里有 `HTTP(S)_PROXY`、没有 `NO_PROXY` 时,连本机的请求也会被交给系统代理,然后失败。
- **`~/.codex/.env` 里的 `NO_PROXY`**:生图、改图的客户端只认环境变量。Codex 启动时会读 `.env`,所以在需要时写一段 `NO_PROXY=localhost,127.0.0.1,::1`,合并用户自己的条目。`.env` 可能含密钥,工具不复制、不输出它。
diff --git a/docs/spec.md b/docs/spec.md
index 149df1f..2939457 100644
--- a/docs/spec.md
+++ b/docs/spec.md
@@ -32,6 +32,8 @@ v0.4:同样的管理也用在 Claude 桌面应用的 Code 标签页里(本
代理跟着 Codex 一起启动、一起退出(用户 2026-09-24 确认)。只要配置指向代理,代理就必须在运行,否则 Codex 连不上。
+登录方式:ChatGPT 账号登录和 API key 登录都接管(2026-10-22 用户定)。API key 登录的请求转给 OpenAI 的 API(`api.openai.com`),也就是没装工具时 Codex 自己会去的地方,图片照常管理;之前装上工具后这类请求会被转到 ChatGPT 的后端,连不上。用真 API key 管理图片还没实测过,只验证了请求能到达 OpenAI 的 API。改用自定义模型供应商(`model_providers`,例如 cc-switch、第三方中转)的 Codex 不经过工具,不接管。
+
### 选择规则
- 新出现的图默认勾选,照常发送,包括和前面内容相同的副本(用户 2026-09-24 决定)。用户没有取消任何图时,请求原样转发,Codex 的表现和没装工具时一样。v0.8:这一条在 Codex 手动模式下照旧,所以手动模式要等第一次取消勾选之后才写特征行(用户 2026-10-18 定:在那之前,插件不碰这个任务的请求,请求走 WebSocket;要写特征行,就得改走 HTTP,每次请求都重新上传全部图片,得不偿失)。开着自动选图的任务,和 Claude Code 的会话(它本来每次都发完整的历史),从第一张图起就写。
diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.ts
index ec734c2..2be4a8a 100644
--- a/plugin/src/proxy.ts
+++ b/plugin/src/proxy.ts
@@ -10,6 +10,7 @@
// copy the model fetched is sent in its own turn only (spec v0.3).
// v0.4: Claude Code too (the plugin's mod points ANTHROPIC_BASE_URL here): its /v1/… requests go to api.anthropic.com,
// everything else to chatgpt.com as before. A Claude session is told apart by x-claude-code-session-id.
+// 2026-10-22: Codex logged in with an API key goes to api.openai.com/v1 instead (see routeOf).
// Only metadata is logged (never auth headers or conversation content).
// Input: [--port 17891] [--stay (no auto-exit)] [--force-http] [--dump-requests (synthetic test threads only)];
// the outbound proxy is taken from HTTPS_PROXY/HTTP_PROXY or the system proxy settings (Windows, macOS).
@@ -48,6 +49,9 @@ const here = dirname(fileURLToPath(import.meta.url));
const UPSTREAM_HOST = "chatgpt.com";
// v0.4: Claude Code's API host.
export const CLAUDE_HOST = "api.anthropic.com";
+// Where Codex logged in with an API key sends its requests without the plugin (its base URL https://api.openai.com/v1).
+const OPENAI_API_HOST = "api.openai.com";
+const CODEX_BASE = "/backend-api/codex/";
const HOP_BY_HOP = new Set(["connection", "keep-alive", "proxy-connection", "transfer-encoding", "te", "trailer", "upgrade", "host"]);
// Codex's requests all start with /backend-api/ (its base URL ends in /backend-api/codex); Claude Code's with /v1/.
@@ -55,6 +59,16 @@ export function upstreamOf(path: string): string {
return path.startsWith("/v1/") ? CLAUDE_HOST : UPSTREAM_HOST;
}
+// Codex logged in with an API key keeps the base URL the plugin set and sends its key (Bearer sk-…, no
+// chatgpt-account-id), which chatgpt.com does not take: those requests go to api.openai.com, /backend-api/codex/
+// becoming /v1/ (2026-10-22, seen with a fake key against a local server). The request bodies are the same Responses
+// requests, so they are rewritten as before.
+export function routeOf(url: string, headers: IncomingHttpHeaders): { host: string; url: string } {
+ const apiKey = /^Bearer sk-/i.test(String(headers.authorization ?? "")) && !headers["chatgpt-account-id"];
+ if (apiKey && url.startsWith(CODEX_BASE)) return { host: OPENAI_API_HOST, url: `/v1/${url.slice(CODEX_BASE.length)}` };
+ return { host: upstreamOf(url.split("?")[0]), url };
+}
+
// Outbound proxy: environment first, then the system setting (Windows per-user, macOS); NO_PROXY is honoured for the
// upstream host.
export function outboundProxy(env = process.env, systemSetting = readSystemProxy, upstream = UPSTREAM_HOST): { host: string; port: number } | null {
@@ -535,8 +549,8 @@ async function main(): Promise<void> {
setPixelCache(pixelCacheDirOf());
const via = outboundProxy();
// v0.4: NO_PROXY may name one upstream host and not the other.
- const claudeVia = outboundProxy(process.env, readSystemProxy, CLAUDE_HOST);
- const viaOf = (upstream: string) => (upstream === CLAUDE_HOST ? claudeVia : via);
+ const vias = new Map([CLAUDE_HOST, OPENAI_API_HOST].map((host) => [host, outboundProxy(process.env, readSystemProxy, host)]));
+ const viaOf = (upstream: string) => (vias.has(upstream) ? vias.get(upstream)! : via);
const startedAt = new Date().toISOString();
// v0.1-3: which code this engine runs, so the plugin can tell when an update needs a new engine.
const build = buildOf();
@@ -635,7 +649,7 @@ async function main(): Promise<void> {
const onRequest = (req: http.IncomingMessage, res: http.ServerResponse) => {
if (req.url === "/__cam/health") {
res.writeHead(200, { "content-type": "application/json" });
- res.end(JSON.stringify({ ok: true, service: ENGINE_SERVICE, pid: process.pid, startedAt, port, build, version, upstream: UPSTREAM_HOST, upstreams: [UPSTREAM_HOST, CLAUDE_HOST], via: via ? `${via.host}:${via.port}` : "direct" }));
+ res.end(JSON.stringify({ ok: true, service: ENGINE_SERVICE, pid: process.pid, startedAt, port, build, version, upstream: UPSTREAM_HOST, upstreams: [UPSTREAM_HOST, CLAUDE_HOST, OPENAI_API_HOST], via: via ? `${via.host}:${via.port}` : "direct" }));
return;
}
if (req.url === "/__cam/retire" && req.method === "POST") {
@@ -677,7 +691,8 @@ async function main(): Promise<void> {
const id = ++sequence;
const started = Date.now();
const path = (req.url ?? "/").split("?")[0];
- const upstream = upstreamOf(path);
+ const route = routeOf(req.url ?? "/", req.headers);
+ const upstream = route.host;
const identity = requestIdentity(req.headers);
const rewrite = req.method === "POST" && /\/responses(\/compact)?$/.test(path) && needsRewrite(identity.threadId, selectionDir, sessionsDir, identity.forkedFrom);
// v0.4: a Claude Code request of a session's main conversation (a subagent's loop has its own); rewritten like a
@@ -721,7 +736,7 @@ async function main(): Promise<void> {
}
} catch { details = { kind: "unparsed" }; }
}
- const entry = { at: new Date(started).toISOString(), id, transport: "http", method: req.method, path, status, requestBytes, decodedBytes: decoded?.length ?? null, contentEncoding: req.headers["content-encoding"] ?? null, responseBytes, ms: Date.now() - started, ...identity, ...claudeFields, ...details, ...extra, error: error ?? null };
+ const entry = { at: new Date(started).toISOString(), id, transport: "http", method: req.method, path, ...(upstream === OPENAI_API_HOST ? { upstream } : {}), status, requestBytes, decodedBytes: decoded?.length ?? null, contentEncoding: req.headers["content-encoding"] ?? null, responseBytes, ms: Date.now() - started, ...identity, ...claudeFields, ...details, ...extra, error: error ?? null };
log(entry);
// Image keys go to the per-thread statistics only, not to the log.
if (/\/responses$/.test(path)) {
@@ -751,7 +766,7 @@ async function main(): Promise<void> {
if (attempt.report) extra = { ...extra, rewrite: attempt.report };
if (dumpDir) sentBody = attempt.edited ? attempt.body : null;
// No `agent` option: with agent:false Node ignores createConnection and dials the host directly.
- const outbound = http.request({ host: upstream, method: req.method, path: req.url, headers: outgoing, createConnection: () => socket }, (answer) => {
+ const outbound = http.request({ host: upstream, method: req.method, path: route.url, headers: outgoing, createConnection: () => socket }, (answer) => {
status = answer.statusCode ?? 0;
const headers: Record<string, string | string[]> = {};
for (const [name, value] of Object.entries(answer.headers)) if (value !== undefined && !HOP_BY_HOP.has(name)) headers[name] = value;
@@ -852,7 +867,8 @@ async function main(): Promise<void> {
let up = head.length;
let down = 0;
let upstreamStatus: string | null = null;
- connectUpstream(via).then((socket) => {
+ const route = routeOf(req.url ?? "/", req.headers);
+ connectUpstream(viaOf(route.host), route.host).then((socket) => {
// The client went away while the upstream connected: its close has passed, nothing would close this one.
if (client.destroyed) { socket.destroy(); return; }
const connection: Live = { client, socket, last: Date.now(), closedForSelection: false, activeWhileUnchecked: false, path, identity };
@@ -866,10 +882,10 @@ async function main(): Promise<void> {
log(opened);
recordRequest(identity.threadId, opened);
noteChild(identity, opened.at);
- const lines = [`${req.method} ${req.url} HTTP/1.1`];
+ const lines = [`${req.method} ${route.url} HTTP/1.1`];
for (let i = 0; i < req.rawHeaders.length; i += 2) {
const name = req.rawHeaders[i];
- lines.push(`${name}: ${name.toLowerCase() === "host" ? UPSTREAM_HOST : req.rawHeaders[i + 1]}`);
+ lines.push(`${name}: ${name.toLowerCase() === "host" ? route.host : req.rawHeaders[i + 1]}`);
}
socket.write(`${lines.join("\r\n")}\r\n\r\n`);
if (head.length) socket.write(head);
@@ -886,7 +902,7 @@ async function main(): Promise<void> {
client.destroy();
sockets.delete(connection);
if (identity.threadId) live.get(identity.threadId)?.delete(connection);
- const entry = { at: new Date(started).toISOString(), id, transport: "websocket", path, upstreamStatus, upBytes: up, downBytes: down, ms: Date.now() - started, closedForSelection: connection.closedForSelection, activeWhileUnchecked: connection.activeWhileUnchecked, ...identity };
+ const entry = { at: new Date(started).toISOString(), id, transport: "websocket", path, ...(route.host === OPENAI_API_HOST ? { upstream: route.host } : {}), upstreamStatus, upBytes: up, downBytes: down, ms: Date.now() - started, closedForSelection: connection.closedForSelection, activeWhileUnchecked: connection.activeWhileUnchecked, ...identity };
log(entry);
recordRequest(identity.threadId, entry);
};
diff --git a/spike/src/proxy-http.test.ts b/spike/src/proxy-http.test.ts
index f1f8553..6c6329f 100644
--- a/spike/src/proxy-http.test.ts
+++ b/spike/src/proxy-http.test.ts
@@ -147,3 +147,37 @@ test("a declined WebSocket upgrade that the client resets leaves the engine runn
}), "the engine did not answer after the resets");
assert.equal(status, 200);
});
+
+// 2026-10-22: Codex logged in with an API key sends its key through the plugin's base URL; the engine passes it on
+// to api.openai.com/v1, where Codex would send it without the plugin. A ChatGPT login still goes to chatgpt.com.
+test("Codex's API-key requests reach api.openai.com/v1, over HTTP and WebSocket", async (t) => {
+ const seen: { host?: string; url?: string; auth?: string }[] = [];
+ const { port, upstream } = await fixture(t, (req, res) => {
+ req.resume();
+ seen.push({ host: req.headers.host, url: req.url, auth: req.headers.authorization });
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end("{}");
+ });
+ const post = (headers: Record<string, string>) => bounded(new Promise<number>((resolve, reject) => {
+ const body = JSON.stringify({ input: [] });
+ const client = http.request({ hostname: "127.0.0.1", port, path: "/backend-api/codex/responses", method: "POST", agent: false, headers: { "content-type": "application/json", "content-length": String(Buffer.byteLength(body)), ...headers } }, (response) => { response.resume(); response.on("end", () => resolve(response.statusCode ?? 0)); });
+ client.on("error", reject);
+ client.end(body);
+ }), "request did not finish");
+ assert.equal(await post({ authorization: "Bearer sk-test-not-a-real-key" }), 200);
+ assert.equal(await post({ authorization: "Bearer eyJ.synthetic.token", "chatgpt-account-id": "acct" }), 200);
+ assert.deepEqual(seen, [
+ { host: "api.openai.com", url: "/v1/responses", auth: "Bearer sk-test-not-a-real-key" },
+ { host: "chatgpt.com", url: "/backend-api/codex/responses", auth: "Bearer eyJ.synthetic.token" },
+ ]);
+ const upgraded = new Promise<{ host?: string; url?: string }>((resolve) => upstream.once("upgrade", (req, socket) => {
+ socket.on("error", () => {});
+ resolve({ host: req.headers.host, url: req.url });
+ socket.end("HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n");
+ }));
+ const socket = net.connect(port, "127.0.0.1");
+ socket.on("error", () => {});
+ t.after(() => socket.destroy());
+ socket.write(["GET /backend-api/codex/responses HTTP/1.1", `Host: 127.0.0.1:${port}`, "Authorization: Bearer sk-test-not-a-real-key", "Connection: Upgrade", "Upgrade: websocket", "Sec-WebSocket-Version: 13", "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==", "", ""].join("\r\n"));
+ assert.deepEqual(await bounded(upgraded, "upgrade did not reach the upstream"), { host: "api.openai.com", url: "/v1/responses" });
+});
diff --git a/spike/src/proxy.test.ts b/spike/src/proxy.test.ts
index e633fc6..08460b1 100644
--- a/spike/src/proxy.test.ts
+++ b/spike/src/proxy.test.ts
@@ -8,7 +8,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import zlib from "node:zlib";
-import { claudeIdentity, describeBody, forwardHeaders, hasUnchecked, hasUnsafeInteger, imageSizesOf, macProxy, needsRewrite, outboundProxy, redactImages, rewriteBody, requestIdentity, upstreamOf } from "../../plugin/src/proxy.ts";
+import { claudeIdentity, describeBody, forwardHeaders, hasUnchecked, hasUnsafeInteger, imageSizesOf, macProxy, needsRewrite, outboundProxy, redactImages, rewriteBody, requestIdentity, routeOf, upstreamOf } from "../../plugin/src/proxy.ts";
import { writeSelection } from "../../plugin/src/selection.ts";
import { png } from "./testkit.ts";
@@ -176,6 +176,22 @@ test("Claude Code's /v1/ requests go to api.anthropic.com, everything else to ch
assert.equal(forwardHeaders({ connection: "keep-alive" }, "api.anthropic.com").connection, undefined);
});
+// 2026-10-22: Codex logged in with an API key keeps the plugin's base URL and sends its key; chatgpt.com does not take
+// API keys, so those requests go where Codex would send them without the plugin.
+test("Codex's API-key requests go to api.openai.com/v1, its ChatGPT-login and Claude's ones as before", () => {
+ const key = { authorization: "Bearer sk-test-not-a-real-key" };
+ assert.deepEqual(routeOf("/backend-api/codex/responses", key), { host: "api.openai.com", url: "/v1/responses" });
+ assert.deepEqual(routeOf("/backend-api/codex/responses/compact?x=1", key), { host: "api.openai.com", url: "/v1/responses/compact?x=1" });
+ assert.deepEqual(routeOf("/backend-api/codex/models?client_version=1", key), { host: "api.openai.com", url: "/v1/models?client_version=1" });
+ // ChatGPT login: an access token and the account id.
+ const chatgpt = { authorization: "Bearer eyJ.synthetic.token", "chatgpt-account-id": "acct" };
+ assert.deepEqual(routeOf("/backend-api/codex/responses", chatgpt), { host: "chatgpt.com", url: "/backend-api/codex/responses" });
+ assert.deepEqual(routeOf("/backend-api/codex/responses", { ...key, "chatgpt-account-id": "acct" }), { host: "chatgpt.com", url: "/backend-api/codex/responses" });
+ assert.deepEqual(routeOf("/backend-api/codex/responses", {}), { host: "chatgpt.com", url: "/backend-api/codex/responses" });
+ // Claude's subscription token also starts with sk- (sk-ant-oat…): its /v1/ requests stay with Anthropic.
+ assert.deepEqual(routeOf("/v1/messages?beta=true", { authorization: "Bearer sk-ant-oat01-synthetic" }), { host: "api.anthropic.com", url: "/v1/messages?beta=true" });
+});
+
test("NO_PROXY is checked against each upstream host on its own", () => {
const env = { HTTPS_PROXY: "http://127.0.0.1:8888", NO_PROXY: "chatgpt.com" };
assert.equal(outboundProxy(env, none, "chatgpt.com"), null);