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
feat(spike): 在 ~/.codex/.env 管理带标记的 NO_PROXY,让当前版本的生图和改图也能连到本地代理
chipfighter3d63c4aaa01b
diff --git a/docs/plan.md b/docs/plan.mdindex 44796ae..366bccf 100644--- a/docs/plan.md+++ b/docs/plan.md@@ -140,12 +140,12 @@- Codex 默认按环境变量选择代理。用户环境里有 `HTTP(S)_PROXY`、没有 `NO_PROXY` 时,连本地地址的请求也会被交给系统代理,然后失败。- 所以要同时打开 `features.respect_system_proxy`,让 Codex 先看 Windows 的代理设置,并把地址写成 `localhost`:Windows 设置里的 `<local>` 只让不带点的主机名直连。- 生图和改图要等 Codex 包含 #47742 的版本才会遵守这个开关。上游从 `0.158.0-alpha.8` 起包含;桌面版 26.917(自带 `0.155.0-alpha.16.4`)还没有,而且检查更新显示已是最新。在此之前,环境变量里有代理、又没有 `NO_PROXY` 的用户,开着代理时不能生图和改图。详见 [p1-report.md](p1-report.md)。-- **不等更新的办法(待用户授权)**:+- **不等更新的办法(用户 2026-09-24 同意,待桌面版验证)**:- Codex 每次启动都会读 `$CODEX_HOME/.env`,把里面的变量设进自己的进程(`CODEX_` 开头的除外,见源码 `arg0` 的 `load_dotenv`)。- 生图模块用的默认客户端认 `NO_PROXY`(P1-3 已实测)。所以在 `.env` 里写 `NO_PROXY=localhost,127.0.0.1,::1`,生图和改图不等 #47742 也能连到本地代理。- - 这样还可以不再打开 `respect_system_proxy`:Codex 其他请求走代理的方式和原来完全一样,只有发往本机的请求不走系统代理。- - 影响范围只有 Codex 自己的进程和它启动的工具,而且只涉及本机地址。- - 要写 `~/.codex/.env`,超出了目前的授权范围,需要用户同意。+ - 用户自己设过的 `NO_PROXY` 条目会合并进来,因为 `.env` 里的值会在 Codex 进程里替换掉原来的值。`.env` 里已经有用户自己的 `NO_PROXY` 时,不覆盖,直接报告。+ - 仍然保留 `respect_system_proxy`:读取 `.env` 这一行为没有写进官方文档,保留它,对话能不能连上就不依赖 `.env`。万一以后的版本不再读 `.env`,最坏的结果也只是生图和改图暂时连不上;而那些版本本来就已经包含 #47742。+ - 影响范围只有 Codex 自己的进程和它启动的工具,而且只涉及本机地址。留下这一段也无害:它只让本机请求直连,不会像 `openai_base_url` 那样在代理不在时让 Codex 连不上。- **元数据差异**:地址不是官方域名时,Codex 会去掉请求里附带的原始工具结果元数据(`executed_tool_calls` 里的 `tool_result_metadata`)。这是随请求上报的内部元数据,不是模型看到的内容。### P1:只转发、不改写diff --git a/docs/spec.md b/docs/spec.mdindex b53bc34..28138be 100644--- a/docs/spec.md+++ b/docs/spec.md@@ -66,9 +66,10 @@## 3. 硬约束-- 原始对话记录和素材文件始终只读,不修改、不移动、不删除。不直接写入 `~/.codex` 下的任何文件,只有两个例外:+- 原始对话记录和素材文件始终只读,不修改、不移动、不删除。不直接写入 `~/.codex` 下的任何文件,只有三个例外:- 官方 app-server 在创建和运行任务时自己产生的正常写入;- - 为接入本地代理,工具可以修改 `config.toml` 里由它自己管理、带标记的设置(用户 2026-09-24 授权)。改之前先备份,能一键恢复,其他设置一律不动。+ - 为接入本地代理,工具可以修改 `config.toml` 里由它自己管理、带标记的设置(用户 2026-09-24 授权)。改之前先备份,能一键恢复,其他设置一律不动;+ - 为让生图和改图也能连到本地代理,工具可以在 `~/.codex/.env` 里写一段带标记的 `NO_PROXY`,只含本机地址,并保留用户自己的条目(用户 2026-09-24 同意)。`.env` 可能含密钥,工具不复制、不输出它,只增删自己的那一段;文件里只剩这一段时,恢复时连文件一起删掉。- 真实数据不进仓库:从真实会话和用户素材里提取的图片、记录片段、日志和备份,只能放在本机的 `local/` 目录(已被 git 忽略),任何时候都不提交。仓库里的样例数据只能是合成的或脱敏的。- 仓库里的文档和代码不写用户本机的具体路径(例如个人项目文件夹)。`~/.codex`、`%LOCALAPPDATA%` 这类通用位置可以写。本项目以后会开源。- 不改写原生任务的历史记录。@@ -117,5 +118,4 @@- 路线待定。路线 A(用 `thread/inject_items` 在新任务里重建)已验证可行,但用户不接受“重建后在界面上看不到原对话”:在同一个任务里勾选、取消文件时,对话必须保持连续可见。现在验证代理路线,即任务不换,每次请求发出前由本地代理按勾选改写:- P1(只转发)已在桌面版通过,生图和改图要等桌面版带上新版 Codex 后复测,见 plan.md 第 9 节;- - P2(按勾选改写)的自测已通过,待桌面版验证,见 plan.md 第 10 节。-- 是否允许工具在 `~/.codex/.env` 里写一段带标记的 `NO_PROXY`,让生图和改图不等 Codex 更新也能经过代理,见 plan.md 第 9 节。+ - P2(按勾选改写)的自测已通过,待桌面版验证,见 plan.md 第 10 节。\ No newline at end of filediff --git a/spike/src/codexconfig.test.ts b/spike/src/codexconfig.test.tsindex e6181eb..a7f6257 100644--- a/spike/src/codexconfig.test.ts+++ b/spike/src/codexconfig.test.ts@@ -1,9 +1,10 @@-// Purpose: P1-1 — the managed config.toml settings are inserted and removed without touching anything else.+// Purpose: P1-1/P2 — the managed config.toml settings and the .env NO_PROXY block 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";+import { coversLoopback, disableProxy, enableNoProxy, enableProxy, noProxyStatus, noProxyValue, proxyStatus } from "./codexconfig.ts";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';@@ -95,3 +96,36 @@ test("a user's own respect_system_proxy is respected", () => {test("disable without managed settings changes nothing", () => {assert.deepEqual(disableProxy(withFeatures), { text: withFeatures, changed: false });});++const LOOP = "localhost,127.0.0.1,::1";++test(".env: the NO_PROXY block goes first and disable restores the file byte for byte", () => {+ const samples = ["", "OPENAI_API_KEY=not-a-real-key\n", "\uFEFFA=1\r\nB=2\r\n", "# only a comment"];+ for (const sample of samples) {+ const { text, changed } = enableNoProxy(sample, LOOP);+ assert.equal(changed, true);+ assert.equal(noProxyStatus(text).value, LOOP);+ assert.match(text.replace(/^\uFEFF/, ""), /^# >>> codex-attachment-manager/);+ assert.equal(disableProxy(text).text, sample);+ }+ assert.equal(disableProxy(enableNoProxy("", LOOP).text).text, "", "a file that only held the block becomes empty");+});++test(".env: enabling twice changes nothing, and a user's own NO_PROXY is never overridden", () => {+ const once = enableNoProxy("A=1\n", LOOP).text;+ assert.deepEqual(enableNoProxy(once, LOOP), { text: once, changed: false });+ for (const own of ["NO_PROXY=corp.example\n", "no_proxy = x\n", "export NO_PROXY=y\n"]) {+ assert.throws(() => enableNoProxy(own, LOOP), /already sets NO_PROXY/);+ assert.equal(noProxyStatus(own).conflict, true);+ }+ assert.equal(noProxyStatus("# NO_PROXY=commented out\n").conflict, false);+});++test("NO_PROXY keeps the user's entries and adds only the missing loopback hosts", () => {+ assert.equal(noProxyValue(null), LOOP);+ assert.equal(noProxyValue(".corp.example, localhost"), ".corp.example,localhost,127.0.0.1,::1");+ assert.equal(coversLoopback(LOOP), true);+ assert.equal(coversLoopback("*"), true);+ assert.equal(coversLoopback("localhost,127.0.0.1"), false);+ assert.equal(coversLoopback(null), false);+});diff --git a/spike/src/codexconfig.ts b/spike/src/codexconfig.tsindex 2330d36..9ef9448 100644--- a/spike/src/codexconfig.ts+++ b/spike/src/codexconfig.ts@@ -1,10 +1,14 @@// 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.+// P2 — also a marked NO_PROXY block in $CODEX_HOME/.env, which Codex loads at startup, so its image generation+// client (which ignores respect_system_proxy before upstream #47742) reaches the local proxy too.+// Nothing else in either 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.+// Output: the edited files. config.toml is copied to local/config-backup/ before every change; .env is never copied+// or printed, because it may hold credentials — its block is removed byte-exactly instead.-import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { execFileSync } from "node:child_process";+import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";import { homedir } from "node:os";import { dirname, join, resolve } from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";@@ -101,6 +105,50 @@ export function proxyStatus(text: string): { enabled: boolean; url: string | nul};}+const LOOPBACK = ["localhost", "127.0.0.1", "::1"];+const NO_PROXY_LINE = /^\s*(export\s+)?no_proxy\s*=/i;++// The user's own NO_PROXY entries are kept, because the .env value replaces the variable inside Codex.+export function noProxyValue(existing: string | null): string {+ const entries = (existing ?? "").split(",").map((entry) => entry.trim()).filter(Boolean);+ for (const host of LOOPBACK) if (!entries.some((entry) => entry.toLowerCase() === host)) entries.push(host);+ return entries.join(",");+}++export function coversLoopback(value: string | null): boolean {+ const entries = (value ?? "").split(",").map((entry) => entry.trim().toLowerCase());+ return entries.includes("*") || LOOPBACK.every((host) => entries.includes(host));+}++// The block goes first, like in config.toml, so disableProxy removes it and the blank line after it.+export function enableNoProxy(text: string, value: string): { text: string; changed: boolean } {+ const { bom, body, eol } = parts(disableProxy(text).text);+ if (body.split(eol).some((line) => NO_PROXY_LINE.test(line))) throw new Error(".env already sets NO_PROXY; not overriding it");+ const next = bom + [BEGIN, `NO_PROXY=${value}`, END, ""].join(eol) + eol + body;+ return { text: next, changed: next !== text };+}++export function noProxyStatus(text: string): { managed: boolean; value: string | null; conflict: boolean } {+ const lines = parts(text).body.split(parts(text).eol);+ const begin = lines.findIndex((line) => line.trim() === BEGIN);+ const line = begin >= 0 ? lines.slice(begin).find((l) => NO_PROXY_LINE.test(l)) : undefined;+ const base = parts(disableProxy(text).text);+ return { managed: begin >= 0, value: line ? line.slice(line.indexOf("=") + 1).trim() : null, conflict: base.body.split(base.eol).some((l) => NO_PROXY_LINE.test(l)) };+}++// What the desktop app inherits: the user's variable overrides the machine's.+function persistedEnv(name: string): string | null {+ if (process.platform !== "win32") return null;+ for (const key of ["HKCU\\Environment", "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"]) {+ try {+ const out = execFileSync("reg", ["query", key, "/v", name], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });+ const match = new RegExp(`${name}\\s+REG_(?:EXPAND_)?SZ\\s+(.*)`, "i").exec(out);+ if (match) return match[1].trim();+ } catch { /* not set at this level */ }+ }+ return null;+}+export function codexHome(): string {return process.env.CODEX_HOME?.trim() || join(homedir(), ".codex");}@@ -109,27 +157,42 @@ 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 dotenv = join(codexHome(), ".env");const current = existsSync(config) ? readFileSync(config, "utf8") : "";+ const currentEnv = existsSync(dotenv) ? readFileSync(dotenv, "utf8") : null;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");};+ // Written through a temporary file, so .env is never left half-written; a file that only held our block is removed.+ const writeEnv = (next: string) => {+ if (!next.replace(/^/, "").trim()) { rmSync(dotenv, { force: true }); return; }+ writeFileSync(`${dotenv}.cam-tmp`, next, "utf8");+ renameSync(`${dotenv}.cam-tmp`, dotenv);+ };+ const userNoProxy = persistedEnv("NO_PROXY");+ const envStatus = (text: string | null) => ({ dotenvExists: text !== null, noProxy: noProxyStatus(text ?? ""), userNoProxy });if (command === "enable") {const index = process.argv.indexOf("--port");const port = Number(index >= 0 ? process.argv[index + 1] : 17891);// "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`);+ // Checked before config.toml is written, so a conflict leaves both files untouched.+ const env = coversLoopback(userNoProxy) ? { text: currentEnv, changed: false } : enableNoProxy(currentEnv ?? "", noProxyValue(userNoProxy));if (changed) write(text);- console.log(JSON.stringify({ command, changed, ...proxyStatus(text) }));+ if (env.changed) writeEnv(env.text!);+ console.log(JSON.stringify({ command, changed, envChanged: env.changed, ...proxyStatus(text), ...envStatus(env.text) }));} else if (command === "disable") {const { text, changed } = disableProxy(current);+ const env = currentEnv === null ? { text: null, changed: false } : disableProxy(currentEnv);if (changed) write(text);- console.log(JSON.stringify({ command, changed, ...proxyStatus(text) }));+ if (env.changed) writeEnv(env.text!);+ console.log(JSON.stringify({ command, changed, envChanged: env.changed, ...proxyStatus(text), ...envStatus(existsSync(dotenv) ? env.text : null) }));} else if (command === "status") {- console.log(JSON.stringify({ command, configExists: existsSync(config), ...proxyStatus(current) }));+ console.log(JSON.stringify({ command, configExists: existsSync(config), ...proxyStatus(current), ...envStatus(currentEnv) }));} else {throw new Error("usage: codexconfig.ts enable [--port N] | disable | status");}