Stop paying the multimodal tax. Your AI agent keeps every image it has seen but only sends the ones it needs: lighter chats, no endless reconnecting, no starting over. Works with Codex, Claude Code, Cline, Gemini CLI, OpenCode, WorkBuddy and more. Install once, forget it.
TypeScript ai-agentsai-imageclaude-codeclaude-code-pluginclinecodexcodex-plugincomputer-usecontext-engineeringcontext-managementdeveloper-toolsgemini-cliimage-generationmcpmultimodalmultimodal-aiopencodeqwen-codetoken-optimizationvision-language-model
feat(spike): 代理验证 P1 的配置工具、透明代理与自测
chipfightera6fce5b29cb6
diff --git a/docs/tasks.md b/docs/tasks.mdindex 807158d..eda4cec 100644--- a/docs/tasks.md+++ b/docs/tasks.md@@ -6,14 +6,14 @@设计见 plan.md 第 9 节。-- [ ] **P1-1 配置工具**+- [x] **P1-1 配置工具**(`spike/src/codexconfig.ts`,7 个单元测试)- 自动定位 Codex 目录,提供 enable、disable、status 三个命令。- 修改前备份;只增删带标记的那一段;如果已经有用户自己的 `openai_base_url`,不覆盖。- 单元测试覆盖:插入位置在所有表头之前、CRLF 和 BOM、重复启用、恢复后逐字节一致、冲突检测。-- [ ] **P1-2 透明代理**+- [x] **P1-2 透明代理**(`spike/src/proxy.ts`,4 个单元测试;自动识别出系统代理,未登录请求得到上游预期的 401)- HTTP 请求和 WebSocket 连接原样转发;自动沿用系统代理;只在 `127.0.0.1` 上监听。- 日志只记元数据,不含认证信息和对话内容。-- [ ] **P1-3 自测(不改配置)**+- [x] **P1-3 自测(不改配置)**(证据:`local/p1-selftest.json`、`local/proxy/*.jsonl`)- 我们自己启动的 app-server 用 `-c openai_base_url` 指向代理,依次验证文字、附图、生图、改图都能成功,日志里能看到对应的请求。- [ ] **P1-4 桌面版验证**【需用户】- 修改桌面版的配置(先备份)。用户重启桌面版后,在任务里依次发文字、上传图片、让它生图、让它改图。diff --git a/spike/src/codexconfig.test.ts b/spike/src/codexconfig.test.tsnew file mode 100644index 0000000..d152ff5--- /dev/null+++ b/spike/src/codexconfig.test.ts@@ -0,0 +1,64 @@+// Purpose: P1-1 — the managed config.toml block is inserted and removed without touching anything else.+// Input: synthetic config texts; output: Node test assertions only.++import assert from "node:assert/strict";+import test from "node:test";+import { disableProxy, enableProxy, proxyStatus } from "./codexconfig.ts";++const URL = "http://127.0.0.1:17891/backend-api/codex";+const original = 'model = "gpt-6-sol"\n\n[features]\nview_image = true\n\n[mcp_servers.demo]\ncommand = "node"\n';++function topLevelKeys(text: string): string[] {+ const keys: string[] = [];+ for (const line of text.replace(/^/, "").split(/\r?\n/)) {+ if (/^\s*\[/.test(line)) break;+ const key = /^\s*([A-Za-z0-9_.-]+)\s*=/.exec(line)?.[1];+ if (key) keys.push(key);+ }+ return keys;+}++test("enable puts openai_base_url at top level, before every table", () => {+ const { text, changed } = enableProxy(original, URL);+ assert.equal(changed, true);+ assert.deepEqual(topLevelKeys(text), ["openai_base_url", "model"]);+ assert.match(text, new RegExp(`openai_base_url = "${URL.replaceAll("/", "\\/")}"`));+ assert.ok(text.endsWith(original), "everything after the block is unchanged");+});++test("enable then disable restores the file byte for byte", () => {+ for (const sample of [original, "", "" + original.replaceAll("\n", "\r\n"), "# only a comment\n"]) {+ assert.equal(disableProxy(enableProxy(sample, URL).text).text, sample);+ }+});++test("CRLF files get a CRLF block and keep their BOM", () => {+ const crlf = "" + original.replaceAll("\n", "\r\n");+ const { text } = enableProxy(crlf, URL);+ assert.ok(text.startsWith("# >>>"));+ assert.doesNotMatch(text.replaceAll("\r\n", ""), /\n/, "no bare LF introduced");+});++test("enabling twice is a no-op, and a new URL only replaces the managed line", () => {+ const once = enableProxy(original, URL).text;+ assert.deepEqual(enableProxy(once, URL), { text: once, changed: false });+ const moved = enableProxy(once, "http://127.0.0.1:18000/backend-api/codex");+ assert.equal(moved.changed, true);+ assert.equal(proxyStatus(moved.text).url, "http://127.0.0.1:18000/backend-api/codex");+ assert.equal(disableProxy(moved.text).text, original);+});++test("a user's own top-level openai_base_url is never overwritten", () => {+ const mine = 'openai_base_url = "https://example.test/v1"\n' + original;+ assert.throws(() => enableProxy(mine, URL), /already sets openai_base_url/);+ assert.equal(proxyStatus(mine).conflict, true);+});++test("openai_base_url inside a table is not a top-level conflict", () => {+ const scoped = original + '\n[profiles.work]\nopenai_base_url = "https://example.test/v1"\n';+ assert.equal(enableProxy(scoped, URL).changed, true);+});++test("disable without a managed block changes nothing", () => {+ assert.deepEqual(disableProxy(original), { text: original, changed: false });+});diff --git a/spike/src/codexconfig.ts b/spike/src/codexconfig.tsnew file mode 100644index 0000000..51acced--- /dev/null+++ b/spike/src/codexconfig.ts@@ -0,0 +1,107 @@+// Purpose: P1-1 — point Codex's built-in openai provider at the local proxy by managing one marked block+// in config.toml, and remove exactly that block again. Nothing else in the file is touched.+// Input (CLI): enable [--port 17891] | disable | status. Codex home comes from CODEX_HOME or %USERPROFILE%\.codex.+// Output: the edited config.toml; a byte copy of the previous file under local/config-backup/ before every change.++import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { homedir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";++export const BEGIN = "# >>> codex-attachment-manager: managed proxy setting, remove it with the tool >>>";+export const END = "# <<< codex-attachment-manager <<<";++function parts(text: string): { bom: string; body: string; eol: string } {+ const bom = text.startsWith("") ? "" : "";+ const body = bom ? text.slice(1) : text;+ return { bom, body, eol: body.includes("\r\n") ? "\r\n" : "\n" };+}++function block(lines: string[]): { start: number; end: number } | null {+ const start = lines.findIndex((line) => line.trim() === BEGIN);+ if (start < 0) return null;+ const end = lines.findIndex((line, i) => i > start && line.trim() === END);+ if (end < 0) throw new Error("the managed block in config.toml has no end marker");+ return { start, end };+}++// TOML top-level keys end at the first table header; a second top-level openai_base_url would be a duplicate key.+function hasTopLevelConflict(lines: string[], managed: { start: number; end: number } | null): boolean {+ for (const [i, line] of lines.entries()) {+ if (managed && i >= managed.start && i <= managed.end) continue;+ if (/^\s*\[/.test(line)) return false;+ if (/^\s*openai_base_url\s*=/.test(line)) return true;+ }+ return false;+}++export function proxyStatus(text: string): { enabled: boolean; url: string | null; conflict: boolean } {+ const { body, eol } = parts(text);+ const lines = body.split(eol);+ const managed = block(lines);+ const line = managed ? lines.slice(managed.start + 1, managed.end).find((l) => /^\s*openai_base_url\s*=/.test(l)) : undefined;+ return { enabled: Boolean(managed), url: line ? (/"([^"]*)"/.exec(line)?.[1] ?? null) : null, conflict: hasTopLevelConflict(lines, managed) };+}++export function enableProxy(text: string, url: string): { text: string; changed: boolean } {+ const { bom, body, eol } = parts(text);+ const lines = body.split(eol);+ const managed = block(lines);+ if (hasTopLevelConflict(lines, managed)) throw new Error("config.toml already sets openai_base_url; not overwriting it");+ const setting = `openai_base_url = "${url}"`;+ if (managed) {+ const current = lines.slice(managed.start + 1, managed.end);+ if (current.length === 1 && current[0] === setting) return { text, changed: false };+ lines.splice(managed.start + 1, managed.end - managed.start - 1, setting);+ return { text: bom + lines.join(eol), changed: true };+ }+ // At the very top the key is always top-level, whatever tables follow; a blank line separates it from the user's text.+ return { text: bom + [BEGIN, setting, END, ""].join(eol) + eol + body, changed: true };+}++export function disableProxy(text: string): { text: string; changed: boolean } {+ const { bom, body, eol } = parts(text);+ const begin = body.indexOf(BEGIN);+ if (begin < 0) return { text, changed: false };+ const end = body.indexOf(END, begin);+ if (end < 0) throw new Error("the managed block in config.toml has no end marker");+ let cut = end + END.length;+ if (body.startsWith(eol, cut)) cut += eol.length;+ // The separator line is ours only when the block still sits where enable put it.+ if (begin === 0 && body.startsWith(eol, cut)) cut += eol.length;+ return { text: bom + body.slice(0, begin) + body.slice(cut), changed: true };+}++export function codexHome(): string {+ return process.env.CODEX_HOME?.trim() || join(homedir(), ".codex");+}++function main(): void {+ const command = process.argv[2];+ const localRoot = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");+ const config = join(codexHome(), "config.toml");+ const current = existsSync(config) ? readFileSync(config, "utf8") : "";+ const write = (next: string) => {+ mkdirSync(join(localRoot, "config-backup"), { recursive: true });+ const stamp = new Date().toISOString().replaceAll(":", "-");+ if (existsSync(config)) copyFileSync(config, join(localRoot, "config-backup", `config.toml.${stamp}`));+ writeFileSync(config, next, "utf8");+ };+ if (command === "enable") {+ const index = process.argv.indexOf("--port");+ const port = Number(index >= 0 ? process.argv[index + 1] : 17891);+ const { text, changed } = enableProxy(current, `http://127.0.0.1:${port}/backend-api/codex`);+ if (changed) write(text);+ console.log(JSON.stringify({ command, changed, ...proxyStatus(text) }));+ } else if (command === "disable") {+ const { text, changed } = disableProxy(current);+ if (changed) write(text);+ console.log(JSON.stringify({ command, changed, ...proxyStatus(text) }));+ } else if (command === "status") {+ console.log(JSON.stringify({ command, configExists: existsSync(config), ...proxyStatus(current) }));+ } else {+ throw new Error("usage: codexconfig.ts enable [--port N] | disable | status");+ }+}++if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) main();diff --git a/spike/src/p1-selftest.ts b/spike/src/p1-selftest.tsnew file mode 100644index 0000000..326682c--- /dev/null+++ b/spike/src/p1-selftest.ts@@ -0,0 +1,100 @@+// Purpose: P1-3 — run text, attached image, image generation and image edit through our own app-server pointed at+// the local proxy (`-c openai_base_url`, the user's config.toml is not touched), then match the proxy log.+// Input: [--port 17891]; the proxy must already be running. Output: local/p1-selftest.json and a console summary.++import { mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import zlib from "node:zlib";+import { AppServer, findBundledCodex } from "./appserver.ts";++type Json = Record<string, any>;+const localRoot = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");++// A synthetic 256×256 RGB gradient, so no user material is sent for the attachment test.+function testPattern(): Buffer {+ const width = 256;+ const height = 256;+ const raw = Buffer.alloc((width * 3 + 1) * height);+ for (let y = 0; y < height; y++) {+ const row = y * (width * 3 + 1);+ for (let x = 0; x < width; x++) {+ raw[row + 1 + x * 3] = x;+ raw[row + 2 + x * 3] = y;+ raw[row + 3 + x * 3] = 160;+ }+ }+ const chunk = (type: string, data: Buffer) => {+ const length = Buffer.alloc(4);+ length.writeUInt32BE(data.length);+ const crc = Buffer.alloc(4);+ crc.writeUInt32BE(zlib.crc32(Buffer.concat([Buffer.from(type, "ascii"), data])));+ return Buffer.concat([length, Buffer.from(type, "ascii"), data, crc]);+ };+ const header = Buffer.alloc(13);+ header.writeUInt32BE(width, 0);+ header.writeUInt32BE(height, 4);+ header[8] = 8;+ header[9] = 2;+ return Buffer.concat([Buffer.from("89504e470d0a1a0a", "hex"), chunk("IHDR", header), chunk("IDAT", zlib.deflateSync(raw)), chunk("IEND", Buffer.alloc(0))]);+}++async function turn(server: AppServer, threadId: string, input: Json[]): Promise<Json> {+ const started = Date.now();+ const before = server.notifications.length;+ const { turn } = await server.request<{ turn: Json }>("turn/start", { threadId, input, effort: "low" }, 120_000);+ const done = await server.waitFor((n) => n.method === "turn/completed" && n.params.turn?.id === turn.id, 20 * 60_000);+ const mine = server.notifications.slice(before).filter((n) => n.params?.turnId === turn.id || n.params?.turn?.id === turn.id);+ const items = mine.filter((n) => n.method === "item/completed").map((n) => n.params.item);+ return {+ turnId: turn.id,+ status: done.params.turn.status,+ error: done.params.turn.error ?? null,+ ms: Date.now() - started,+ tools: items.filter((item) => !["agentMessage", "reasoning", "userMessage"].includes(item.type)).map((item) => `${item.type}:${item.status ?? ""}`),+ reply: items.filter((item) => item.type === "agentMessage").map((item) => item.text).join(" ").slice(0, 200),+ errors: mine.filter((n) => n.method === "error").map((n) => n.params.error?.message ?? "error"),+ };+}++async function main(): Promise<void> {+ const portIndex = process.argv.indexOf("--port");+ const port = Number(portIndex >= 0 ? process.argv[portIndex + 1] : 17891);+ const workDir = join(localRoot, "p1");+ mkdirSync(join(localRoot, "logs"), { recursive: true });+ mkdirSync(workDir, { recursive: true });+ const pattern = join(workDir, "test-pattern.png");+ writeFileSync(pattern, testPattern());++ const startedAt = new Date().toISOString();+ const server = new AppServer(findBundledCodex(), ["-c", `openai_base_url="http://127.0.0.1:${port}/backend-api/codex"`], {}, join(localRoot, "logs", `p1-selftest-appserver-${startedAt.replaceAll(":", "-")}.log`));+ const results: Json = {};+ let threadId = "";+ try {+ await server.initialize();+ const started = await server.request<{ thread: Json }>("thread/start", { cwd: workDir, approvalPolicy: "never", sandbox: "read-only", ephemeral: true });+ threadId = started.thread.id;+ const text = (value: string) => ({ type: "text", text: value, text_elements: [] });+ results.text = await turn(server, threadId, [text("请只回复“收到”两个字。")]);+ results.attachment = await turn(server, threadId, [text("附件里是什么图案?用一句话回答,不需要调用任何工具。"), { type: "localImage", path: pattern }]);+ results.imageGeneration = await turn(server, threadId, [text("请用内置的生图工具生成一张简单的图片:浅蓝色背景,正中间一个黄色圆形。生成 1 张即可。")]);+ results.imageEdit = await turn(server, threadId, [text("请用内置的生图工具修改刚才那张图:把黄色圆形改成红色,其余保持不变。生成 1 张即可。")]);+ } finally {+ await server.stop();+ }++ const logFile = join(localRoot, "proxy", `${new Date().toISOString().slice(0, 10)}.jsonl`);+ const entries = readFileSync(logFile, "utf8").trim().split("\n").map((line) => JSON.parse(line)).filter((entry: Json) => entry.at >= startedAt);+ const forThread = entries.filter((entry: Json) => entry.threadId === threadId);+ const summary = Object.values(forThread.reduce((groups: Record<string, Json>, entry: Json) => {+ const key = `${entry.transport} ${entry.method ?? "GET"} ${entry.path} ${entry.status ?? entry.upstreamStatus ?? ""}`;+ groups[key] ??= { request: key, count: 0 };+ groups[key].count++;+ return groups;+ }, {}));+ const report = { createdAt: new Date().toISOString(), threadId, results, proxyEntriesInWindow: entries.length, proxyEntriesForThread: forThread.length, summary, otherThreadIds: [...new Set(entries.map((e: Json) => e.threadId).filter((id: string | null) => id && id !== threadId))] };+ writeFileSync(join(localRoot, "p1-selftest.json"), JSON.stringify(report, null, 2));+ console.log(JSON.stringify({ results, summary, proxyEntriesInWindow: entries.length, proxyEntriesForThread: forThread.length }, null, 2));+}++await main();diff --git a/spike/src/proxy.test.ts b/spike/src/proxy.test.tsnew file mode 100644index 0000000..8d65e93--- /dev/null+++ b/spike/src/proxy.test.ts@@ -0,0 +1,43 @@+// Purpose: P1-2 — pure helpers of the transparent proxy: outbound proxy detection, task identity, body metadata.+// Input: synthetic env, headers and request bodies; output: Node test assertions only.++import assert from "node:assert/strict";+import test from "node:test";+import { describeBody, outboundProxy, requestIdentity } from "./proxy.ts";++const none = () => null;++test("outbound proxy comes from the environment, then Windows settings", () => {+ assert.deepEqual(outboundProxy({ HTTPS_PROXY: "http://127.0.0.1:8888", NO_PROXY: "localhost,127.0.0.1,::1,.local" }, none), { host: "127.0.0.1", port: 8888 });+ assert.deepEqual(outboundProxy({}, () => "http=10.0.0.1:80;https=10.0.0.2:8080"), { host: "10.0.0.2", port: 8080 });+ assert.deepEqual(outboundProxy({}, () => "127.0.0.1:7890"), { host: "127.0.0.1", port: 7890 });+ assert.equal(outboundProxy({}, none), null);+});++test("NO_PROXY entries covering the upstream host mean a direct connection", () => {+ for (const entry of ["chatgpt.com", ".chatgpt.com", "*"]) {+ assert.equal(outboundProxy({ HTTPS_PROXY: "http://127.0.0.1:8888", NO_PROXY: `localhost,${entry}` }, none), null);+ }+});++test("the task a request belongs to is read from x-codex-turn-metadata", () => {+ const headers = { "x-codex-turn-metadata": JSON.stringify({ thread_id: "thread-a", turn_id: "turn-1" }), "x-codex-window-id": "thread-a:0" };+ assert.deepEqual(requestIdentity(headers), { threadId: "thread-a", turnId: "turn-1", windowId: "thread-a:0" });+ assert.deepEqual(requestIdentity({ "x-codex-turn-metadata": "not json" }), { threadId: null, turnId: null, windowId: null });+});++test("request metadata counts images in messages and in tool outputs, without content", () => {+ const body = {+ model: "m",+ prompt_cache_key: "thread-a",+ stream: true,+ input: [+ { type: "message", role: "user", content: [{ type: "input_text", text: "secret words" }, { type: "input_image", image_url: "data:image/png;base64,AAAA" }] },+ { type: "custom_tool_call_output", call_id: "c1", output: [{ type: "input_image", image_url: "data:image/png;base64,BBBBBBBB" }] },+ ],+ };+ const described = describeBody("/backend-api/codex/responses", body);+ assert.deepEqual(described, { kind: "responses", model: "m", inputItems: 2, images: 2, imageBytes: "data:image/png;base64,AAAA".length + "data:image/png;base64,BBBBBBBB".length, stream: true, promptCacheKey: "thread-a" });+ assert.doesNotMatch(JSON.stringify(described), /secret words/);+ assert.equal(describeBody("/backend-api/codex/images/edits", { model: "gpt-image", images: [{}, {}], size: "1024x1024" }).kind, "image_edit");+});diff --git a/spike/src/proxy.ts b/spike/src/proxy.tsnew file mode 100644index 0000000..5d12282--- /dev/null+++ b/spike/src/proxy.ts@@ -0,0 +1,216 @@+// Purpose: P1-2 — transparent local proxy between Codex and the ChatGPT backend. HTTP requests and WebSocket+// upgrades are forwarded byte for byte; only metadata is logged (never auth headers or conversation content).+// Input: [--port 17891]; the outbound proxy is taken from HTTPS_PROXY/HTTP_PROXY or the Windows proxy settings.+// Output: responses streamed back to Codex; one JSON line per request in local/proxy/<date>.jsonl.++import { execFileSync } from "node:child_process";+import { appendFileSync, mkdirSync } from "node:fs";+import http, { type IncomingHttpHeaders } from "node:http";+import net from "node:net";+import { dirname, join, resolve } from "node:path";+import tls from "node:tls";+import { fileURLToPath, pathToFileURL } from "node:url";+import zlib from "node:zlib";++type Json = Record<string, any>;+const UPSTREAM_HOST = "chatgpt.com";+const HOP_BY_HOP = new Set(["connection", "keep-alive", "proxy-connection", "transfer-encoding", "te", "trailer", "upgrade", "host"]);+const localRoot = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");++// Outbound proxy: environment first, then the Windows per-user setting; NO_PROXY is honoured for the upstream host.+export function outboundProxy(env = process.env, windowsSetting = readWindowsProxy): { host: string; port: number } | null {+ const noProxy = (env.NO_PROXY ?? env.no_proxy ?? "").split(",").map((s) => s.trim().replace(/^\./, "")).filter(Boolean);+ if (noProxy.some((entry) => entry === "*" || UPSTREAM_HOST === entry || UPSTREAM_HOST.endsWith(`.${entry}`))) return null;+ const fromEnv = env.HTTPS_PROXY ?? env.https_proxy ?? env.HTTP_PROXY ?? env.http_proxy;+ let value = fromEnv || windowsSetting();+ if (!value) return null;+ // Windows may store per-protocol entries: "http=host:port;https=host:port".+ if (value.includes("=")) value = /https=([^;]+)/.exec(value)?.[1] ?? /http=([^;]+)/.exec(value)?.[1] ?? "";+ if (!value) return null;+ const url = new URL(/^[a-z]+:\/\//i.test(value) ? value : `http://${value}`);+ return { host: url.hostname, port: Number(url.port || 80) };+}++function readWindowsProxy(): string | null {+ if (process.platform !== "win32") return null;+ try {+ const out = execFileSync("reg", ["query", "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"], { encoding: "utf8" });+ if (!/ProxyEnable\s+REG_DWORD\s+0x1/.test(out)) return null;+ return /ProxyServer\s+REG_SZ\s+(\S+)/.exec(out)?.[1] ?? null;+ } catch {+ return null;+ }+}++function connectUpstream(via: { host: string; port: number } | null): Promise<tls.TLSSocket> {+ const startTls = (socket?: net.Socket) => new Promise<tls.TLSSocket>((ok, fail) => {+ const secure = tls.connect({ socket, host: socket ? undefined : UPSTREAM_HOST, port: 443, servername: UPSTREAM_HOST, ALPNProtocols: ["http/1.1"] }, () => ok(secure));+ secure.once("error", fail);+ });+ if (!via) return startTls();+ return new Promise((ok, fail) => {+ const socket = net.connect(via.port, via.host, () => socket.write(`CONNECT ${UPSTREAM_HOST}:443 HTTP/1.1\r\nHost: ${UPSTREAM_HOST}:443\r\n\r\n`));+ let buffered = Buffer.alloc(0);+ const onData = (chunk: Buffer) => {+ buffered = Buffer.concat([buffered, chunk]);+ const end = buffered.indexOf("\r\n\r\n");+ if (end < 0) return;+ socket.off("data", onData);+ const status = buffered.toString("latin1", 0, end).split(" ")[1];+ if (status !== "200") { socket.destroy(); fail(new Error(`outbound proxy refused CONNECT (${status})`)); return; }+ startTls(socket).then(ok, fail);+ };+ socket.on("data", onData);+ socket.once("error", fail);+ });+}++function forwardHeaders(headers: IncomingHttpHeaders): Record<string, string | string[]> {+ const out: Record<string, string | string[]> = {};+ for (const [name, value] of Object.entries(headers)) if (value !== undefined && !HOP_BY_HOP.has(name)) out[name] = value;+ out.host = UPSTREAM_HOST;+ return out;+}++// Which task a request belongs to, from Codex's own turn metadata header.+export function requestIdentity(headers: IncomingHttpHeaders): { threadId: string | null; turnId: string | null; windowId: string | null } {+ let meta: Json = {};+ try { meta = JSON.parse(String(headers["x-codex-turn-metadata"] ?? "{}")); } catch { /* not JSON */ }+ return { threadId: meta.thread_id ?? meta.session_id ?? null, turnId: meta.turn_id ?? null, windowId: (headers["x-codex-window-id"] as string) ?? null };+}++function decodeBody(body: Buffer, encoding: string | undefined): Buffer | null {+ try {+ if (!encoding || encoding === "identity") return body;+ if (encoding === "zstd") return zlib.zstdDecompressSync(body);+ if (encoding === "gzip") return zlib.gunzipSync(body);+ if (encoding === "br") return zlib.brotliDecompressSync(body);+ } catch { /* fall through */ }+ return null;+}++// Metadata only: counts and sizes, never text or image content.+export function describeBody(path: string, json: Json): Json {+ if (/\/responses$/.test(path)) {+ const input: Json[] = Array.isArray(json.input) ? json.input : [];+ let images = 0;+ let imageBytes = 0;+ const visit = (value: unknown) => {+ if (Array.isArray(value)) return value.forEach(visit);+ if (!value || typeof value !== "object") return;+ const part = value as Json;+ if (part.type === "input_image" && typeof part.image_url === "string") { images++; imageBytes += part.image_url.length; }+ for (const child of Object.values(part)) if (typeof child === "object") visit(child);+ };+ visit(input);+ return { kind: "responses", model: json.model ?? null, inputItems: input.length, images, imageBytes, stream: json.stream ?? null, promptCacheKey: json.prompt_cache_key ?? null };+ }+ if (/\/images\/(generations|edits)$/.test(path)) {+ const inputs = Array.isArray(json.images) ? json.images : json.image ? [json.image] : [];+ return { kind: path.endsWith("edits") ? "image_edit" : "image_generation", model: json.model ?? null, inputImages: inputs.length, size: json.size ?? null };+ }+ return { kind: "other" };+}++function log(entry: Json): void {+ mkdirSync(join(localRoot, "proxy"), { recursive: true });+ appendFileSync(join(localRoot, "proxy", `${new Date().toISOString().slice(0, 10)}.jsonl`), `${JSON.stringify(entry)}\n`);+}++function main(): void {+ const portIndex = process.argv.indexOf("--port");+ const port = Number(portIndex >= 0 ? process.argv[portIndex + 1] : 17891);+ const via = outboundProxy();+ let sequence = 0;++ const server = http.createServer((req, res) => {+ if (req.url === "/__cam/health") {+ res.writeHead(200, { "content-type": "application/json" });+ res.end(JSON.stringify({ ok: true, upstream: UPSTREAM_HOST, via: via ? `${via.host}:${via.port}` : "direct" }));+ return;+ }+ const id = ++sequence;+ const started = Date.now();+ const path = (req.url ?? "/").split("?")[0];+ const chunks: Buffer[] = [];+ let requestBytes = 0;+ let responseBytes = 0;+ let status = 0;+ let finished = false;+ const finish = (error?: string) => {+ if (finished) return;+ finished = true;+ const body = Buffer.concat(chunks);+ const decoded = req.method === "POST" ? decodeBody(body, req.headers["content-encoding"] as string | undefined) : null;+ let details: Json = {};+ if (decoded) { try { details = describeBody(path, JSON.parse(decoded.toString("utf8"))); } catch { details = { kind: "unparsed" }; } }+ log({ 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, ...requestIdentity(req.headers), ...details, error: error ?? null });+ };+ connectUpstream(via).then((socket) => {+ // No `agent` option: with agent:false Node ignores createConnection and dials the host directly.+ const upstream = http.request({ host: UPSTREAM_HOST, method: req.method, path: req.url, headers: forwardHeaders(req.headers), 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;+ res.writeHead(status, headers);+ answer.on("data", (chunk: Buffer) => { responseBytes += chunk.length; });+ answer.pipe(res);+ answer.on("end", () => finish());+ answer.on("error", (error) => finish(String(error)));+ });+ upstream.on("error", (error) => { if (!res.headersSent) res.writeHead(502); res.end(); finish(String(error)); });+ // Codex may drop the connection mid-stream; still log the request once.+ res.on("close", () => finish(res.writableFinished ? undefined : "client closed before the response ended"));+ req.on("data", (chunk: Buffer) => { chunks.push(chunk); requestBytes += chunk.length; });+ req.pipe(upstream);+ }, (error) => {+ res.writeHead(502, { "content-type": "text/plain" });+ res.end(`codex-attachment-manager proxy: cannot reach ${UPSTREAM_HOST}`);+ finish(String(error));+ });+ });++ server.on("upgrade", (req, client, head) => {+ const id = ++sequence;+ const started = Date.now();+ let up = head.length;+ let down = 0;+ let upstreamStatus: string | null = null;+ connectUpstream(via).then((socket) => {+ const lines = [`${req.method} ${req.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]}`);+ }+ socket.write(`${lines.join("\r\n")}\r\n\r\n`);+ if (head.length) socket.write(head);+ socket.once("data", (chunk: Buffer) => { upstreamStatus = chunk.toString("latin1", 0, Math.min(chunk.length, 40)).split("\r\n")[0]; });+ socket.on("data", (chunk: Buffer) => { down += chunk.length; });+ client.on("data", (chunk: Buffer) => { up += chunk.length; });+ socket.pipe(client);+ client.pipe(socket);+ let logged = false;+ const close = () => {+ if (logged) return;+ logged = true;+ socket.destroy();+ client.destroy();+ log({ at: new Date(started).toISOString(), id, transport: "websocket", path: (req.url ?? "/").split("?")[0], upstreamStatus, upBytes: up, downBytes: down, ms: Date.now() - started, ...requestIdentity(req.headers) });+ };+ socket.on("close", close);+ client.on("close", close);+ socket.on("error", close);+ client.on("error", close);+ }, (error) => {+ client.end("HTTP/1.1 502 Bad Gateway\r\n\r\n");+ log({ at: new Date(started).toISOString(), id, transport: "websocket", path: req.url, error: String(error), ...requestIdentity(req.headers) });+ });+ });++ server.requestTimeout = 0;+ server.listen(port, "127.0.0.1", () => {+ console.log(JSON.stringify({ listening: `http://127.0.0.1:${port}/backend-api/codex`, upstream: UPSTREAM_HOST, via: via ? `${via.host}:${via.port}` : "direct" }));+ });+}++if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) main();