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.
TypeScript ai-agentsclaude-codeclaude-code-plugincodexcodex-plugincontext-managementdeveloper-toolsimage-generationmcpmultimodal
fix(spike): 桌面版连不上本地代理——改用 localhost 并启用 respect_system_proxy
chipfighterf33d5c648323
diff --git a/spike/src/appserver.ts b/spike/src/appserver.tsindex c8699b7..1362b96 100644--- a/spike/src/appserver.ts+++ b/spike/src/appserver.ts@@ -41,10 +41,13 @@ export class AppServer {#onServerRequest: ServerRequestHandler | undefined;#exited: Promise<number | null>;- constructor(codexPath: string, args: string[], env: Record<string, string>, stderrLog: string, onServerRequest?: ServerRequestHandler) {+ // `env` overrides the inherited environment; an undefined value removes that variable.+ constructor(codexPath: string, args: string[], env: Record<string, string | undefined>, stderrLog: string, onServerRequest?: ServerRequestHandler) {this.#log = createWriteStream(stderrLog, { flags: "a" });this.#onServerRequest = onServerRequest;- this.#child = spawn(codexPath, ["app-server", ...args], { env: { ...process.env, ...env }, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });+ const childEnv: Record<string, string | undefined> = { ...process.env, ...env };+ for (const [name, value] of Object.entries(childEnv)) if (value === undefined) delete childEnv[name];+ this.#child = spawn(codexPath, ["app-server", ...args], { env: childEnv, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });this.#child.stderr.pipe(this.#log);this.#exited = new Promise((resolve) => this.#child.on("exit", (code) => resolve(code)));this.#child.on("exit", (code) => {diff --git a/spike/src/codexconfig.test.ts b/spike/src/codexconfig.test.tsindex d152ff5..e6181eb 100644--- a/spike/src/codexconfig.test.ts+++ b/spike/src/codexconfig.test.ts@@ -1,12 +1,13 @@-// Purpose: P1-1 — the managed config.toml block is inserted and removed without touching anything else.+// Purpose: P1-1 — the managed config.toml settings are 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';+const URL = "http://localhost:17891/backend-api/codex";+const withFeatures = 'model = "gpt-6-sol"\n\n[features]\nview_image = true\n\n[mcp_servers.demo]\ncommand = "node"\n';+const withoutFeatures = 'model = "gpt-6-sol"\n\n[mcp_servers.demo]\ncommand = "node"\n';function topLevelKeys(text: string): string[] {const keys: string[] = [];@@ -18,47 +19,79 @@ function topLevelKeys(text: string): string[] {return keys;}+function tableKeys(text: string, table: string): string[] {+ const lines = text.split(/\r?\n/);+ const start = lines.findIndex((line) => line.trim() === `[${table}]`);+ const keys: string[] = [];+ for (const line of lines.slice(start + 1)) {+ 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);+ const { text, changed } = enableProxy(withFeatures, 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");+ assert.match(text, /openai_base_url = "http:\/\/localhost:17891\/backend-api\/codex"/);+});++test("respect_system_proxy goes into an existing [features] table", () => {+ const { text } = enableProxy(withFeatures, URL);+ assert.deepEqual(tableKeys(text, "features"), ["respect_system_proxy", "view_image"]);+ assert.equal(proxyStatus(text).respectSystemProxy, "managed");+});++test("without a [features] table it becomes a top-level dotted key", () => {+ const { text } = enableProxy(withoutFeatures, URL);+ assert.deepEqual(topLevelKeys(text), ["openai_base_url", "features.respect_system_proxy", "model"]);+ assert.doesNotMatch(text, /^\[features\]/m);});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);- }+ const samples = [withFeatures, withoutFeatures, "", "" + withFeatures.replaceAll("\n", "\r\n"), "# only a comment\n"];+ for (const sample of samples) 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");+test("CRLF files get CRLF blocks and keep their BOM", () => {+ const crlf = "" + withFeatures.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;+test("enabling twice is a no-op, and a new URL only replaces the managed setting", () => {+ const once = enableProxy(withFeatures, URL).text;assert.deepEqual(enableProxy(once, URL), { text: once, changed: false });- const moved = enableProxy(once, "http://127.0.0.1:18000/backend-api/codex");+ const moved = enableProxy(once, "http://localhost: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);+ assert.equal(proxyStatus(moved.text).url, "http://localhost:18000/backend-api/codex");+ assert.equal(disableProxy(moved.text).text, withFeatures);});test("a user's own top-level openai_base_url is never overwritten", () => {- const mine = 'openai_base_url = "https://example.test/v1"\n' + original;+ const mine = 'openai_base_url = "https://example.test/v1"\n' + withFeatures;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';+ const scoped = withFeatures + '\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 });+test("a user's own respect_system_proxy is respected", () => {+ const on = withFeatures.replace("[features]\n", "[features]\nrespect_system_proxy = true\n");+ const enabled = enableProxy(on, URL).text;+ assert.deepEqual(tableKeys(enabled, "features"), ["respect_system_proxy", "view_image"], "not duplicated");+ assert.equal(proxyStatus(enabled).respectSystemProxy, "user");+ assert.equal(disableProxy(enabled).text, on);+ const off = withFeatures.replace("[features]\n", "[features]\nrespect_system_proxy = false\n");+ assert.throws(() => enableProxy(off, URL), /turns respect_system_proxy off/);+});++test("disable without managed settings changes nothing", () => {+ assert.deepEqual(disableProxy(withFeatures), { text: withFeatures, changed: false });});diff --git a/spike/src/codexconfig.ts b/spike/src/codexconfig.tsindex 51acced..2330d36 100644--- a/spike/src/codexconfig.ts+++ b/spike/src/codexconfig.ts@@ -1,5 +1,6 @@-// 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.+// Purpose: P1-1 — point Codex's built-in openai provider at the local proxy by managing marked blocks+// in config.toml (openai_base_url and respect_system_proxy), and remove exactly those blocks 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.@@ -17,59 +18,87 @@ function parts(text: string): { bom: string; body: string; eol: string } {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 };+const isTable = (line: string) => /^\s*\[/.test(line);++// TOML top-level keys end at the first table header; a second top-level key would be a duplicate.+function topLevelValue(lines: string[], key: string): string | null {+ for (const line of lines) {+ if (isTable(line)) return null;+ const match = new RegExp(`^\\s*${key.replaceAll(".", "\\.")}\\s*=\\s*(.+?)\\s*(#.*)?$`).exec(line);+ if (match) return match[1];+ }+ return null;+}++function featuresHeader(lines: string[]): number {+ return lines.findIndex((line) => /^\s*\[features\]\s*(#.*)?$/.test(line));}-// 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;+// The user's own respect_system_proxy, as a top-level dotted key or inside [features]; null when absent.+function userRespectSystemProxy(lines: string[]): string | null {+ const dotted = topLevelValue(lines, "features.respect_system_proxy");+ if (dotted !== null) return dotted;+ const header = featuresHeader(lines);+ if (header < 0) return null;+ for (const line of lines.slice(header + 1)) {+ if (isTable(line)) break;+ const match = /^\s*respect_system_proxy\s*=\s*(\S+)/.exec(line);+ if (match) return match[1];}- return false;+ return null;}-export function proxyStatus(text: string): { enabled: boolean; url: string | null; conflict: boolean } {- const { body, eol } = parts(text);+// Removes every managed block; the blank line enable adds after the top block goes with it.+export function disableProxy(text: string): { text: string; changed: boolean } {+ const { bom, 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) };+ const kept: string[] = [];+ let changed = false;+ for (let i = 0; i < lines.length; i++) {+ if (lines[i].trim() !== BEGIN) { kept.push(lines[i]); continue; }+ const end = lines.findIndex((line, j) => j > i && line.trim() === END);+ if (end < 0) throw new Error("a managed block in config.toml has no end marker");+ const atTop = kept.length === 0;+ i = end;+ if (atTop && lines[i + 1] === "") i++;+ changed = true;+ }+ return changed ? { text: bom + kept.join(eol), changed } : { text, changed: false };}+// Codex needs two settings to reach the proxy on Windows: openai_base_url (top level, so it goes first in the+// file) and features.respect_system_proxy, without which Codex sends even localhost through HTTP(S)_PROXY.export function enableProxy(text: string, url: string): { text: string; changed: boolean } {- const { bom, body, eol } = parts(text);+ const { bom, body, eol } = parts(disableProxy(text).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 };+ if (topLevelValue(lines, "openai_base_url") !== null) throw new Error("config.toml already sets openai_base_url; not overwriting it");+ const own = userRespectSystemProxy(lines);+ if (own !== null && own !== "true") throw new Error("config.toml turns respect_system_proxy off; not overriding it");+ const header = featuresHeader(lines);+ const top = [BEGIN, `openai_base_url = "${url}"`];+ if (own === null && header < 0) top.push("features.respect_system_proxy = true");+ top.push(END, "");+ if (own === null && header >= 0) lines.splice(header + 1, 0, BEGIN, "respect_system_proxy = true", END);+ const next = bom + top.join(eol) + eol + lines.join(eol);+ return { text: next, changed: next !== text };}-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 proxyStatus(text: string): { enabled: boolean; url: string | null; conflict: boolean; respectSystemProxy: "managed" | "user" | "off" | "absent" } {+ const { body, eol } = parts(text);+ const lines = body.split(eol);+ const enabled = lines.some((line) => line.trim() === BEGIN);+ const begin = lines.findIndex((line) => line.trim() === BEGIN);+ const urlLine = begin >= 0 ? lines.slice(begin).find((line) => /^\s*openai_base_url\s*=/.test(line)) : undefined;+ const base = parts(disableProxy(text).text);+ const baseLines = base.body.split(base.eol);+ const own = userRespectSystemProxy(baseLines);+ const managedRsp = enabled && lines.some((line, i) => /respect_system_proxy\s*=\s*true/.test(line) && lines.slice(0, i).reverse().find((l) => l.trim() === BEGIN || l.trim() === END)?.trim() === BEGIN);+ return {+ enabled,+ url: urlLine ? (/"([^"]*)"/.exec(urlLine)?.[1] ?? null) : null,+ conflict: topLevelValue(baseLines, "openai_base_url") !== null,+ respectSystemProxy: managedRsp ? "managed" : own === "true" ? "user" : own !== null ? "off" : "absent",+ };}export function codexHome(): string {@@ -90,7 +119,9 @@ function main(): void {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`);+ // "localhost", not 127.0.0.1: Codex on Windows applies the system proxy's "<local>" bypass only to+ // host names without a dot, so 127.0.0.1 would be sent to the user's system proxy.+ const { text, changed } = enableProxy(current, `http://localhost:${port}/backend-api/codex`);if (changed) write(text);console.log(JSON.stringify({ command, changed, ...proxyStatus(text) }));} else if (command === "disable") {diff --git a/spike/src/p1-selftest.ts b/spike/src/p1-selftest.tsindex 326682c..e75b0a8 100644--- a/spike/src/p1-selftest.ts+++ b/spike/src/p1-selftest.ts@@ -1,6 +1,9 @@// 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.+// Input: [--port 17891] [--host localhost] [--desktop-env] [--only-text] [--label name]; the proxy must already be running.+// --desktop-env drops NO_PROXY so the app-server sees the same proxy environment as the desktop app;+// --respect-system-proxy turns on features.respect_system_proxy, as the managed config.toml does.+// Output: local/p1-selftest-<label>.json and a console summary.import { mkdirSync, readFileSync, writeFileSync } from "node:fs";import { dirname, join, resolve } from "node:path";@@ -58,8 +61,12 @@ async function turn(server: AppServer, threadId: string, input: Json[]): Promise}async function main(): Promise<void> {- const portIndex = process.argv.indexOf("--port");- const port = Number(portIndex >= 0 ? process.argv[portIndex + 1] : 17891);+ const option = (name: string, fallback: string) => (process.argv.includes(name) ? process.argv[process.argv.indexOf(name) + 1] : fallback);+ const port = Number(option("--port", "17891"));+ const host = option("--host", "localhost");+ const label = option("--label", "default");+ const desktopEnv = process.argv.includes("--desktop-env");+ const onlyText = process.argv.includes("--only-text");const workDir = join(localRoot, "p1");mkdirSync(join(localRoot, "logs"), { recursive: true });mkdirSync(workDir, { recursive: true });@@ -67,7 +74,9 @@ async function main(): Promise<void> {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 env = desktopEnv ? { NO_PROXY: undefined, no_proxy: undefined } : {};+ const extra = process.argv.includes("--respect-system-proxy") ? ["-c", "features.respect_system_proxy=true"] : [];+ const server = new AppServer(findBundledCodex(), ["-c", `openai_base_url="http://${host}:${port}/backend-api/codex"`, ...extra], env, join(localRoot, "logs", `p1-selftest-${label}-appserver-${startedAt.replaceAll(":", "-")}.log`));const results: Json = {};let threadId = "";try {@@ -76,13 +85,17 @@ async function main(): Promise<void> {threadId = started.thread.id;const text = (value: string) => ({ type: "text", text: value, text_elements: [] });results.text = await turn(server, threadId, [text("请只回复“收到”两个字。")]);+ if (onlyText) return;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();+ await summarize(threadId, startedAt, { host, port, desktopEnv, respectSystemProxy: extra.length > 0, onlyText, label }, results);}+}+async function summarize(threadId: string, startedAt: string, options: Json, results: Json): Promise<void> {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);@@ -92,9 +105,9 @@ async function main(): Promise<void> {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));+ const report = { createdAt: new Date().toISOString(), options, 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-${options.label}.json`), JSON.stringify(report, null, 2));+ console.log(JSON.stringify({ options, results, summary, proxyEntriesInWindow: entries.length, proxyEntriesForThread: forThread.length }, null, 2));}await main();diff --git a/spike/src/proxy.ts b/spike/src/proxy.tsindex 5d12282..6eb79b8 100644--- a/spike/src/proxy.ts+++ b/spike/src/proxy.ts@@ -8,6 +8,7 @@ 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 type { Duplex } from "node:stream";import tls from "node:tls";import { fileURLToPath, pathToFileURL } from "node:url";import zlib from "node:zlib";@@ -123,7 +124,7 @@ function main(): void {const via = outboundProxy();let sequence = 0;- const server = http.createServer((req, res) => {+ 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, upstream: UPSTREAM_HOST, via: via ? `${via.host}:${via.port}` : "direct" }));@@ -168,9 +169,9 @@ function main(): void {res.end(`codex-attachment-manager proxy: cannot reach ${UPSTREAM_HOST}`);finish(String(error));});- });+ };- server.on("upgrade", (req, client, head) => {+ const onUpgrade = (req: http.IncomingMessage, client: Duplex, head: Buffer) => {const id = ++sequence;const started = Date.now();let up = head.length;@@ -205,12 +206,18 @@ function main(): void {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" }));- });+ // Codex may resolve "localhost" to either loopback address, so listen on both (and only on loopback).+ for (const host of ["127.0.0.1", "::1"]) {+ const server = http.createServer(onRequest);+ server.on("upgrade", onUpgrade);+ server.requestTimeout = 0;+ server.on("error", (error) => console.error(JSON.stringify({ host, error: String(error) })));+ server.listen(port, host, () => {+ console.log(JSON.stringify({ listening: `http://${host.includes(":") ? `[${host}]` : host}:${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();