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(p5): 打包成 Codex 插件——运行代码搬进 plugin/,仓库根目录即插件市场
chipfighterbaf41b8e69f8
diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.jsonnew file mode 100644index 0000000..89ba143--- /dev/null+++ b/.agents/plugins/marketplace.json@@ -0,0 +1,20 @@+{+ "name": "codex-attachment-manager",+ "interface": {+ "displayName": "Codex Attachment Manager"+ },+ "plugins": [+ {+ "name": "codex-attachment-manager",+ "source": {+ "source": "local",+ "path": "./plugin"+ },+ "policy": {+ "installation": "AVAILABLE",+ "authentication": "ON_INSTALL"+ },+ "category": "Productivity"+ }+ ]+}diff --git a/.gitattributes b/.gitattributesnew file mode 100644index 0000000..db7e1d2--- /dev/null+++ b/.gitattributes@@ -0,0 +1 @@+*.cmd text eol=crlfdiff --git a/plugin/.codex-plugin/plugin.json b/plugin/.codex-plugin/plugin.jsonnew file mode 100644index 0000000..370213a--- /dev/null+++ b/plugin/.codex-plugin/plugin.json@@ -0,0 +1,24 @@+{+ "name": "codex-attachment-manager",+ "version": "0.1.0",+ "description": "Choose which images from a Codex task's history go out with the next message. Unchecked images become short placeholders; the task and the conversation stay the same.",+ "author": {+ "name": "chipfighter"+ },+ "homepage": "https://github.com/chipfighter/codex-attachment-manager",+ "repository": "https://github.com/chipfighter/codex-attachment-manager",+ "keywords": ["codex", "images", "context", "attachments", "mcp-app", "proxy"],+ "mcpServers": "./.mcp.json",+ "interface": {+ "displayName": "上下文素材管理器",+ "shortDescription": "选择哪些历史图片随下一条消息发给模型",+ "longDescription": "长任务里的图片会一轮轮累积在上下文里。这个插件在 Codex 右侧的侧边面板里,按时间顺序列出任务历史里的全部图片:勾选的照常发送,取消的换成占位符(有内容相同的图还在发送时,指向那一张)。任务不换,对话连续。模型需要某张图时会回复“需要 IMG-xxx”,给不给由你决定。所有数据只留在本机;除了 Codex 本来就要发给 OpenAI 的请求,不向任何地方发送数据。",+ "developerName": "chipfighter",+ "category": "Productivity",+ "capabilities": ["Interactive", "Read", "Write"],+ "websiteURL": "https://github.com/chipfighter/codex-attachment-manager",+ "brandColor": "#339CFF",+ "logo": "./assets/logo.png",+ "composerIcon": "./assets/logo.png"+ }+}diff --git a/plugin/.mcp.json b/plugin/.mcp.jsonnew file mode 100644index 0000000..c59076e--- /dev/null+++ b/plugin/.mcp.json@@ -0,0 +1,34 @@+{+ "mcpServers": {+ "codex_attachment_manager": {+ "command": "cmd.exe",+ "args": ["/d", "/s", "/c", "call", "./scripts/launch.cmd", "./src/plugin-server.ts"],+ "cwd": ".",+ "default_tools_approval_mode": "approve",+ "env_vars": [+ "CODEX_HOME",+ "CAM_DATA_DIR",+ "CAM_ENGINE_PORT",+ "CODEX_MCP_NODE_PATH",+ "CODEX_BROWSER_USE_NODE_PATH",+ "HTTPS_PROXY",+ "HTTP_PROXY",+ "ALL_PROXY",+ "NO_PROXY",+ "https_proxy",+ "http_proxy",+ "all_proxy",+ "no_proxy",+ "USERPROFILE",+ "LOCALAPPDATA",+ "APPDATA",+ "PATH",+ "SYSTEMROOT",+ "WINDIR",+ "TEMP",+ "TMP"+ ],+ "startup_timeout_sec": 20+ }+ }+}diff --git a/plugin/assets/logo.png b/plugin/assets/logo.pngnew file mode 100644index 0000000..e8b8ab6Binary files /dev/null and b/plugin/assets/logo.png differdiff --git a/plugin/package.json b/plugin/package.jsonnew file mode 100644index 0000000..e77e45b--- /dev/null+++ b/plugin/package.json@@ -0,0 +1,9 @@+{+ "name": "codex-attachment-manager-plugin",+ "private": true,+ "type": "module",+ "description": "The Codex plugin itself: the MCP server, the local proxy engine, the panel and the install command. No dependencies; runs on Node 24 with type stripping (Codex ships one).",+ "engines": {+ "node": ">=24"+ }+}diff --git a/plugin/scripts/launch.cmd b/plugin/scripts/launch.cmdnew file mode 100644index 0000000..11f853c--- /dev/null+++ b/plugin/scripts/launch.cmd@@ -0,0 +1,36 @@+@echo off+rem Purpose: P5 - start the plugin's MCP server with a Node that runs TypeScript directly (Node 24 or newer).+rem Tries the Node runtimes that Codex ships first, then a node on PATH.+rem Input: the script to run and its arguments. Output: whatever the script prints (the MCP stdio stream).+setlocal++if "%~1"=="" (+ echo codex-attachment-manager: missing script path 1>&2+ exit /b 64+)++if defined CODEX_MCP_NODE_PATH if exist "%CODEX_MCP_NODE_PATH%" (+ "%CODEX_MCP_NODE_PATH%" %*+ exit /b+)+if defined CODEX_BROWSER_USE_NODE_PATH if exist "%CODEX_BROWSER_USE_NODE_PATH%" (+ "%CODEX_BROWSER_USE_NODE_PATH%" %*+ exit /b+)+if defined LOCALAPPDATA for /d %%D in ("%LOCALAPPDATA%\OpenAI\Codex\runtimes\cua_node\*") do if exist "%%~fD\bin\node.exe" (+ "%%~fD\bin\node.exe" %*+ exit /b+)+if defined USERPROFILE if exist "%USERPROFILE%\.cache\codex-runtimes\codex-primary-runtime\dependencies\node\bin\node.exe" (+ "%USERPROFILE%\.cache\codex-runtimes\codex-primary-runtime\dependencies\node\bin\node.exe" %*+ exit /b+)++where node >nul 2>&1+if not errorlevel 1 (+ node %*+ exit /b+)++echo codex-attachment-manager: no Node runtime found; update Codex or install Node 24 1>&2+exit /b 127diff --git a/plugin/src/cam.ts b/plugin/src/cam.tsnew file mode 100644index 0000000..33ae22f--- /dev/null+++ b/plugin/src/cam.ts@@ -0,0 +1,213 @@+// Purpose: the tool's command line. install / uninstall / status set up and remove every managed setting at once;+// list / uncheck / check / check-all work on one thread from the terminal.+// P5: install registers this repository as a plugin marketplace and installs the plugin with Codex's own command line+// (Codex copies it into its plugin cache and starts its MCP server, which keeps the engine running), checks that the+// installed copy starts, and only then points Codex at the engine. uninstall goes the other way round. Either way+// Codex is never left pointed at an engine that nothing would start.+// Input: install [--port N] | uninstall | status | list|uncheck|check|check-all <thread id> [IMG-…].+// Output: config.toml (copied to <data dir>/config-backup/ before every change), ~/.codex/.env (never copied or+// printed: it may hold credentials), the plugin cache (through Codex's command line), the selection files, and a+// summary on stdout. Rollouts are only read.++import { spawn } from "node:child_process";+import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";+import { pathToFileURL } from "node:url";+import { findCodexCli, runCodex } from "./codexcli.ts";+import { codexHome, MCP_BEGIN, noProxyStatus, persistedEnv, proxyStatus } from "./codexconfig.ts";+import { DEFAULT_PORT, engineHealth, ensureEngine } from "./engine.ts";+import { MARKETPLACE, PLUGIN, PLUGIN_ID, planInstall, planUninstall, pluginStatus, type Plan } from "./install.ts";+import { applySelection, loadPanelState, type PanelState } from "./panel-state.ts";+import { dataDir, selectionDirOf } from "./paths.ts";++type Json = Record<string, any>;+const KIND: Record<string, string> = { upload: "上传", view: "工具查看", generated: "生成", tool: "工具结果" };+// This file lives in <repository>/plugin/src; the repository root is the marketplace.+const repository = resolve(import.meta.dirname, "..", "..");+const pluginVersion = (): string => JSON.parse(readFileSync(resolve(import.meta.dirname, "..", ".codex-plugin", "plugin.json"), "utf8")).version;+export const pluginCacheDir = (version: string) => join(codexHome(), "plugins", "cache", MARKETPLACE, PLUGIN, version);++function table(state: PanelState): string {+ const rows = state.images.map((image) => [+ image.id,+ !image.replaceable ? "锁定" : image.checked ? "勾选" : "取消",+ KIND[image.kind] ?? image.kind,+ image.name ?? "—",+ image.turn ?? "—",+ image.width && image.height ? `${image.width}×${image.height}` : "—",+ `${(image.bytes / 1024).toFixed(0)} KB`,+ image.sameAs.join(",") || "—",+ image.requested ? "模型索要" : "",+ ].join(" | "));+ const mb = (bytes: number) => (bytes / 1e6).toFixed(2);+ return [+ `任务 ${state.threadId}:${state.totals.images} 张图,${state.turns} 轮;取消 ${state.totals.unchecked} 张;勾选的图共 ${mb(state.totals.checkedBytes)} MB(全部勾选时 ${mb(state.totals.allBytes)} MB)`,+ "编号 | 状态 | 来源 | 名称 | 轮次 | 尺寸 | 大小 | 内容相同 | 备注",+ ...rows,+ ].join("\n");+}++function backupConfig(configFile: string): void {+ if (!existsSync(configFile)) return;+ const backups = join(dataDir(), "config-backup");+ mkdirSync(backups, { recursive: true });+ copyFileSync(configFile, join(backups, `config.toml.${new Date().toISOString().replaceAll(":", "-")}`));+}++function applyPlan(plan: Plan, configFile: string, envFile: string): void {+ if (plan.configChanged) {+ backupConfig(configFile);+ writeFileSync(configFile, plan.configText, "utf8");+ }+ if (plan.envChanged) {+ if (plan.envText === null) rmSync(envFile, { force: true });+ else {+ writeFileSync(`${envFile}.cam-tmp`, plan.envText, "utf8");+ renameSync(`${envFile}.cam-tmp`, envFile);+ }+ }+}++// Codex may store the marketplace path with the \\?\ prefix; compare the plain paths, ignoring case on Windows.+const samePath = (a: string, b: string) => {+ const plain = (path: string) => resolve(path.replace(/^\\\\\?\\/, ""));+ return process.platform === "win32" ? plain(a).toLowerCase() === plain(b).toLowerCase() : plain(a) === plain(b);+};++function codex(cli: string, args: string[]): string {+ const { ok, output } = runCodex(cli, args);+ if (!ok) throw new Error(`codex ${args.join(" ")} 失败:${output || "没有输出"}`);+ return output;+}++// Start the installed copy the way Codex will (its launcher, its folder) and ask it for its tools and its page.+export function selfTest(dir: string, timeoutMs = 20_000): Promise<{ ok: boolean; tools: string[]; error: string | null }> {+ return new Promise((done) => {+ const scratch = mkdtempSync(join(tmpdir(), "cam-selftest-"));+ const child = spawn("cmd.exe", ["/d", "/s", "/c", "call", "./scripts/launch.cmd", "./src/plugin-server.ts"], {+ cwd: dir, windowsHide: true, stdio: ["pipe", "pipe", "pipe"],+ env: { ...process.env, CAM_NO_ENGINE: "1", CAM_DATA_DIR: scratch },+ });+ const replies = new Map<number, Json>();+ let buffer = "";+ let errors = "";+ const finish = (result: { ok: boolean; tools: string[]; error: string | null }) => {+ clearTimeout(timer);+ child.stdin.end();+ done(result);+ };+ const timer = setTimeout(() => finish({ ok: false, tools: [], error: `没有在 ${timeoutMs / 1000} 秒内响应。${errors.trim()}` }), timeoutMs);+ child.stderr.on("data", (chunk: Buffer) => { errors += chunk.toString("utf8"); });+ child.on("error", (error) => finish({ ok: false, tools: [], error: String(error) }));+ child.stdout.on("data", (chunk: Buffer) => {+ buffer += chunk.toString("utf8");+ for (let end = buffer.indexOf("\n"); end >= 0; end = buffer.indexOf("\n")) {+ const line = buffer.slice(0, end).trim();+ buffer = buffer.slice(end + 1);+ if (!line) continue;+ try { const message = JSON.parse(line); if (typeof message.id === "number") replies.set(message.id, message); } catch { /* not ours */ }+ }+ if (replies.has(3)) {+ const tools = (replies.get(2)?.result?.tools ?? []).map((tool: Json) => tool.name);+ const page = replies.get(3)?.result?.contents?.[0]?.text ?? "";+ finish(tools.includes("cam_panel") && page.includes("<title>") ? { ok: true, tools, error: null } : { ok: false, tools, error: "工具或面板页面不完整" });+ }+ });+ const send = (message: Json) => child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`);+ send({ id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "cam-install-selftest" } } });+ send({ method: "notifications/initialized" });+ send({ id: 2, method: "tools/list" });+ send({ id: 3, method: "resources/read", params: { uri: "ui://codex-attachment-manager/panel.html" } });+ });+}++// Selections made before P5 lived in the repository's local/ folder; they move along once, never overwriting.+function migrateSelections(): number {+ const legacy = join(repository, "local", "selection");+ const target = selectionDirOf();+ if (!existsSync(legacy) || resolve(legacy) === resolve(target)) return 0;+ mkdirSync(target, { recursive: true });+ let moved = 0;+ for (const name of readdirSync(legacy).filter((file) => file.endsWith(".json"))) {+ if (existsSync(join(target, name))) continue;+ copyFileSync(join(legacy, name), join(target, name));+ moved++;+ }+ return moved;+}++async function main(): Promise<void> {+ const [command, threadId, ...ids] = process.argv.slice(2);+ const configFile = join(codexHome(), "config.toml");+ const envFile = join(codexHome(), ".env");+ const readConfig = () => (existsSync(configFile) ? readFileSync(configFile, "utf8") : "");+ const readEnv = () => (existsSync(envFile) ? readFileSync(envFile, "utf8") : null);+ const port = Number(process.argv.includes("--port") ? process.argv[process.argv.indexOf("--port") + 1] : DEFAULT_PORT);++ if (command === "install") {+ if (!existsSync(join(repository, ".agents", "plugins", "marketplace.json"))) throw new Error("请在仓库里运行:node plugin/src/cam.ts install");+ const cli = findCodexCli();+ if (!cli) throw new Error("找不到 Codex 的命令行(codex.exe)。请先安装 Codex 桌面版,并至少打开过一次。");+ const env = { httpProxy: persistedEnv("HTTPS_PROXY") ?? persistedEnv("HTTP_PROXY") ?? persistedEnv("ALL_PROXY"), noProxy: persistedEnv("NO_PROXY") };+ // A conflict with the user's own settings stops everything before anything changes.+ planInstall({ configText: readConfig(), envText: readEnv(), env, port });+ backupConfig(configFile);+ const steps: string[] = [];+ const registered = pluginStatus(readConfig()).marketplace;+ if (registered && !samePath(registered, repository)) { codex(cli, ["plugin", "marketplace", "remove", MARKETPLACE]); steps.push("去掉指向别处的旧插件市场"); }+ if (!registered || !samePath(registered, repository)) { codex(cli, ["plugin", "marketplace", "add", repository]); steps.push("登记插件市场(这个仓库)"); }+ // Installed afresh every time, so Codex's copy matches this checkout.+ if (pluginStatus(readConfig()).installed) { codex(cli, ["plugin", "remove", PLUGIN_ID]); steps.push("卸掉旧的插件副本"); }+ codex(cli, ["plugin", "add", PLUGIN_ID]);+ steps.push("安装插件");+ const installed = pluginCacheDir(pluginVersion());+ const test = await selfTest(installed);+ if (!test.ok) throw new Error(`装好的插件服务没能启动:${test.error}。代理设置没有写入,Codex 仍然直连。`);+ steps.push(`自检通过:插件服务能启动,提供 ${test.tools.join("、")}`);+ const plan = planInstall({ configText: readConfig(), envText: readEnv(), env, port });+ applyPlan(plan, configFile, envFile);+ const migrated = migrateSelections();+ const engine = await ensureEngine({ port });+ console.log(JSON.stringify({ command, steps, configChanged: plan.configChanged, envChanged: plan.envChanged, notes: plan.notes, migratedSelections: migrated, dataDir: dataDir(), engine: engine.state, enginePid: engine.health?.pid ?? null, next: "重启 Codex 后生效。面板在任务右侧的侧边面板:新建标签页 → 插件和 MCP → 上下文素材" }, null, 2));+ return;+ }+ if (command === "uninstall") {+ // Codex goes back to connecting directly first; only then is the plugin that starts the engine removed.+ const plan = planUninstall({ configText: readConfig(), envText: readEnv() });+ applyPlan(plan, configFile, envFile);+ const steps = ["恢复直连:去掉代理设置" + (plan.envChanged ? "和 .env 里的 NO_PROXY" : "")];+ const cli = findCodexCli();+ const status = pluginStatus(readConfig());+ if (!cli && (status.installed || status.marketplace)) steps.push("找不到 Codex 的命令行,插件没有卸载;可以在 Codex 的插件页面里移除");+ if (cli && status.installed) { codex(cli, ["plugin", "remove", PLUGIN_ID]); steps.push("卸载插件"); }+ if (cli && status.marketplace) { codex(cli, ["plugin", "marketplace", "remove", MARKETPLACE]); steps.push("去掉插件市场"); }+ console.log(JSON.stringify({ command, steps, configChanged: plan.configChanged, envChanged: plan.envChanged, dataDir: dataDir(), next: "重启 Codex 后生效;引擎会在 Codex 全部退出后自己退出。勾选记录留在数据目录里,不需要可以删掉" }, null, 2));+ return;+ }+ if (command === "status") {+ const config = readConfig();+ const health = await engineHealth(port);+ const version = pluginVersion();+ console.log(JSON.stringify({+ command,+ proxy: proxyStatus(config),+ plugin: { ...pluginStatus(config), version, cached: existsSync(pluginCacheDir(version)) },+ legacyMcpServer: config.split(/\r?\n/).some((line) => line.trim() === MCP_BEGIN),+ dotenv: noProxyStatus(readEnv() ?? ""),+ engine: health ? { running: true, pid: health.pid, startedAt: health.startedAt } : { running: false },+ codexCli: findCodexCli(),+ dataDir: dataDir(),+ }, null, 2));+ return;+ }+ if (!command || !threadId) throw new Error("usage: cam.ts install [--port N] | uninstall | status | list|uncheck|check|check-all <thread id> [IMG-…]");+ const options = { sessionsDir: join(codexHome(), "sessions") };+ if (command === "list") console.log(table(loadPanelState(threadId, options)));+ else if (command === "uncheck") console.log(table(applySelection(threadId, { uncheck: ids }, options)));+ else if (command === "check") console.log(table(applySelection(threadId, { check: ids }, options)));+ else if (command === "check-all") console.log(table(applySelection(threadId, { checkAll: true }, options)));+ else throw new Error(`unknown command ${command}`);+}++if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) await main();diff --git a/plugin/src/codexcli.ts b/plugin/src/codexcli.tsnew file mode 100644index 0000000..66dff7d--- /dev/null+++ b/plugin/src/codexcli.ts@@ -0,0 +1,33 @@+// Purpose: P5 — find and run Codex's own command line, which registers marketplaces and installs or removes plugins+// (copying them into Codex's plugin cache). The desktop app ships one; a codex on PATH is the fallback.+// Input: CODEX_CLI_PATH, the desktop app's folder (%LOCALAPPDATA%\OpenAI\Codex\bin\<build>\codex.exe), or PATH.+// Output: the command's exit status and its combined output (Codex prints no secrets for these commands).++import { execFileSync, spawnSync } from "node:child_process";+import { existsSync, readdirSync, statSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";++export function findCodexCli(env: NodeJS.ProcessEnv = process.env): string | null {+ if (env.CODEX_CLI_PATH && existsSync(env.CODEX_CLI_PATH)) return env.CODEX_CLI_PATH;+ if (process.platform === "win32") {+ // The desktop app keeps one folder per build; the newest one belongs to the app that runs now.+ const root = join(env.LOCALAPPDATA || join(homedir(), "AppData", "Local"), "OpenAI", "Codex", "bin");+ const builds = existsSync(root) ? readdirSync(root).map((name) => join(root, name, "codex.exe")).filter((file) => existsSync(file)) : [];+ builds.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs);+ if (builds.length) return builds[0];+ }+ try {+ const found = execFileSync(process.platform === "win32" ? "where" : "which", ["codex"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });+ return found.split(/\r?\n/).map((line) => line.trim()).find(Boolean) ?? null;+ } catch {+ return null;+ }+}++export function runCodex(cli: string, args: string[]): { ok: boolean; output: string } {+ // An npm-installed codex on Windows is a .cmd shim, which only cmd.exe can start.+ const shim = /\.cmd$/i.test(cli);+ const result = spawnSync(shim ? "cmd.exe" : cli, shim ? ["/d", "/s", "/c", cli, ...args] : args, { encoding: "utf8", windowsHide: true });+ return { ok: result.status === 0, output: `${result.stdout ?? ""}${result.stderr ?? ""}`.trim() };+}diff --git a/spike/src/codexconfig.ts b/plugin/src/codexconfig.tssimilarity index 67%rename from spike/src/codexconfig.tsrename to plugin/src/codexconfig.tsindex 43aa10b..e7e0ecb 100644--- a/spike/src/codexconfig.ts+++ b/plugin/src/codexconfig.ts@@ -3,15 +3,13 @@// 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 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.+// P5 — a library only: cam.ts install / uninstall / status use it, and do every write and backup themselves.+// Input: file texts. Codex home comes from CODEX_HOME or %USERPROFILE%\.codex. Output: next texts and status.+// .env may hold credentials: it is never copied or printed, and its block is removed byte-exactly.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";+import { join } from "node:path";export const BEGIN = "# >>> codex-attachment-manager: managed proxy setting, remove it with the tool >>>";export const END = "# <<< codex-attachment-manager <<<";@@ -173,61 +171,3 @@ export function persistedEnv(name: string): string | null {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 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);- 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);- 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 === "mcp-enable") {- const name = process.argv[process.argv.indexOf("--name") + 1];- const script = resolve(process.argv[process.argv.indexOf("--script") + 1]);- if (!process.argv.includes("--name") || !process.argv.includes("--script") || !existsSync(script)) throw new Error("usage: codexconfig.ts mcp-enable --name <server> --script <path to .ts>");- const { text, changed } = enableMcpServer(current, name, process.execPath, [script]);- if (changed) write(text);- console.log(JSON.stringify({ command, changed, mcpServer: name }));- } else if (command === "mcp-disable") {- const { text, changed } = disableMcpServer(current);- if (changed) write(text);- console.log(JSON.stringify({ command, changed }));- } else if (command === "status") {- console.log(JSON.stringify({ command, configExists: existsSync(config), ...proxyStatus(current), mcpServerManaged: current.split(/\r?\n/).some((line) => line.trim() === MCP_BEGIN), ...envStatus(currentEnv) }));- } else {- throw new Error("usage: codexconfig.ts enable [--port N] | disable | mcp-enable --name <server> --script <path> | mcp-disable | status");- }-}--if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) main();diff --git a/spike/src/engine.ts b/plugin/src/engine.tssimilarity index 100%rename from spike/src/engine.tsrename to plugin/src/engine.tsdiff --git a/spike/src/images.ts b/plugin/src/images.tssimilarity index 100%rename from spike/src/images.tsrename to plugin/src/images.tsdiff --git a/spike/src/install.ts b/plugin/src/install.tssimilarity index 50%rename from spike/src/install.tsrename to plugin/src/install.tsindex 29626a0..0f3eb92 100644--- a/spike/src/install.ts+++ b/plugin/src/install.ts@@ -1,10 +1,16 @@// Purpose: P3-4 — what installing and uninstalling change, as pure functions over the current file contents:-// config.toml gets the proxy settings and the plugin's MCP server; ~/.codex/.env gets NO_PROXY only when the user's-// environment proxy would otherwise swallow requests to this machine. Uninstall removes exactly those blocks.+// config.toml gets the proxy settings; ~/.codex/.env gets NO_PROXY only when the user's environment proxy would+// otherwise swallow requests to this machine. Uninstall removes exactly those blocks.+// P5 — the MCP server now comes with the plugin, which Codex's own command line installs (see cam.ts); an MCP server+// block left by an earlier install is removed here.// Input: current texts and the user's persisted proxy variables. Output: next texts (envText null = delete the file).-import { coversLoopback, disableMcpServer, disableProxy, enableMcpServer, enableNoProxy, enableProxy, noProxyValue } from "./codexconfig.ts";+import { coversLoopback, disableMcpServer, disableProxy, enableNoProxy, enableProxy, noProxyValue } from "./codexconfig.ts";+export const PLUGIN = "codex-attachment-manager";+export const MARKETPLACE = "codex-attachment-manager";+export const PLUGIN_ID = `${PLUGIN}@${MARKETPLACE}`;+// The MCP server's name, in the plugin's .mcp.json and in config.toml blocks written before P5.export const SERVER_NAME = "codex_attachment_manager";export type UserProxyEnv = { httpProxy: string | null; noProxy: string | null };@@ -15,10 +21,11 @@ export function needsNoProxy(env: UserProxyEnv): boolean {return !!env.httpProxy && !coversLoopback(env.noProxy);}-export function planInstall(input: { configText: string; envText: string | null; env: UserProxyEnv; port: number; nodePath: string; serverScript: string }): Plan {+export function planInstall(input: { configText: string; envText: string | null; env: UserProxyEnv; port: number }): Plan {const notes: string[] = [];const proxied = enableProxy(input.configText, `http://localhost:${input.port}/backend-api/codex`);- const served = enableMcpServer(proxied.text, SERVER_NAME, input.nodePath, [input.serverScript]);+ const legacy = disableMcpServer(proxied.text);+ if (legacy.changed) notes.push("去掉旧版写进 config.toml 的插件服务:现在由插件自己提供");let envText = input.envText;let envChanged = false;if (needsNoProxy(input.env)) {@@ -32,7 +39,7 @@ export function planInstall(input: { configText: string; envText: string | null;envText = cleared.text;envChanged = cleared.changed;}- return { configText: served.text, configChanged: served.text !== input.configText, envText: emptyToNull(envText), envChanged, notes };+ return { configText: legacy.text, configChanged: legacy.text !== input.configText, envText: emptyToNull(envText), envChanged, notes };}export function planUninstall(input: { configText: string; envText: string | null }): Plan {@@ -41,6 +48,24 @@ export function planUninstall(input: { configText: string; envText: string | nulreturn { configText: config.text, configChanged: config.text !== input.configText, envText: emptyToNull(env.text), envChanged: env.changed, notes: [] };}+// What config.toml says about our marketplace and plugin (Codex writes both; we only read them).+export function pluginStatus(configText: string): { marketplace: string | null; installed: boolean; enabled: boolean } {+ const lines = configText.replace(/^/, "").split(/\r?\n/);+ const table = (header: string) => {+ const start = lines.findIndex((line) => line.trim() === header);+ if (start < 0) return null;+ const end = lines.findIndex((line, index) => index > start && /^\s*\[/.test(line));+ return lines.slice(start + 1, end < 0 ? undefined : end);+ };+ const value = (body: string[] | null, key: string) => {+ const line = body?.find((candidate) => new RegExp(`^\\s*${key}\\s*=`).test(candidate));+ return line ? line.slice(line.indexOf("=") + 1).trim().replace(/^['"]|['"]$/g, "") : null;+ };+ const marketplace = table(`[marketplaces.${MARKETPLACE}]`);+ const plugin = table(`[plugins."${PLUGIN_ID}"]`);+ return { marketplace: marketplace ? value(marketplace, "source") : null, installed: plugin !== null, enabled: plugin !== null && value(plugin, "enabled") !== "false" };+}+// A .env that held nothing but our block is removed rather than left empty.function emptyToNull(text: string | null): string | null {return text === null || !text.replace(/^/, "").trim() ? null : text;diff --git a/spike/src/panel-state.ts b/plugin/src/panel-state.tssimilarity index 100%rename from spike/src/panel-state.tsrename to plugin/src/panel-state.tsdiff --git a/spike/src/panel.html b/plugin/src/panel.htmlsimilarity index 100%rename from spike/src/panel.htmlrename to plugin/src/panel.htmldiff --git a/plugin/src/paths.ts b/plugin/src/paths.tsnew file mode 100644index 0000000..d3bab18--- /dev/null+++ b/plugin/src/paths.ts@@ -0,0 +1,19 @@+// Purpose: one place for where the tool keeps its own data (selection state, request statistics, logs, backups).+// Input: CAM_DATA_DIR when set; otherwise a per-user folder: %LOCALAPPDATA%\codex-attachment-manager on Windows,+// $XDG_DATA_HOME (or ~/.local/share)/codex-attachment-manager elsewhere. Never inside the plugin folder, which Codex+// replaces on every update, and never under ~/.codex.+// Output: absolute directory paths. Nothing here writes anything.++import { homedir } from "node:os";+import { join } from "node:path";++export function dataDir(): string {+ const chosen = process.env.CAM_DATA_DIR?.trim();+ if (chosen) return chosen;+ if (process.platform === "win32") return join(process.env.LOCALAPPDATA || join(homedir(), "AppData", "Local"), "codex-attachment-manager");+ return join(process.env.XDG_DATA_HOME || join(homedir(), ".local", "share"), "codex-attachment-manager");+}++export const selectionDirOf = (root = dataDir()) => join(root, "selection");+export const requestStatsDirOf = (root = dataDir()) => join(root, "state", "requests");+export const proxyLogDirOf = (root = dataDir()) => join(root, "proxy");diff --git a/spike/src/plugin-server.ts b/plugin/src/plugin-server.tssimilarity index 100%rename from spike/src/plugin-server.tsrename to plugin/src/plugin-server.tsdiff --git a/spike/src/png.ts b/plugin/src/png.tssimilarity index 100%rename from spike/src/png.tsrename to plugin/src/png.tsdiff --git a/spike/src/proxy.ts b/plugin/src/proxy.tssimilarity index 100%rename from spike/src/proxy.tsrename to plugin/src/proxy.tsdiff --git a/spike/src/request-stats.ts b/plugin/src/request-stats.tssimilarity index 100%rename from spike/src/request-stats.tsrename to plugin/src/request-stats.tsdiff --git a/spike/src/rewrite.ts b/plugin/src/rewrite.tssimilarity index 100%rename from spike/src/rewrite.tsrename to plugin/src/rewrite.tsdiff --git a/spike/src/selection.ts b/plugin/src/selection.tssimilarity index 100%rename from spike/src/selection.tsrename to plugin/src/selection.tsdiff --git a/spike/src/thread-index.ts b/plugin/src/thread-index.tssimilarity index 100%rename from spike/src/thread-index.tsrename to plugin/src/thread-index.tsdiff --git a/spike/src/thumbnail.ts b/plugin/src/thumbnail.tssimilarity index 100%rename from spike/src/thumbnail.tsrename to plugin/src/thumbnail.tsdiff --git a/spike/scripts/panel-dev.ts b/spike/scripts/panel-dev.tsindex 1fa0fbb..2506d14 100644--- a/spike/scripts/panel-dev.ts+++ b/spike/scripts/panel-dev.ts@@ -128,7 +128,7 @@ let extra = 0;createServer((request, response) => {const reply = (status: number, type: string, body: string) => { response.writeHead(status, { "content-type": type, "cache-control": "no-store" }); response.end(body); };if (request.method === "GET" && (request.url === "/" || request.url?.startsWith("/?"))) return reply(200, "text/html; charset=utf-8", HOST);- if (request.method === "GET" && request.url === "/panel.html") return reply(200, "text/html; charset=utf-8", readFileSync(join(here, "..", "src", "panel.html"), "utf8"));+ if (request.method === "GET" && request.url === "/panel.html") return reply(200, "text/html; charset=utf-8", readFileSync(join(here, "..", "..", "plugin", "src", "panel.html"), "utf8"));if (request.method === "POST" && request.url?.startsWith("/stats")) {writeStats(new URL(request.url, "http://x").searchParams.get("kind") ?? "normal");return reply(200, "application/json", "{}");diff --git a/spike/src/cam.ts b/spike/src/cam.tsdeleted file mode 100644index ef81615..0000000--- a/spike/src/cam.ts+++ /dev/null@@ -1,91 +0,0 @@-// Purpose: the tool's command line. P3-4: install / uninstall / status set up and remove every managed setting at-// once; list / uncheck / check / check-all stand in for the panel until P4.-// Input: install [--port N] | uninstall | status | list|uncheck|check|check-all <thread id> [IMG-…].-// Output: config.toml (copied to <data dir>/config-backup/ before every change), ~/.codex/.env (never copied or-// printed: it may hold credentials), the selection file, and a summary on stdout. Rollouts are only read.--import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";-import { join, resolve } from "node:path";-import { pathToFileURL } from "node:url";-import { codexHome, MCP_BEGIN, noProxyStatus, persistedEnv, proxyStatus } from "./codexconfig.ts";-import { DEFAULT_PORT, engineHealth, ensureEngine } from "./engine.ts";-import { planInstall, planUninstall, type Plan } from "./install.ts";-import { applySelection, loadPanelState, type PanelState } from "./panel-state.ts";-import { dataDir } from "./paths.ts";--const KIND: Record<string, string> = { upload: "上传", view: "工具查看", generated: "生成", tool: "工具结果" };--function table(state: PanelState): string {- const rows = state.images.map((image) => [- image.id,- !image.replaceable ? "锁定" : image.checked ? "勾选" : "取消",- KIND[image.kind] ?? image.kind,- image.name ?? "—",- image.turn ?? "—",- image.width && image.height ? `${image.width}×${image.height}` : "—",- `${(image.bytes / 1024).toFixed(0)} KB`,- image.sameAs.join(",") || "—",- image.requested ? "模型索要" : "",- ].join(" | "));- const mb = (bytes: number) => (bytes / 1e6).toFixed(2);- return [- `任务 ${state.threadId}:${state.totals.images} 张图,${state.turns} 轮;取消 ${state.totals.unchecked} 张;勾选的图共 ${mb(state.totals.checkedBytes)} MB(全部勾选时 ${mb(state.totals.allBytes)} MB)`,- "编号 | 状态 | 来源 | 名称 | 轮次 | 尺寸 | 大小 | 内容相同 | 备注",- ...rows,- ].join("\n");-}--function applyPlan(plan: Plan, configFile: string, envFile: string): void {- if (plan.configChanged) {- const backups = join(dataDir(), "config-backup");- mkdirSync(backups, { recursive: true });- if (existsSync(configFile)) copyFileSync(configFile, join(backups, `config.toml.${new Date().toISOString().replaceAll(":", "-")}`));- writeFileSync(configFile, plan.configText, "utf8");- }- if (plan.envChanged) {- if (plan.envText === null) rmSync(envFile, { force: true });- else {- writeFileSync(`${envFile}.cam-tmp`, plan.envText, "utf8");- renameSync(`${envFile}.cam-tmp`, envFile);- }- }-}--async function main(): Promise<void> {- const [command, threadId, ...ids] = process.argv.slice(2);- const configFile = join(codexHome(), "config.toml");- const envFile = join(codexHome(), ".env");- const readConfig = () => (existsSync(configFile) ? readFileSync(configFile, "utf8") : "");- const readEnv = () => (existsSync(envFile) ? readFileSync(envFile, "utf8") : null);- const port = Number(process.argv.includes("--port") ? process.argv[process.argv.indexOf("--port") + 1] : DEFAULT_PORT);-- if (command === "install") {- const env = { httpProxy: persistedEnv("HTTPS_PROXY") ?? persistedEnv("HTTP_PROXY") ?? persistedEnv("ALL_PROXY"), noProxy: persistedEnv("NO_PROXY") };- const plan = planInstall({ configText: readConfig(), envText: readEnv(), env, port, nodePath: process.execPath, serverScript: resolve(import.meta.dirname, "plugin-server.ts") });- applyPlan(plan, configFile, envFile);- const engine = await ensureEngine({ port });- console.log(JSON.stringify({ command, configChanged: plan.configChanged, envChanged: plan.envChanged, notes: plan.notes, engine: engine.state, enginePid: engine.health?.pid ?? null, next: "重启 Codex 后生效" }, null, 2));- return;- }- if (command === "uninstall") {- const plan = planUninstall({ configText: readConfig(), envText: readEnv() });- applyPlan(plan, configFile, envFile);- console.log(JSON.stringify({ command, configChanged: plan.configChanged, envChanged: plan.envChanged, next: "重启 Codex 后生效;引擎会在 Codex 全部退出后自己退出" }, null, 2));- return;- }- if (command === "status") {- const config = readConfig();- const health = await engineHealth(port);- console.log(JSON.stringify({ command, proxy: proxyStatus(config), mcpServer: config.split(/\r?\n/).some((line) => line.trim() === MCP_BEGIN), dotenv: noProxyStatus(readEnv() ?? ""), engine: health ? { running: true, pid: health.pid, startedAt: health.startedAt } : { running: false }, dataDir: dataDir() }, null, 2));- return;- }- if (!command || !threadId) throw new Error("usage: cam.ts install [--port N] | uninstall | status | list|uncheck|check|check-all <thread id> [IMG-…]");- const options = { sessionsDir: join(codexHome(), "sessions") };- if (command === "list") console.log(table(loadPanelState(threadId, options)));- else if (command === "uncheck") console.log(table(applySelection(threadId, { uncheck: ids }, options)));- else if (command === "check") console.log(table(applySelection(threadId, { check: ids }, options)));- else if (command === "check-all") console.log(table(applySelection(threadId, { checkAll: true }, options)));- else throw new Error(`unknown command ${command}`);-}--if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) await main();diff --git a/spike/src/codexconfig.test.ts b/spike/src/codexconfig.test.tsindex e8c5531..5a8e5e0 100644--- a/spike/src/codexconfig.test.ts+++ b/spike/src/codexconfig.test.ts@@ -4,7 +4,7 @@import assert from "node:assert/strict";import test from "node:test";-import { coversLoopback, disableMcpServer, disableProxy, enableMcpServer, enableNoProxy, enableProxy, noProxyStatus, noProxyValue, proxyStatus } from "./codexconfig.ts";+import { coversLoopback, disableMcpServer, disableProxy, enableMcpServer, enableNoProxy, enableProxy, noProxyStatus, noProxyValue, proxyStatus } from "../../plugin/src/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';diff --git a/spike/src/engine.test.ts b/spike/src/engine.test.tsindex c41dfd2..bf895a0 100644--- a/spike/src/engine.test.ts+++ b/spike/src/engine.test.ts@@ -10,8 +10,8 @@ import { tmpdir } from "node:os";import { dirname, join } from "node:path";import test from "node:test";import { fileURLToPath } from "node:url";-import { countCodexProcesses, engineHealth, ensureEngine, isEngineHealth, watchForCodex } from "./engine.ts";-import { readRequestStats, recordRequest } from "./request-stats.ts";+import { countCodexProcesses, engineHealth, ensureEngine, isEngineHealth, watchForCodex } from "../../plugin/src/engine.ts";+import { readRequestStats, recordRequest } from "../../plugin/src/request-stats.ts";const here = dirname(fileURLToPath(import.meta.url));@@ -50,7 +50,7 @@ test("ensure starts one engine; a second start on the same port leaves it alone"t.after(() => { try { process.kill(first.health!.pid); } catch { /* already gone */ } });const again = await ensureEngine({ port });assert.deepEqual([again.state, again.health?.pid], ["running", first.health!.pid]);- const second = await new Promise<string>((resolve) => execFile(process.execPath, [join(here, "proxy.ts"), "--port", String(port), "--stay"], (_error, stdout) => resolve(stdout)));+ const second = await new Promise<string>((resolve) => execFile(process.execPath, [join(here, "..", "..", "plugin", "src", "proxy.ts"), "--port", String(port), "--stay"], (_error, stdout) => resolve(stdout)));assert.match(second, /"alreadyRunning":true/);assert.equal((await engineHealth(port))?.pid, first.health!.pid);});diff --git a/spike/src/images.test.ts b/spike/src/images.test.tsindex 40a6c89..77d8b8f 100644--- a/spike/src/images.test.ts+++ b/spike/src/images.test.ts@@ -3,7 +3,7 @@import assert from "node:assert/strict";import test from "node:test";-import { findImages, imageSize } from "./images.ts";+import { findImages, imageSize } from "../../plugin/src/images.ts";import { png } from "./testkit.ts";const url = (bytes: Buffer) => `data:image/png;base64,${bytes.toString("base64")}`;diff --git a/spike/src/index.ts b/spike/src/index.tsindex b1b53ad..dba70a8 100644--- a/spike/src/index.ts+++ b/spike/src/index.ts@@ -6,7 +6,7 @@ import { createReadStream, existsSync, mkdirSync, readdirSync, realpathSync, staimport { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";import { createInterface } from "node:readline";import { fileURLToPath } from "node:url";-import { decodePng } from "./png.ts";+import { decodePng } from "../../plugin/src/png.ts";import { fileSha256, pathForViewedImage } from "./viewpaths.ts";type Json = Record<string, any>;diff --git a/spike/src/install.test.ts b/spike/src/install.test.tsindex 1c453a7..6aed2a1 100644--- a/spike/src/install.test.ts+++ b/spike/src/install.test.ts@@ -1,13 +1,16 @@// Purpose: P3-4 — installing writes every managed block (and .env only when needed); uninstalling restores both// files byte for byte; a conflict leaves everything untouched.+// P5 — the MCP server comes with the plugin: installing writes no server block and removes one an earlier install+// left; the plugin's own entries in config.toml (written by Codex) are read correctly.// Input: synthetic config and .env texts; output: Node test assertions only.import assert from "node:assert/strict";import test from "node:test";-import { needsNoProxy, planInstall, planUninstall, SERVER_NAME } from "./install.ts";+import { enableMcpServer } from "../../plugin/src/codexconfig.ts";+import { needsNoProxy, planInstall, planUninstall, pluginStatus, SERVER_NAME } from "../../plugin/src/install.ts";const CONFIG = 'model = "gpt-6-sol"\n\n[features]\nview_image = true\n\n[projects.\'d:\\\\work\']\ntrust_level = "trusted"\n';-const base = { port: 17891, nodePath: "C:\\Program Files\\nodejs\\node.exe", serverScript: "D:\\cam\\plugin-server.ts" };+const base = { port: 17891 };const proxied = { httpProxy: "http://127.0.0.1:8888", noProxy: null };const direct = { httpProxy: null, noProxy: null };@@ -18,19 +21,27 @@ test(".env is needed only when an environment proxy would swallow loopback requeassert.equal(needsNoProxy({ httpProxy: "http://p:1", noProxy: "*" }), false);});-test("install writes the proxy settings, the MCP server and, with an environment proxy, .env", () => {+test("install writes the proxy settings and, with an environment proxy, .env; the plugin brings the MCP server", () => {const plan = planInstall({ ...base, configText: CONFIG, envText: null, env: proxied });assert.equal(plan.configChanged, true);assert.match(plan.configText, /^# >>> codex-attachment-manager: managed proxy setting/);assert.match(plan.configText, /openai_base_url = "http:\/\/localhost:17891\/backend-api\/codex"/);assert.match(plan.configText, /respect_system_proxy = true/);- assert.match(plan.configText, new RegExp(`\\[mcp_servers\\.${SERVER_NAME}\\]`));+ assert.doesNotMatch(plan.configText, /\[mcp_servers\./);assert.equal(plan.envChanged, true);assert.match(plan.envText!, /NO_PROXY=localhost,127\.0\.0\.1,::1/);const again = planInstall({ ...base, configText: plan.configText, envText: plan.envText, env: proxied });assert.deepEqual([again.configChanged, again.envChanged], [false, false], "installing twice changes nothing");});+test("an MCP server block from an install before the plugin is removed", () => {+ const legacy = enableMcpServer(CONFIG, SERVER_NAME, "C:\\node.exe", ["D:\\cam\\plugin-server.ts"]).text;+ const plan = planInstall({ ...base, configText: legacy, envText: null, env: direct });+ assert.doesNotMatch(plan.configText, new RegExp(`\\[mcp_servers\\.${SERVER_NAME}\\]`));+ assert.ok(plan.notes.some((note) => note.includes("旧版")));+ assert.equal(planUninstall({ configText: plan.configText, envText: null }).configText, CONFIG);+});+test("without an environment proxy no .env is written, and an old block is cleared", () => {const plan = planInstall({ ...base, configText: CONFIG, envText: null, env: direct });assert.deepEqual([plan.envText, plan.envChanged], [null, false]);@@ -52,3 +63,10 @@ test("a conflict stops the whole install before anything is written", () => {assert.throws(() => planInstall({ ...base, configText: mine, envText: null, env: proxied }), /already sets openai_base_url/);assert.throws(() => planInstall({ ...base, configText: CONFIG, envText: "NO_PROXY=corp\n", env: proxied }), /already sets NO_PROXY/);});++test("the plugin's marketplace and install state are read from what Codex wrote", () => {+ assert.deepEqual(pluginStatus(CONFIG), { marketplace: null, installed: false, enabled: false });+ const written = CONFIG + '\n[marketplaces.codex-attachment-manager]\nsource_type = "local"\nsource = \'\\\\?\\D:\\repos\\cam\'\n\n[plugins."codex-attachment-manager@codex-attachment-manager"]\nenabled = true\n';+ assert.deepEqual(pluginStatus(written), { marketplace: "\\\\?\\D:\\repos\\cam", installed: true, enabled: true });+ assert.equal(pluginStatus(written.replace("enabled = true", "enabled = false")).enabled, false);+});diff --git a/spike/src/match.ts b/spike/src/match.tsindex a5f486d..ece4030 100644--- a/spike/src/match.ts+++ b/spike/src/match.ts@@ -7,7 +7,7 @@ import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, staimport { basename, dirname, extname, join, resolve } from "node:path";import { createInterface } from "node:readline";import { fileURLToPath } from "node:url";-import { decodePng, type DecodedPng } from "./png.ts";+import { decodePng, type DecodedPng } from "../../plugin/src/png.ts";type Json = Record<string, any>;const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../..");diff --git a/spike/src/p2-bench.ts b/spike/src/p2-bench.tsindex d04e984..3538b18 100644--- a/spike/src/p2-bench.ts+++ b/spike/src/p2-bench.ts@@ -8,13 +8,13 @@ import { tmpdir } from "node:os";import { dirname, join, resolve } from "node:path";import { fileURLToPath } from "node:url";import zlib from "node:zlib";-import { codexHome } from "./codexconfig.ts";-import { findImages } from "./images.ts";-import { decodePng } from "./png.ts";-import { hasUnsafeInteger, rewriteBody } from "./proxy.ts";-import { rewriteItems } from "./rewrite.ts";-import { writeSelection } from "./selection.ts";-import { imageData, loadThreadIndex, readThreadHistory } from "./thread-index.ts";+import { codexHome } from "../../plugin/src/codexconfig.ts";+import { findImages } from "../../plugin/src/images.ts";+import { decodePng } from "../../plugin/src/png.ts";+import { hasUnsafeInteger, rewriteBody } from "../../plugin/src/proxy.ts";+import { rewriteItems } from "../../plugin/src/rewrite.ts";+import { writeSelection } from "../../plugin/src/selection.ts";+import { imageData, loadThreadIndex, readThreadHistory } from "../../plugin/src/thread-index.ts";type Json = Record<string, any>;const localRoot = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");diff --git a/spike/src/p2-selftest.ts b/spike/src/p2-selftest.tsindex eb5a741..962a5f0 100644--- a/spike/src/p2-selftest.ts+++ b/spike/src/p2-selftest.ts@@ -10,10 +10,10 @@ import { dirname, join, resolve } from "node:path";import { setTimeout as sleep } from "node:timers/promises";import { fileURLToPath } from "node:url";import { AppServer, findBundledCodex } from "./appserver.ts";-import { codexHome } from "./codexconfig.ts";-import { readSelection, writeSelection } from "./selection.ts";+import { codexHome } from "../../plugin/src/codexconfig.ts";+import { readSelection, writeSelection } from "../../plugin/src/selection.ts";import { runTurn, TEST_MODEL, testImages, text } from "./testkit.ts";-import { loadThreadIndex } from "./thread-index.ts";+import { loadThreadIndex } from "../../plugin/src/thread-index.ts";type Json = Record<string, any>;const localRoot = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");diff --git a/spike/src/p3-lifecycle.ts b/spike/src/p3-lifecycle.tsindex ec59512..647fd68 100644--- a/spike/src/p3-lifecycle.ts+++ b/spike/src/p3-lifecycle.ts@@ -8,9 +8,9 @@ import { dirname, join } from "node:path";import { setTimeout as sleep } from "node:timers/promises";import { fileURLToPath } from "node:url";import { AppServer, findBundledCodex } from "./appserver.ts";-import { engineHealth } from "./engine.ts";-import { SERVER_NAME } from "./install.ts";-import { dataDir } from "./paths.ts";+import { engineHealth } from "../../plugin/src/engine.ts";+import { SERVER_NAME } from "../../plugin/src/install.ts";+import { dataDir } from "../../plugin/src/paths.ts";import { TEST_MODEL } from "./testkit.ts";type Json = Record<string, any>;@@ -33,7 +33,7 @@ async function main(): Promise<void> {const startedAt = new Date().toISOString();const server = new AppServer(findBundledCodex(), ["-c", `mcp_servers.${SERVER_NAME}.command=${JSON.stringify(process.execPath)}`,- "-c", `mcp_servers.${SERVER_NAME}.args=${JSON.stringify([join(here, "plugin-server.ts")])}`,+ "-c", `mcp_servers.${SERVER_NAME}.args=${JSON.stringify([join(here, "..", "..", "plugin", "src", "plugin-server.ts")])}`,], { NO_PROXY: undefined, no_proxy: undefined }, join(dataDir(), "logs", `p3-lifecycle-${startedAt.replaceAll(":", "-")}.log`));try {await server.initialize();diff --git a/spike/src/p3-selftest.ts b/spike/src/p3-selftest.tsindex 7f2f337..b5fda0e 100644--- a/spike/src/p3-selftest.ts+++ b/spike/src/p3-selftest.ts@@ -9,11 +9,11 @@ import { dirname, join, resolve } from "node:path";import { setTimeout as sleep } from "node:timers/promises";import { fileURLToPath } from "node:url";import { AppServer, findBundledCodex } from "./appserver.ts";-import { codexHome } from "./codexconfig.ts";-import { DEFAULT_PORT, engineHealth } from "./engine.ts";-import { SERVER_NAME } from "./install.ts";-import { applySelection } from "./panel-state.ts";-import { dataDir, proxyLogDirOf, requestStatsDirOf } from "./paths.ts";+import { codexHome } from "../../plugin/src/codexconfig.ts";+import { DEFAULT_PORT, engineHealth } from "../../plugin/src/engine.ts";+import { SERVER_NAME } from "../../plugin/src/install.ts";+import { applySelection } from "../../plugin/src/panel-state.ts";+import { dataDir, proxyLogDirOf, requestStatsDirOf } from "../../plugin/src/paths.ts";import { runTurn, TEST_MODEL, testImages, text } from "./testkit.ts";type Json = Record<string, any>;@@ -61,7 +61,7 @@ async function main(): Promise<void> {"-c", `openai_base_url="http://localhost:${DEFAULT_PORT}/backend-api/codex"`,"-c", "features.respect_system_proxy=true","-c", `mcp_servers.${SERVER_NAME}.command=${JSON.stringify(process.execPath)}`,- "-c", `mcp_servers.${SERVER_NAME}.args=${JSON.stringify([join(here, "plugin-server.ts")])}`,+ "-c", `mcp_servers.${SERVER_NAME}.args=${JSON.stringify([join(here, "..", "..", "plugin", "src", "plugin-server.ts")])}`,"-c", `mcp_servers.${SERVER_NAME}.default_tools_approval_mode="approve"`,], { NO_PROXY: undefined, no_proxy: undefined }, join(dataDir(), "logs", `p3-selftest-${label}-${startedAt.replaceAll(":", "-")}.log`));const threads: Json = {};diff --git a/spike/src/panel-state.test.ts b/spike/src/panel-state.test.tsindex 6a758b6..7c2bcd1 100644--- a/spike/src/panel-state.test.ts+++ b/spike/src/panel-state.test.ts@@ -4,12 +4,12 @@import assert from "node:assert/strict";import test from "node:test";-import { decodePng } from "./png.ts";-import { applySelection, imageFor, loadPanelState, requestedIds, sendInfo } from "./panel-state.ts";-import { requestStatsDirOf } from "./paths.ts";-import { recordRequest } from "./request-stats.ts";+import { decodePng } from "../../plugin/src/png.ts";+import { applySelection, imageFor, loadPanelState, requestedIds, sendInfo } from "../../plugin/src/panel-state.ts";+import { requestStatsDirOf } from "../../plugin/src/paths.ts";+import { recordRequest } from "../../plugin/src/request-stats.ts";import { assistant, line, red, sampleSessions, THREAD, turn } from "./testfixtures.ts";-import { shrink } from "./thumbnail.ts";+import { shrink } from "../../plugin/src/thumbnail.ts";const records = (text: string) => text.trim().split("\n").map((raw) => JSON.parse(raw));diff --git a/spike/src/paths.ts b/spike/src/paths.tsdeleted file mode 100644index f99bd6d..0000000--- a/spike/src/paths.ts+++ /dev/null@@ -1,14 +0,0 @@-// Purpose: one place for where the tool keeps its own data (selection state, request statistics, logs).-// Input: CAM_DATA_DIR when set; otherwise the repository's git-ignored local/ folder (spike phase).-// Output: absolute directory paths. Nothing here writes to ~/.codex.--import { dirname, join, resolve } from "node:path";-import { fileURLToPath } from "node:url";--export function dataDir(): string {- return process.env.CAM_DATA_DIR?.trim() || join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");-}--export const selectionDirOf = (root = dataDir()) => join(root, "selection");-export const requestStatsDirOf = (root = dataDir()) => join(root, "state", "requests");-export const proxyLogDirOf = (root = dataDir()) => join(root, "proxy");diff --git a/spike/src/plugin-server.test.ts b/spike/src/plugin-server.test.tsindex 6f2ba82..3b1f93f 100644--- a/spike/src/plugin-server.test.ts+++ b/spike/src/plugin-server.test.ts@@ -8,7 +8,7 @@ import { spawn } from "node:child_process";import { dirname, join } from "node:path";import test from "node:test";import { fileURLToPath } from "node:url";-import { callTool, fromModel, PANEL_MIME, PANEL_URI, readResource, threadOf, TOOLS } from "./plugin-server.ts";+import { callTool, fromModel, PANEL_MIME, PANEL_URI, readResource, threadOf, TOOLS } from "../../plugin/src/plugin-server.ts";import { sampleSessions, THREAD } from "./testfixtures.ts";const here = dirname(fileURLToPath(import.meta.url));@@ -62,7 +62,7 @@ test("image data stays in _meta, out of the model-visible content", () => {test("a stdio session lists the tools and answers calls", async () => {const { sessionsDir, dataRoot } = sampleSessions();- const child = spawn(process.execPath, [join(here, "plugin-server.ts")], { env: { ...process.env, CAM_NO_ENGINE: "1", CAM_DATA_DIR: dataRoot, CODEX_HOME: dirname(sessionsDir) }, stdio: ["pipe", "pipe", "inherit"] });+ const child = spawn(process.execPath, [join(here, "..", "..", "plugin", "src", "plugin-server.ts")], { env: { ...process.env, CAM_NO_ENGINE: "1", CAM_DATA_DIR: dataRoot, CODEX_HOME: dirname(sessionsDir) }, stdio: ["pipe", "pipe", "inherit"] });const replies: Record<number, any> = {};let buffer = "";child.stdout.on("data", (chunk: Buffer) => {diff --git a/spike/src/png.test.ts b/spike/src/png.test.tsindex 850a32d..c2e54af 100644--- a/spike/src/png.test.ts+++ b/spike/src/png.test.ts@@ -5,7 +5,7 @@ import assert from "node:assert/strict";import { createHash } from "node:crypto";import test from "node:test";import { deflateSync } from "node:zlib";-import { decodePng } from "./png.ts";+import { decodePng } from "../../plugin/src/png.ts";function chunk(type: string, data: Buffer): Buffer {const length = Buffer.alloc(4);diff --git a/spike/src/proxy.test.ts b/spike/src/proxy.test.tsindex 72a9013..7e89679 100644--- a/spike/src/proxy.test.ts+++ b/spike/src/proxy.test.ts@@ -8,8 +8,8 @@ import { tmpdir } from "node:os";import { join } from "node:path";import test from "node:test";import zlib from "node:zlib";-import { describeBody, hasUnchecked, hasUnsafeInteger, imageSizesOf, outboundProxy, rewriteBody, requestIdentity } from "./proxy.ts";-import { writeSelection } from "./selection.ts";+import { describeBody, hasUnchecked, hasUnsafeInteger, imageSizesOf, outboundProxy, rewriteBody, requestIdentity } from "../../plugin/src/proxy.ts";+import { writeSelection } from "../../plugin/src/selection.ts";import { png } from "./testkit.ts";const none = () => null;diff --git a/spike/src/rebuild.ts b/spike/src/rebuild.tsindex d1aaab4..18d3f74 100644--- a/spike/src/rebuild.ts+++ b/spike/src/rebuild.ts@@ -13,7 +13,7 @@ import { dirname, join, resolve } from "node:path";import { fileURLToPath } from "node:url";import { AppServer, findBundledCodex, type Notification } from "./appserver.ts";import { baseName, buildMigration, type AssetInfo } from "./migrate.ts";-import { decodePng } from "./png.ts";+import { decodePng } from "../../plugin/src/png.ts";type Json = Record<string, any>;const localRoot = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");diff --git a/spike/src/rewrite.test.ts b/spike/src/rewrite.test.tsindex d4bc2c7..e2b95c2 100644--- a/spike/src/rewrite.test.ts+++ b/spike/src/rewrite.test.ts@@ -3,8 +3,8 @@import assert from "node:assert/strict";import test from "node:test";-import { findImages, type ImageRef } from "./images.ts";-import { rewriteItems, type Described } from "./rewrite.ts";+import { findImages, type ImageRef } from "../../plugin/src/images.ts";+import { rewriteItems, type Described } from "../../plugin/src/rewrite.ts";import { png } from "./testkit.ts";const url = (bytes: Buffer) => `data:image/png;base64,${bytes.toString("base64")}`;diff --git a/spike/src/selection.test.ts b/spike/src/selection.test.tsindex 327c76e..fab2249 100644--- a/spike/src/selection.test.ts+++ b/spike/src/selection.test.ts@@ -7,8 +7,8 @@ import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import test from "node:test";-import { hasUnchecked } from "./proxy.ts";-import { effectiveSelection, readSelection, writeSelection } from "./selection.ts";+import { hasUnchecked } from "../../plugin/src/proxy.ts";+import { effectiveSelection, readSelection, writeSelection } from "../../plugin/src/selection.ts";const PARENT = "01a0d301-0000-7000-8000-0000000000f0";const FORK = "01a0d301-0000-7000-8000-0000000000f1";diff --git a/spike/src/thread-index.test.ts b/spike/src/thread-index.test.tsindex 4f97ee4..1698521 100644--- a/spike/src/thread-index.test.ts+++ b/spike/src/thread-index.test.ts@@ -7,7 +7,7 @@ import { appendFileSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import test from "node:test";-import { loadThreadIndex } from "./thread-index.ts";+import { loadThreadIndex } from "../../plugin/src/thread-index.ts";import { png } from "./testkit.ts";const THREAD = "01a0d301-0000-7000-8000-000000000001";