Stop paying the multimodal tax. Your AI agent keeps every image it has seen but only sends the ones it needs: lighter chats, no endless reconnecting, no starting over. Works with Codex, Claude Code, Cline, Gemini CLI, OpenCode, WorkBuddy and more. Install once, forget it.
TypeScript ai-agentsai-imageclaude-codeclaude-code-pluginclinecodexcodex-plugincomputer-usecontext-engineeringcontext-managementdeveloper-toolsgemini-cliimage-generationmcpmultimodalmultimodal-aiopencodeqwen-codetoken-optimizationvision-language-model
feat(install): 不开终端也能装——面板的启用、停用,一行命令安装、卸载(v0.1-5)
chipfighter7f01b81a1a3f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 2709eb9..d2b9bdc 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -39,3 +39,6 @@ jobs:run: npm install --global @openai/codex- name: Plugin smoke testrun: node spike/src/plugin-smoke.ts+ # The one-line install and uninstall scripts of this platform, against a throwaway Codex home.+ - name: Install script smoke test+ run: node spike/src/scripts-smoke.tsdiff --git a/plugin/src/cam.ts b/plugin/src/cam.tsindex 6020d3c..d2513c3 100644--- a/plugin/src/cam.ts+++ b/plugin/src/cam.ts@@ -4,22 +4,25 @@// (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-…].+// v0.1-5: setup, run from the copy Codex installed (the install scripts do this after Codex's own command line added+// the plugin), points Codex at the engine and starts it. The settings themselves are switched in setup.ts.+// Input: install [--port N] | setup [--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 { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync } from "node:fs";import { tmpdir } from "node:os";import { join, resolve } from "node:path";import { findCodexCli, runCodex } from "./codexcli.ts";-import { codexHome, MCP_BEGIN, noProxyStatus, persistedEnv, proxyStatus } from "./codexconfig.ts";+import { codexHome, MCP_BEGIN, noProxyStatus, proxyStatus } from "./codexconfig.ts";import { buildOf, DEFAULT_PORT, engineHealth, ensureEngine } from "./engine.ts";import { isEntryPoint } from "./entry.ts";-import { MARKETPLACE, PLUGIN, PLUGIN_ID, planInstall, planUninstall, pluginStatus, type Plan } from "./install.ts";+import { MARKETPLACE, PLUGIN, PLUGIN_ID, planInstall, pluginStatus } from "./install.ts";import { applySelection, loadPanelState, type PanelState } from "./panel-state.ts";import { dataDir, selectionDirOf } from "./paths.ts";+import { backupConfig, connectDirectly, readConfig, readEnv, useEngine, userProxyEnv } from "./setup.ts";type Json = Record<string, any>;const KIND: Record<string, string> = { upload: "上传", view: "工具查看", generated: "生成", tool: "工具结果" };@@ -48,27 +51,6 @@ function table(state: PanelState): string {].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(/^\\\\\?\\/, ""));@@ -145,20 +127,16 @@ function migrateSelections(): number {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);+ // The same port the plugin's MCP server uses: --port, else CAM_ENGINE_PORT, else the default.+ const port = Number(process.argv.includes("--port") ? process.argv[process.argv.indexOf("--port") + 1] : process.env.CAM_ENGINE_PORT ?? 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 桌面版并至少打开过一次,或者安装 Codex 命令行;也可以用环境变量 CODEX_CLI_PATH 指定它的位置。");- 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);+ planInstall({ configText: readConfig(), envText: readEnv(), env: userProxyEnv(), port });+ backupConfig();const steps: string[] = [];const registered = pluginStatus(readConfig()).marketplace;if (registered && !samePath(registered, repository)) { codex(cli, ["plugin", "marketplace", "remove", MARKETPLACE]); steps.push("去掉指向别处的旧插件市场"); }@@ -171,18 +149,25 @@ async function main(): Promise<void> {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 plan = useEngine(port);const migrated = migrateSelections();// The installed copy runs the engine, as it will when Codex starts it; an older engine still running is replaced.const engine = await ensureEngine({ port, dir: join(installed, "src") });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 === "setup") {+ // Only once Codex has the plugin: otherwise nothing would start the engine after Codex restarts.+ if (!pluginStatus(readConfig()).installed || !existsSync(pluginCacheDir(pluginVersion()))) throw new Error("插件还没有装进 Codex:请先安装插件,再运行 setup。");+ const plan = useEngine(port);+ // Started from this copy, which is the installed one when the install scripts run it.+ const engine = await ensureEngine({ port });+ console.log(JSON.stringify({ command, configChanged: plan.configChanged, envChanged: plan.envChanged, notes: plan.notes, 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 plan = connectDirectly();const steps = ["恢复直连:去掉代理设置" + (plan.envChanged ? "和 .env 里的 NO_PROXY" : "")];const cli = findCodexCli();const status = pluginStatus(readConfig());@@ -208,7 +193,7 @@ async function main(): Promise<void> {}, 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-…]");+ if (!command || !threadId) throw new Error("usage: cam.ts install [--port N] | setup [--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)));diff --git a/plugin/src/engine.ts b/plugin/src/engine.tsindex f8fb826..ca1f8b1 100644--- a/plugin/src/engine.ts+++ b/plugin/src/engine.ts@@ -9,6 +9,7 @@import { execFile, spawn } from "node:child_process";import { createHash } from "node:crypto";import { readdirSync, readFileSync } from "node:fs";+import { tmpdir } from "node:os";import { dirname, join, posix } from "node:path";import { fileURLToPath } from "node:url";@@ -75,9 +76,11 @@ export function shouldReplace(running: Health, own: { build: string | null; versreturn compareVersions(own.version ?? "0.0.0", running.version ?? "0.0.0") >= 0;}-// Detached and hidden, so it outlives whoever asked for it (a plugin server instance, the CLI).+// Detached and hidden, so it outlives whoever asked for it (a plugin server instance, the CLI). Its working folder is+// not the plugin's: Windows will not delete a folder a running process works in, and Codex replaces the plugin's+// folder on every update and removes it on uninstall.export function spawnEngine(port = DEFAULT_PORT, extraArgs: string[] = [], dir = here): number | undefined {- const child = spawn(process.execPath, [join(dir, "proxy.ts"), "--port", String(port), ...extraArgs], { detached: true, stdio: "ignore", windowsHide: true });+ const child = spawn(process.execPath, [join(dir, "proxy.ts"), "--port", String(port), ...extraArgs], { cwd: tmpdir(), detached: true, stdio: "ignore", windowsHide: true });child.unref();return child.pid;}diff --git a/plugin/src/panel.html b/plugin/src/panel.htmlindex 8036241..bffde5b 100644--- a/plugin/src/panel.html+++ b/plugin/src/panel.html@@ -9,6 +9,7 @@images in history order; the user previews them, checks or unchecks them, and confirms. Nothing is sent to the model.Input: the MCP Apps bridge (postMessage) — Codex's call of cam_panel, and our own calls of cam_panel, cam_image andcam_set_selection. Output: selection changes through cam_set_selection. Self-contained: no network, no storage.+ v0.1-5 — 启用 / 停用 (cam_setup): point Codex at the engine, or back to a direct connection before uninstalling.--><style>/* Fallbacks follow Codex's own widget palette; inside Codex its theme variables (MCP Apps host styles) win. */@@ -56,6 +57,8 @@.title h1 { margin: 0; font-size: 15px; font-weight: 600; letter-spacing: .01em; }.count { padding: 0 7px; border-radius: 999px; background: var(--bg-soft); color: var(--text-2); font-size: 12px; font-weight: 500; line-height: 20px; font-variant-numeric: tabular-nums; }.count:empty { display: none; }+ .quiet { margin-left: auto; height: 24px; padding: 0 10px; border: 0; border-radius: 999px; background: transparent; color: var(--text-3); font-size: 12px; cursor: pointer; transition: background .15s, color .15s; }+ .quiet:hover { background: var(--bg-soft); color: var(--text-2); }.plan { margin-top: 4px; color: var(--text-2); font-size: 12.5px; font-variant-numeric: tabular-nums; }.plan b { font-weight: 600; color: var(--text); }.meter { margin-top: 12px; padding: 10px 12px 11px; border-radius: 12px; background: var(--bg-soft); }@@ -121,8 +124,14 @@.notice { margin: 12px 8px 0; padding: 9px 12px; border-radius: 10px; font-size: 12.5px; display: flex; gap: 10px; align-items: flex-start; }.notice.warn { background: var(--warn-bg); color: var(--warn); }.notice.error { background: var(--danger-bg); color: var(--danger); }+ .notice.info { background: var(--info-bg); color: var(--text); }+ .notice.cta { align-items: center; }.notice .grow { flex: 1; }- .notice button { border: 0; background: none; padding: 0; font-weight: 600; cursor: pointer; color: inherit; font-size: 12.5px; }+ .notice button { flex: none; border: 0; background: none; padding: 0; font-weight: 600; cursor: pointer; color: inherit; font-size: 12.5px; }+ .notice button.primary { height: 26px; padding: 0 12px; border-radius: 999px; background: var(--accent); color: var(--accent-text); transition: background .15s, transform .1s; }+ .notice button.primary:hover { background: color-mix(in srgb, var(--accent) 84%, var(--bg)); }+ .notice button.primary:active:not(:disabled) { transform: scale(.97); }+ .notice button:disabled { opacity: .5; cursor: default; }.empty { height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; padding: 24px; text-align: center; color: var(--text-3); }.empty svg { width: 36px; height: 36px; margin-bottom: 6px; }@@ -165,7 +174,7 @@</head><body><header>- <div class="title"><h1>图片</h1><span class="count" id="count"></span></div>+ <div class="title"><h1>图片</h1><span class="count" id="count"></span><button class="quiet" id="disable" type="button" hidden>停用</button></div><div class="plan" id="plan">正在读取…</div><div class="meter" id="meter" hidden><div class="meter-head"><span id="meterLabel"></span><b id="meterValue"></b><span class="meter-full" id="meterFull"></span></div>@@ -247,6 +256,8 @@thumbs: new Map(), // id -> data URL or nullviewer: null, // { id, url, loading, failed }refreshing: false, saving: false,+ confirmDisable: false, // the 停用 confirmation is showing+ switching: false, // a 启用 / 停用 call is under way};const images = () => S.data?.images ?? [];const byId = (id) => images().find((image) => image.id === id);@@ -309,6 +320,21 @@}}+ // 启用 / 停用: Codex reads the setting when it starts, so either one waits for a restart (the notices say so).+ async function switchEngine(enable) {+ if (S.switching) return;+ S.switching = true; render();+ try {+ const result = await callTool("cam_setup", { enable });+ S.confirmDisable = false;+ ingest(result.structuredContent);+ } catch (error) {+ S.error = (enable ? "启用失败:" : "停用失败:") + error.message;+ } finally {+ S.switching = false; render();+ }+ }+// ---- images: every thumbnail is queued in list order, a few at a time; rows scrolled into view go first ----// (Visibility alone is not enough: a page that is hidden or not painted yet gets no intersection updates.)const thumbQueue = [];@@ -434,6 +460,8 @@}function renderHeader() {+ const setup = S.data?.setup;+ $("disable").hidden = !setup?.usesEngine || !!setup.changed || S.confirmDisable;const list = images();const plan = $("plan");$("count").textContent = list.length ? String(list.length) : "";@@ -467,29 +495,43 @@// Notices are reused while their text stays the same, so re-rendering does not move the list around.const notices = new Map();- function notice(tone, text, action) {- const key = `${tone}|${text}`;+ function notice(tone, text, ...actions) {+ const key = `${tone}|${text}|${actions.map((action) => action.label).join("|")}`;if (notices.has(key)) return notices.get(key);const box = document.createElement("div");notices.set(key, box);- box.className = `notice ${tone}`;+ box.className = `notice ${tone}${actions.some((action) => action.primary) ? " cta" : ""}`;const span = document.createElement("span");span.className = "grow";span.textContent = text;box.append(span);- if (action) {+ for (const action of actions) {const button = document.createElement("button");+ button.type = "button";button.textContent = action.label;+ if (action.primary) button.className = "primary";+ if (action.switches) button.dataset.switches = "1";button.addEventListener("click", action.run);box.append(button);}return box;}+ function setupNotices() {+ const setup = S.data?.setup;+ if (!setup) return [];+ if (setup.changed === "enabled") return [notice("info", "已启用。重启 Codex 后生效,取消勾选的图就不再发送了。")];+ if (setup.changed === "disabled") return [notice("warn", "已停用。重启 Codex 后恢复直连,取消勾选不再生效。要卸载插件,现在可以去插件页面移除。", { label: "重新启用", run: () => switchEngine(true), switches: true })];+ if (!setup.usesEngine) return [notice("info", "还没有接入 Codex:启用后重启 Codex,取消勾选才会生效。", { label: "启用", run: () => switchEngine(true), primary: true, switches: true })];+ if (S.confirmDisable) return [notice("warn", "停用后,Codex 下次启动时恢复直连,取消勾选的图会照常发送。卸载插件前请先停用。", { label: "停用", run: () => switchEngine(false), switches: true }, { label: "取消", run: () => { S.confirmDisable = false; render(); } })];+ return [];+ }+function renderList() {const nodes = [];if (S.error) nodes.push(notice("error", S.error, { label: "重试", run: () => { S.error = null; render(); refresh(); } }));- if (S.data?.engineRunning === false) nodes.push(notice("warn", "代理没有在运行,取消勾选暂时不会生效。关掉 Codex 再打开,一般就能恢复。"));+ nodes.push(...setupNotices());+ if (S.data?.engineRunning === false && S.data?.setup?.usesEngine !== false) nodes.push(notice("warn", "代理没有在运行,取消勾选暂时不会生效。关掉 Codex 再打开,一般就能恢复。"));const sendNotice = S.data?.send?.notice;if (sendNotice?.kind === "skipped") nodes.push(notice("error", `上一次请求(${timeOf(sendNotice.at)})没能按勾选替换,图片原样发给了模型。原因:${sendNotice.reason}。`));if (sendNotice?.kind === "websocket") nodes.push(notice("warn", "取消勾选时这一轮对话还在进行,这一轮剩下的请求仍带着原图;从下一条消息起生效。"));@@ -517,6 +559,7 @@// Only touch the list when its items changed, so scrolling and keyboard focus are kept.const current = main.children;if (nodes.length !== current.length || nodes.some((node, index) => node !== current[index])) main.replaceChildren(...nodes);+ for (const button of main.querySelectorAll("button[data-switches]")) button.disabled = S.switching;for (const image of list) queueThumb(image.id);}@@ -582,6 +625,7 @@$("viewerCheck").querySelector("input").addEventListener("change", (event) => { if (S.viewer) setChecked(S.viewer.id, event.target.checked); });document.addEventListener("keydown", (event) => { if (event.key === "Escape" && S.viewer) closeViewer(); });$("undo").addEventListener("click", () => { S.pending.clear(); render(); });+ $("disable").addEventListener("click", () => { S.confirmDisable = true; render(); main.scrollTo({ top: 0 }); });$("confirm").addEventListener("click", confirm);// ---- start: handshake, then Codex sends its own cam_panel result; poll so new images show up ----diff --git a/plugin/src/plugin-server.ts b/plugin/src/plugin-server.tsindex b00f4c7..4c619da 100644--- a/plugin/src/plugin-server.ts+++ b/plugin/src/plugin-server.ts@@ -5,6 +5,7 @@// Only the user may check or uncheck: calls the model makes (they carry Codex's turn metadata) are refused.// P4 — the panel page itself (an MCP App resource). cam_panel declares a "thread" entrypoint, so Codex lists the panel// under the side panel's New Tab → 插件和 MCP, and the user opens it without the model.+// v0.1-5 — cam_setup: the panel's 启用 / 停用 point Codex at the engine or back to a direct connection (setup.ts).// Input: MCP JSON-RPC over stdio. Env: CAM_ENGINE_PORT (default 17891), CAM_NO_ENGINE=1 (tests), CAM_DATA_DIR.// Output: tool results; <data dir>/plugin-server.jsonl (events and counts only, no conversation content).@@ -17,6 +18,7 @@ import { DEFAULT_PORT, ensureEngine } from "./engine.ts";import { isEntryPoint } from "./entry.ts";import { applySelection, imageFor, loadPanelState, type PanelState } from "./panel-state.ts";import { dataDir } from "./paths.ts";+import { connectDirectly, useEngine, usesEngine } from "./setup.ts";type Json = Record<string, any>;const here = dirname(fileURLToPath(import.meta.url));@@ -48,6 +50,13 @@ export const TOOLS = [inputSchema: { type: "object", properties: { ...threadArg, id: { type: "string" }, maxSide: { type: "number" } }, required: ["id"] },_meta: APP_ONLY,},+ {+ name: "cam_setup",+ title: "上下文素材:启用或停用",+ description: "素材面板内部使用:让 Codex 经过本机代理(启用),或者恢复直连(停用),重启 Codex 后生效。只有用户能操作,模型调用会被拒绝。",+ inputSchema: { type: "object", properties: { ...threadArg, enable: { type: "boolean" } }, required: ["enable"] },+ _meta: APP_ONLY,+ },];// A stack of pictures, drawn for light and dark themes (Codex takes https or data URLs only).@@ -67,6 +76,11 @@ export function readResource(uri: string): Json {// Whether this instance last found the engine running; null until the first check (and in tests).let engineRunning: boolean | null = null;+const enginePort = Number(process.env.CAM_ENGINE_PORT ?? DEFAULT_PORT);+// v0.1-5: whether config.toml points Codex at the engine, and what the panel's 启用 / 停用 changed since this instance+// started: Codex reads the setting when it starts, so a change waits for a restart.+let setupChanged: "enabled" | "disabled" | null = null;+const setupState = () => ({ usesEngine: usesEngine(), changed: setupChanged });function log(entry: Json): void {const root = dataDir();@@ -91,12 +105,20 @@ export function callTool(name: string, args: Json, meta: Json | undefined, sessiconst options = { sessionsDir };if (name === "cam_panel") {const state = loadPanelState(threadId, options);- return { content: [{ type: "text", text: summary(state) }], structuredContent: { ...state, engineRunning } };+ return { content: [{ type: "text", text: summary(state) }], structuredContent: { ...state, engineRunning, setup: setupState() } };}if (name === "cam_set_selection") {if (fromModel(meta)) throw new Error("只有用户能勾选或取消图片;需要某张图时,请回复“需要 IMG-xxx”。");const state = applySelection(threadId, { uncheck: args.uncheck, check: args.check, checkAll: args.checkAll }, options);- return { content: [{ type: "text", text: summary(state) }], structuredContent: { ...state, engineRunning } };+ return { content: [{ type: "text", text: summary(state) }], structuredContent: { ...state, engineRunning, setup: setupState() } };+ }+ if (name === "cam_setup") {+ if (fromModel(meta)) throw new Error("只有用户能启用或停用。");+ // A conflict with the user's own settings throws here, before anything is written.+ const plan = args.enable === true ? useEngine(enginePort) : connectDirectly();+ setupChanged = args.enable === true ? "enabled" : "disabled";+ const state = loadPanelState(threadId, options);+ return { content: [{ type: "text", text: args.enable === true ? "已启用,重启 Codex 后生效。" : "已停用,重启 Codex 后恢复直连。" }], structuredContent: { ...state, engineRunning, setup: setupState(), notes: plan.notes } };}if (name === "cam_image") {const image = imageFor(threadId, String(args.id), Number(args.maxSide ?? 160), options);@@ -108,11 +130,10 @@ export function callTool(name: string, args: Json, meta: Json | undefined, sessifunction main(): void {const send = (message: Json) => process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`);- const port = Number(process.env.CAM_ENGINE_PORT ?? DEFAULT_PORT);let engineState = "";const supervise = async () => {if (process.env.CAM_NO_ENGINE === "1") return;- const result = await ensureEngine({ port });+ const result = await ensureEngine({ port: enginePort });const replaced = result.replaced ? { replacedPid: result.replaced.pid, replacedBuild: result.replaced.build ?? null } : {};if (result.state !== "running" || engineState !== "running") log({ event: "engine", state: result.state, enginePid: result.health?.pid ?? null, build: result.health?.build ?? null, ...replaced });engineState = result.state;@@ -148,7 +169,7 @@ function main(): void {try {const result = callTool(params.name, params.arguments ?? {}, params._meta);// The open panel reads its state every few seconds and loads each image once; only changes are worth a line.- if (params.name === "cam_set_selection" || fromModel(params._meta)) log({ event: "tools/call", name: params.name, fromModel: fromModel(params._meta) });+ if (params.name === "cam_set_selection" || params.name === "cam_setup" || fromModel(params._meta)) log({ event: "tools/call", name: params.name, fromModel: fromModel(params._meta) });send({ id, result });} catch (error) {log({ event: "tools/call", name: params.name, fromModel: fromModel(params._meta), error: String(error) });diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.tsindex c1b0496..dbd59b9 100644--- a/plugin/src/proxy.ts+++ b/plugin/src/proxy.ts@@ -25,6 +25,7 @@ import { isEntryPoint } from "./entry.ts";import { dataDir, proxyLogDirOf } from "./paths.ts";import { recordRequest } from "./request-stats.ts";import { rewriteItems, type Described } from "./rewrite.ts";+import { connectDirectly, pluginGone, usesEngine } from "./setup.ts";import { effectiveSelection, selectionDir } from "./selection.ts";import { loadThreadIndex, pixelHashOf, type ThreadIndex } from "./thread-index.ts";@@ -241,7 +242,25 @@ async function main(): Promise<void> {let sequence = 0;log({ at: startedAt, event: "engine-start", pid: process.pid, port, build, version });if (!process.argv.includes("--stay")) {+ // v0.1-5: a plugin removed or turned off without 停用 leaves Codex pointed at an engine nothing will start again.+ // Seen in two checks in a row (or once more as the engine exits, when Codex is gone and cannot be mid-write), Codex+ // goes back to connecting directly from its next start; until then this engine keeps serving. On Windows the engine+ // usually ends together with the plugin's MCP server, so there the panel's 停用 or the uninstall command does it.+ let gone = 0;+ const checkPlugin = (final: boolean) => {+ try {+ const state = pluginGone();+ gone = state ? gone + 1 : 0;+ if (!state || (!final && gone < 2) || !usesEngine()) return;+ connectDirectly();+ log({ at: new Date().toISOString(), event: "connect-directly", pid: process.pid, reason: `plugin ${state}` });+ } catch (error) {+ log({ at: new Date().toISOString(), event: "plugin-check-failed", pid: process.pid, error: String(error) });+ }+ };+ setInterval(() => checkPlugin(false), 15_000).unref();watchForCodex(() => {+ checkPlugin(true);log({ at: new Date().toISOString(), event: "engine-exit", pid: process.pid, reason: "no Codex process left" });process.exit(0);});diff --git a/plugin/src/setup.ts b/plugin/src/setup.tsnew file mode 100644index 0000000..808556f--- /dev/null+++ b/plugin/src/setup.ts@@ -0,0 +1,75 @@+// Purpose: v0.1-5 — switch Codex between going through the engine and connecting directly. Shared by the command line+// (cam install / setup / uninstall), the panel's 启用 / 停用 buttons, and the engine's own check after the plugin was+// removed without 停用. Every change backs up config.toml first and replaces the file whole (write, then rename), so+// Codex never reads half a file. .env may hold credentials: it is never copied or printed.+// Input: ~/.codex/config.toml and ~/.codex/.env; the proxy variables Codex inherits; the plugin's folder in Codex's+// cache. Output: the same two files, and a backup under <data dir>/config-backup/.++import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { codexHome, persistedEnv, proxyStatus } from "./codexconfig.ts";+import { MARKETPLACE, PLUGIN, planInstall, planUninstall, pluginStatus, type Plan, type UserProxyEnv } from "./install.ts";+import { dataDir } from "./paths.ts";++export const codexFiles = () => ({ configFile: join(codexHome(), "config.toml"), envFile: join(codexHome(), ".env") });+export const readConfig = (): string => (existsSync(codexFiles().configFile) ? readFileSync(codexFiles().configFile, "utf8") : "");+export const readEnv = (): string | null => (existsSync(codexFiles().envFile) ? readFileSync(codexFiles().envFile, "utf8") : null);++// The proxy variables Codex will start with (the Windows registry; elsewhere the current environment).+export const userProxyEnv = (): UserProxyEnv => ({ httpProxy: persistedEnv("HTTPS_PROXY") ?? persistedEnv("HTTP_PROXY") ?? persistedEnv("ALL_PROXY"), noProxy: persistedEnv("NO_PROXY") });++export function backupConfig(): void {+ const { configFile } = codexFiles();+ 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 replaceFile(file: string, text: string): void {+ writeFileSync(`${file}.cam-tmp`, text, "utf8");+ try {+ renameSync(`${file}.cam-tmp`, file);+ } catch {+ // Windows refuses the rename while another program has the file open; write it in place then.+ writeFileSync(file, text, "utf8");+ rmSync(`${file}.cam-tmp`, { force: true });+ }+}++export function applyPlan(plan: Plan): void {+ const { configFile, envFile } = codexFiles();+ if (plan.configChanged) {+ backupConfig();+ replaceFile(configFile, plan.configText);+ }+ if (plan.envChanged) {+ if (plan.envText === null) rmSync(envFile, { force: true });+ else replaceFile(envFile, plan.envText);+ }+}++// Codex goes through the engine from its next start. Throws, changing nothing, when the user's own settings conflict.+export function useEngine(port: number): Plan {+ const plan = planInstall({ configText: readConfig(), envText: readEnv(), env: userProxyEnv(), port });+ applyPlan(plan);+ return plan;+}++// Codex connects directly again from its next start; only what this tool wrote is removed.+export function connectDirectly(): Plan {+ const plan = planUninstall({ configText: readConfig(), envText: readEnv() });+ applyPlan(plan);+ return plan;+}++export const usesEngine = (): boolean => proxyStatus(readConfig()).enabled;++// Whether Codex no longer runs the plugin, judged only from clear signs: its folder in Codex's cache is gone+// (uninstalled), or config.toml turns it off. An entry Codex may some day write differently is not taken as a removal.+export function pluginGone(): "removed" | "disabled" | null {+ const root = join(codexHome(), "plugins", "cache", MARKETPLACE, PLUGIN);+ if (!existsSync(root) || !readdirSync(root).length) return "removed";+ const status = pluginStatus(readConfig());+ return status.installed && !status.enabled ? "disabled" : null;+}diff --git a/scripts/install.ps1 b/scripts/install.ps1new file mode 100644index 0000000..f213af0--- /dev/null+++ b/scripts/install.ps1@@ -0,0 +1,61 @@+# Purpose: v0.1-5 - install the Codex attachment manager on Windows in one line, without opening GitHub:+# irm https://github.com/chipfighter/codex-attachment-manager/releases/latest/download/install.ps1 | iex+# Codex's own command line adds this repository as a plugin marketplace and installs the plugin; the installed plugin+# then points Codex at its local engine (cam setup) and starts it. Running it again upgrades. Restart Codex afterwards.+# Input: CAM_REF (a tag or branch; a release sets its own tag), CAM_SOURCE (a local checkout, for tests),+# CODEX_CLI_PATH, CODEX_HOME. Output: Codex's plugin cache, config.toml (backed up first) and, when needed, .env.+# ASCII only: Windows PowerShell 5.1 decodes a downloaded script as Latin-1. The body runs in its own scope, so the+# user's session keeps its own settings.++& {+ $ErrorActionPreference = 'Stop'+ $repo = 'chipfighter/codex-attachment-manager'+ $name = 'codex-attachment-manager'+ $plugin = "$name@$name"++ function Find-Codex {+ if ($env:CODEX_CLI_PATH -and (Test-Path -LiteralPath $env:CODEX_CLI_PATH)) { return $env:CODEX_CLI_PATH }+ # The desktop app keeps one folder per build; the newest belongs to the app that runs now.+ $bin = Join-Path $env:LOCALAPPDATA 'OpenAI\Codex\bin'+ if (Test-Path -LiteralPath $bin) {+ $newest = Get-ChildItem -LiteralPath $bin -Directory | ForEach-Object { Join-Path $_.FullName 'codex.exe' } |+ Where-Object { Test-Path -LiteralPath $_ } | Sort-Object { (Get-Item -LiteralPath $_).LastWriteTime } -Descending | Select-Object -First 1+ if ($newest) { return $newest }+ }+ $onPath = Get-Command codex -All -ErrorAction SilentlyContinue | Where-Object { $_.Source -match '\.(exe|cmd)$' } | Select-Object -First 1+ if ($onPath) { return $onPath.Source }+ throw 'Codex command line not found. Install the Codex desktop app and open it once, or set CODEX_CLI_PATH to codex.exe.'+ }++ # Codex prints warnings on stderr; they are not failures.+ function Invoke-Codex([string[]]$CodexArgs, [switch]$AllowFailure) {+ $ErrorActionPreference = 'Continue'+ $output = (& $codex @CodexArgs 2>&1 | ForEach-Object { "$_" }) -join "`n"+ if ($LASTEXITCODE -ne 0 -and -not $AllowFailure) { throw "codex $($CodexArgs -join ' ') failed: $output" }+ }++ $codex = Find-Codex+ $codexHome = if ($env:CODEX_HOME) { $env:CODEX_HOME } else { Join-Path $HOME '.codex' }+ # A release replaces the placeholder with its own tag; a copy from the repository follows the default branch.+ $ref = if ($env:CAM_REF) { $env:CAM_REF } elseif ('__CAM_REF__' -notlike '__*') { '__CAM_REF__' } else { $null }+ $source = if ($env:CAM_SOURCE) { $env:CAM_SOURCE } else { $repo }++ Write-Host "Installing the plugin with $codex ..."+ # Added afresh, so the marketplace follows the release this script came with.+ Invoke-Codex @('plugin', 'remove', $plugin) -AllowFailure+ Invoke-Codex @('plugin', 'marketplace', 'remove', $name) -AllowFailure+ $add = @('plugin', 'marketplace', 'add', $source)+ if ($ref -and -not $env:CAM_SOURCE) { $add += @('--ref', $ref) }+ Invoke-Codex $add+ Invoke-Codex @('plugin', 'add', $plugin)++ $root = Join-Path $codexHome "plugins\cache\$name\$name"+ $installed = Get-ChildItem -LiteralPath $root -Directory -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending | Select-Object -First 1+ if (-not $installed) { throw "The plugin did not arrive in $root." }+ # The installed plugin writes the proxy settings itself (checking for conflicts first) and starts its engine.+ Write-Host 'Pointing Codex at the local engine ...'+ & cmd.exe /d /s /c call "$($installed.FullName)\scripts\launch.cmd" "$($installed.FullName)\src\cam.ts" setup+ if ($LASTEXITCODE -ne 0) { throw 'The proxy settings were not written (see above); Codex still connects directly.' }+ Write-Host ''+ Write-Host 'Done. Restart Codex, then open the panel from the side panel: New tab > Plugins and MCP.'+}diff --git a/scripts/install.sh b/scripts/install.shnew file mode 100755index 0000000..5c26e38--- /dev/null+++ b/scripts/install.sh@@ -0,0 +1,62 @@+#!/bin/sh+# Purpose: v0.1-5 - install the Codex attachment manager on macOS or Linux in one line, without opening GitHub:+# curl -fsSL https://github.com/chipfighter/codex-attachment-manager/releases/latest/download/install.sh | sh+# Codex's own command line adds this repository as a plugin marketplace and installs the plugin; the installed plugin+# then points Codex at its local engine (cam setup) and starts it. Running it again upgrades. Restart Codex afterwards.+# Input: CAM_REF (a tag or branch; a release sets its own tag), CAM_SOURCE (a local checkout, for tests),+# CODEX_CLI_PATH, CODEX_HOME. Output: Codex's plugin cache, config.toml (backed up first) and, when needed, .env.+set -eu++repo=chipfighter/codex-attachment-manager+name=codex-attachment-manager+plugin="$name@$name"++find_codex() {+ if [ -n "${CODEX_CLI_PATH:-}" ] && [ -x "$CODEX_CLI_PATH" ]; then printf '%s\n' "$CODEX_CLI_PATH"; return 0; fi+ # The desktop app ships one; Codex's own installer puts it in ~/.local/bin.+ for candidate in \+ /Applications/ChatGPT.app/Contents/Resources/codex \+ /Applications/Codex.app/Contents/Resources/codex \+ "$HOME/Applications/ChatGPT.app/Contents/Resources/codex" \+ "$HOME/Applications/Codex.app/Contents/Resources/codex" \+ "$HOME/.local/bin/codex"+ do+ if [ -x "$candidate" ]; then printf '%s\n' "$candidate"; return 0; fi+ done+ command -v codex+}++codex=$(find_codex) || {+ printf '%s\n' 'Codex command line not found. Install Codex (the desktop app, or the command line), or set CODEX_CLI_PATH.' >&2+ exit 1+}+codex_home=${CODEX_HOME:-$HOME/.codex}+# A release replaces the placeholder with its own tag; a copy from the repository follows the default branch.+ref=${CAM_REF:-__CAM_REF__}+case "$ref" in __*) ref= ;; esac+source=${CAM_SOURCE:-$repo}++printf 'Installing the plugin with %s ...\n' "$codex"+# Added afresh, so the marketplace follows the release this script came with.+"$codex" plugin remove "$plugin" >/dev/null 2>&1 || true+"$codex" plugin marketplace remove "$name" >/dev/null 2>&1 || true+if [ -n "${CAM_SOURCE:-}" ] || [ -z "$ref" ]; then+ "$codex" plugin marketplace add "$source"+else+ "$codex" plugin marketplace add "$source" --ref "$ref"+fi+"$codex" plugin add "$plugin"++installed=$(ls -dt "$codex_home/plugins/cache/$name/$name"/*/ 2>/dev/null | head -n 1)+installed=${installed%/}+if [ -z "$installed" ]; then+ printf 'The plugin did not arrive in %s.\n' "$codex_home/plugins/cache/$name/$name" >&2+ exit 1+fi+# The installed plugin writes the proxy settings itself (checking for conflicts first) and starts its engine.+printf '%s\n' 'Pointing Codex at the local engine ...'+if ! "$installed/scripts/launch" "$installed/src/cam.ts" setup; then+ printf '%s\n' 'The proxy settings were not written (see above); Codex still connects directly.' >&2+ exit 1+fi+printf '\n%s\n' 'Done. Restart Codex, then open the panel from the side panel: New tab > Plugins and MCP.'diff --git a/scripts/uninstall.ps1 b/scripts/uninstall.ps1new file mode 100644index 0000000..fe49b61--- /dev/null+++ b/scripts/uninstall.ps1@@ -0,0 +1,94 @@+# Purpose: v0.1-5 - remove the Codex attachment manager on Windows in one line; also the way back when Codex cannot+# connect because the plugin was removed without turning it off in the panel first:+# irm https://github.com/chipfighter/codex-attachment-manager/releases/latest/download/uninstall.ps1 | iex+# Takes out only the marked blocks this tool wrote to config.toml and .env (config.toml is backed up first), then removes+# the plugin and its marketplace with Codex's own command line. Needs neither Node nor any of the plugin's files.+# Input: CODEX_HOME, CAM_DATA_DIR, CODEX_CLI_PATH. Output: config.toml, .env, Codex's plugin cache.+# ASCII only, and in its own scope (see install.ps1).++& {+ $ErrorActionPreference = 'Stop'+ $name = 'codex-attachment-manager'+ $plugin = "$name@$name"+ $beginMarkers = @(+ '# >>> codex-attachment-manager: managed proxy setting, remove it with the tool >>>',+ '# >>> codex-attachment-manager: managed MCP server, remove it with the tool >>>'+ )+ $endMarker = '# <<< codex-attachment-manager <<<'++ # The rule the plugin itself uses (codexconfig.ts): drop every marked block; a block at the very top takes the blank+ # line after it along. BOM and line endings stay as they were. Returns $null when there is nothing to remove.+ function Remove-ManagedBlocks([string]$Path) {+ if (-not (Test-Path -LiteralPath $Path)) { return $null }+ $bytes = [IO.File]::ReadAllBytes($Path)+ $bom = $bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF+ $skip = if ($bom) { 3 } else { 0 }+ $body = [Text.Encoding]::UTF8.GetString($bytes, $skip, $bytes.Length - $skip)+ $eol = if ($body.Contains("`r`n")) { "`r`n" } else { "`n" }+ $lines = $body.Split([string[]]@($eol), [StringSplitOptions]::None)+ $kept = New-Object System.Collections.Generic.List[string]+ $changed = $false+ for ($i = 0; $i -lt $lines.Length; $i++) {+ if ($beginMarkers -notcontains $lines[$i].Trim()) { $kept.Add($lines[$i]); continue }+ $stop = $i + 1+ while ($stop -lt $lines.Length -and $lines[$stop].Trim() -ne $endMarker) { $stop++ }+ if ($stop -ge $lines.Length) { throw "A marked block in $Path has no end marker; the file was left as it is." }+ $atTop = $kept.Count -eq 0+ $i = $stop+ if ($atTop -and $i + 1 -lt $lines.Length -and $lines[$i + 1] -eq '') { $i++ }+ $changed = $true+ }+ if (-not $changed) { return $null }+ return [pscustomobject]@{ Bom = $bom; Text = [string]::Join($eol, $kept.ToArray()) }+ }++ function Save-Text([string]$Path, $Result) {+ $out = [Text.Encoding]::UTF8.GetBytes($Result.Text)+ if ($Result.Bom) { $out = [byte[]]((0xEF, 0xBB, 0xBF) + $out) }+ [IO.File]::WriteAllBytes($Path, $out)+ }++ $codexHome = if ($env:CODEX_HOME) { $env:CODEX_HOME } else { Join-Path $HOME '.codex' }+ $dataDir = if ($env:CAM_DATA_DIR) { $env:CAM_DATA_DIR } else { Join-Path $env:LOCALAPPDATA $name }+ $config = Join-Path $codexHome 'config.toml'+ $dotenv = Join-Path $codexHome '.env'++ $result = Remove-ManagedBlocks $config+ if ($result) {+ $backups = Join-Path $dataDir 'config-backup'+ New-Item -ItemType Directory -Force -Path $backups | Out-Null+ Copy-Item -LiteralPath $config -Destination (Join-Path $backups ('config.toml.' + (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH-mm-ss.fffZ')))+ Save-Text $config $result+ Write-Host 'Codex connects directly again: the proxy settings were taken out of config.toml.'+ } else {+ Write-Host 'config.toml holds no proxy settings of this tool.'+ }+ $result = Remove-ManagedBlocks $dotenv+ if ($result) {+ # A .env that held nothing but this block is deleted rather than left empty.+ if ($result.Text.Trim() -eq '') { Remove-Item -LiteralPath $dotenv } else { Save-Text $dotenv $result }+ Write-Host 'The NO_PROXY block was taken out of .env.'+ }++ $codex = $null+ if ($env:CODEX_CLI_PATH -and (Test-Path -LiteralPath $env:CODEX_CLI_PATH)) { $codex = $env:CODEX_CLI_PATH }+ if (-not $codex) {+ $bin = Join-Path $env:LOCALAPPDATA 'OpenAI\Codex\bin'+ if (Test-Path -LiteralPath $bin) {+ $codex = Get-ChildItem -LiteralPath $bin -Directory | ForEach-Object { Join-Path $_.FullName 'codex.exe' } |+ Where-Object { Test-Path -LiteralPath $_ } | Sort-Object { (Get-Item -LiteralPath $_).LastWriteTime } -Descending | Select-Object -First 1+ }+ }+ if (-not $codex) { $codex = (Get-Command codex -All -ErrorAction SilentlyContinue | Where-Object { $_.Source -match '\.(exe|cmd)$' } | Select-Object -First 1).Source }+ if ($codex) {+ $ErrorActionPreference = 'Continue'+ & $codex plugin remove $plugin 2>&1 | Out-Null+ & $codex plugin marketplace remove $name 2>&1 | Out-Null+ $ErrorActionPreference = 'Stop'+ Write-Host 'The plugin and its marketplace were removed from Codex.'+ } else {+ Write-Host 'Codex command line not found: remove the plugin on the Plugins page in Codex.'+ }+ Write-Host ''+ Write-Host "Done. Restart Codex. Selections and logs stay in $dataDir; delete that folder if you do not need them."+}diff --git a/scripts/uninstall.sh b/scripts/uninstall.shnew file mode 100755index 0000000..cede7db--- /dev/null+++ b/scripts/uninstall.sh@@ -0,0 +1,101 @@+#!/bin/sh+# Purpose: v0.1-5 - remove the Codex attachment manager on macOS or Linux in one line; also the way back when Codex+# cannot connect because the plugin was removed without turning it off in the panel first:+# curl -fsSL https://github.com/chipfighter/codex-attachment-manager/releases/latest/download/uninstall.sh | sh+# Takes out only the marked blocks this tool wrote to config.toml and .env (config.toml is backed up first), then removes+# the plugin and its marketplace with Codex's own command line. Needs neither Node nor any of the plugin's files.+# Input: CODEX_HOME, CAM_DATA_DIR, XDG_DATA_HOME, CODEX_CLI_PATH. Output: config.toml, .env, Codex's plugin cache.+set -eu++name=codex-attachment-manager+plugin="$name@$name"+codex_home=${CODEX_HOME:-$HOME/.codex}+if [ -n "${CAM_DATA_DIR:-}" ]; then data_dir=$CAM_DATA_DIR+elif [ "$(uname -s)" = Darwin ]; then data_dir="$HOME/Library/Application Support/$name"+else data_dir="${XDG_DATA_HOME:-$HOME/.local/share}/$name"+fi++# The rule the plugin itself uses (codexconfig.ts): drop every marked block; a block at the very top takes the blank+# line after it along. A BOM and CRLF line endings stay as they were. Writes the result to $2; exit status 1 when+# there was nothing to remove, 2 when a block has no end marker.+strip_blocks() {+ awk '+ function trim(s) { sub(/^[ \t\r]+/, "", s); sub(/[ \t\r]+$/, "", s); return s }+ { line[NR] = $0 }+ END {+ bom = "\357\273\277"+ proxy = "# >>> codex-attachment-manager: managed proxy setting, remove it with the tool >>>"+ mcp = "# >>> codex-attachment-manager: managed MCP server, remove it with the tool >>>"+ stop = "# <<< codex-attachment-manager <<<"+ if (NR > 0 && substr(line[1], 1, 3) == bom) { hadbom = 1; line[1] = substr(line[1], 4) }+ kept = 0; changed = 0+ for (i = 1; i <= NR; i++) {+ t = trim(line[i])+ if (t != proxy && t != mcp) { out[++kept] = line[i]; continue }+ j = i + 1+ while (j <= NR && trim(line[j]) != stop) j+++ if (j > NR) exit 2+ top = (kept == 0)+ i = j+ if (top && i < NR && (line[i + 1] == "" || line[i + 1] == "\r")) i+++ changed = 1+ }+ if (!changed) exit 1+ for (k = 1; k <= kept; k++) printf "%s%s\n", (k == 1 && hadbom ? bom : ""), out[k]+ }' "$1" > "$2"+}++# Only replaces the file when something was removed; the new text goes in place in one step.+clean() {+ file=$1+ [ -f "$file" ] || return 1+ status=0+ strip_blocks "$file" "$file.cam-tmp" || status=$?+ if [ "$status" -ne 0 ]; then+ rm -f "$file.cam-tmp"+ if [ "$status" -eq 2 ]; then printf 'A marked block in %s has no end marker; the file was left as it is.\n' "$file" >&2; exit 1; fi+ return 1+ fi+ return 0+}++config="$codex_home/config.toml"+if clean "$config"; then+ mkdir -p "$data_dir/config-backup"+ cp "$config" "$data_dir/config-backup/config.toml.$(date -u +%Y-%m-%dT%H-%M-%S.000Z)"+ mv "$config.cam-tmp" "$config"+ printf '%s\n' 'Codex connects directly again: the proxy settings were taken out of config.toml.'+else+ printf '%s\n' 'config.toml holds no proxy settings of this tool.'+fi+dotenv="$codex_home/.env"+if clean "$dotenv"; then+ # A .env that held nothing but this block is deleted rather than left empty.+ if awk 'NR == 1 { sub(/^\357\273\277/, "") } /[^ \t\r]/ { found = 1 } END { exit found ? 1 : 0 }' "$dotenv.cam-tmp"; then+ rm -f "$dotenv" "$dotenv.cam-tmp"+ else+ mv "$dotenv.cam-tmp" "$dotenv"+ fi+ printf '%s\n' 'The NO_PROXY block was taken out of .env.'+fi++codex=+if [ -n "${CODEX_CLI_PATH:-}" ] && [ -x "$CODEX_CLI_PATH" ]; then codex=$CODEX_CLI_PATH; fi+for candidate in \+ /Applications/ChatGPT.app/Contents/Resources/codex \+ /Applications/Codex.app/Contents/Resources/codex \+ "$HOME/Applications/ChatGPT.app/Contents/Resources/codex" \+ "$HOME/Applications/Codex.app/Contents/Resources/codex" \+ "$HOME/.local/bin/codex"+do+ if [ -z "$codex" ] && [ -x "$candidate" ]; then codex=$candidate; fi+done+if [ -z "$codex" ]; then codex=$(command -v codex || true); fi+if [ -n "$codex" ]; then+ "$codex" plugin remove "$plugin" >/dev/null 2>&1 || true+ "$codex" plugin marketplace remove "$name" >/dev/null 2>&1 || true+ printf '%s\n' 'The plugin and its marketplace were removed from Codex.'+else+ printf '%s\n' 'Codex command line not found: remove the plugin on the Plugins page in Codex.'+fi+printf '\nDone. Restart Codex. Selections and logs stay in %s; delete that folder if you do not need them.\n' "$data_dir"diff --git a/spike/scripts/panel-dev.ts b/spike/scripts/panel-dev.tsindex 2506d14..c3ac048 100644--- a/spike/scripts/panel-dev.ts+++ b/spike/scripts/panel-dev.ts@@ -3,8 +3,10 @@// server code over a synthetic thread of test images (no user material).// Input: none; `node spike/scripts/panel-dev.ts [--port 17895]`. Output: http://127.0.0.1:<port>/// (?theme=dark, ?solo=1 for the panel alone, ?demo=pending|preview for a state to screenshot, ?slow=1 for slow calls,-// ?stats=none|skipped|websocket for other engine statistics than a normal rewritten request).-// Everything is written to a temporary folder; nothing in the user's Codex home is read or changed.+// ?stats=none|skipped|websocket for other engine statistics than a normal rewritten request, ?setup=off for a Codex that+// does not go through the engine yet, ?demo=disable for the 停用 confirmation).+// Everything is written to a temporary folder, including a Codex home of its own: nothing in the user's Codex home is+// read or changed, whatever is clicked.import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { createServer } from "node:http";@@ -22,6 +24,11 @@ const root = mkdtempSync(join(tmpdir(), "cam-panel-dev-"));const day = join(root, "sessions", "2026", "09", "24");mkdirSync(day, { recursive: true });process.env.CAM_DATA_DIR = join(root, "data");+// A Codex home of its own, with the plugin installed, so 启用 / 停用 on this page never touch the real one.+const codexHomeDir = join(root, "codex-home");+mkdirSync(join(codexHomeDir, "plugins", "cache", "codex-attachment-manager", "codex-attachment-manager", "0.1.0"), { recursive: true });+writeFileSync(join(codexHomeDir, "config.toml"), `model = "gpt-6-sol"\n\n[plugins."codex-attachment-manager@codex-attachment-manager"]\nenabled = true\n`);+process.env.CODEX_HOME = codexHomeDir;const url = (bytes: Buffer) => `data:image/png;base64,${bytes.toString("base64")}`;const line = (type: string, payload: object) => `${JSON.stringify({ timestamp: "2026-09-24T10:00:00Z", type, payload })}\n`;const turn = (id: string) => line("event_msg", { type: "task_started", turn_id: id });@@ -51,10 +58,11 @@ writeFileSync(join(day, `rollout-2026-09-24T10-00-00-${THREAD}.jsonl`),turn("t4") + upload("msg_4", "t4", [["settings-screenshot.png", screenshot]]) +line("response_item", { type: "image_generation_call", id: "ig_1", status: "completed", result: png(256, 256, (x, y) => [x, y, 180]).toString("base64") }) + say("需要 IMG-001 才能回答。", "t4"));-const { callTool } = await import("../src/plugin-server.ts");-const { imageSizesOf } = await import("../src/proxy.ts");-const { recordRequest } = await import("../src/request-stats.ts");-const { requestStatsDirOf } = await import("../src/paths.ts");+const { callTool } = await import("../../plugin/src/plugin-server.ts");+const { imageSizesOf } = await import("../../plugin/src/proxy.ts");+const { recordRequest } = await import("../../plugin/src/request-stats.ts");+const { connectDirectly, useEngine } = await import("../../plugin/src/setup.ts");+const { requestStatsDirOf } = await import("../../plugin/src/paths.ts");const sessionsDir = join(root, "sessions");const meta = { threadId: THREAD, thread_id: THREAD };// Start with the red square, the copy of the blue circle and the large noise image unchecked, so both placeholder@@ -116,12 +124,15 @@ const HOST = `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><titsetTimeout(() => {if (params.get("demo") === "pending") d.querySelector('[data-id="IMG-002"] input')?.click();if (params.get("demo") === "preview") d.querySelector('[data-id="IMG-004"] .thumb')?.click();+ if (params.get("demo") === "disable") d.getElementById("disable")?.click();}, 700);}document.getElementById("theme").onclick = () => { theme = theme === "dark" ? "light" : "dark"; document.body.classList.toggle("dark", theme === "dark"); send({ method: "ui/notifications/host-context-changed", params: { theme } }); };document.getElementById("grow").onclick = () => fetch("/grow", { method: "POST" });// The engine statistics for this page load, then the panel.- fetch("/stats?kind=" + (params.get("stats") || "normal"), { method: "POST" }).then(() => { frame.src = "/panel.html"; });+ fetch("/stats?kind=" + (params.get("stats") || "normal"), { method: "POST" })+ .then(() => fetch("/setup?state=" + (params.get("setup") || "on"), { method: "POST" }))+ .then(() => { frame.src = "/panel.html"; });</script></body></html>`;let extra = 0;@@ -133,6 +144,11 @@ createServer((request, response) => {writeStats(new URL(request.url, "http://x").searchParams.get("kind") ?? "normal");return reply(200, "application/json", "{}");}+ if (request.method === "POST" && request.url?.startsWith("/setup")) {+ // Whether the (temporary) Codex home goes through the engine when the page loads.+ if (new URL(request.url, "http://x").searchParams.get("state") === "off") connectDirectly(); else useEngine(17891);+ return reply(200, "application/json", "{}");+ }if (request.method === "POST" && request.url === "/grow") {// A new turn with one more upload, to watch the panel pick it up by polling.extra++;diff --git a/spike/src/plugin-server.test.ts b/spike/src/plugin-server.test.tsindex 3b1f93f..8b79fcc 100644--- a/spike/src/plugin-server.test.ts+++ b/spike/src/plugin-server.test.ts@@ -88,7 +88,7 @@ test("a stdio session lists the tools and answers calls", async () => {child.stdin.end();assert.deepEqual(replies[1].result.capabilities, { tools: {}, resources: {} });assert.deepEqual(replies[1].result.serverInfo.icons.map((icon: any) => [icon.theme, icon.src.slice(0, 26)]), [["light", "data:image/svg+xml;base64,"], ["dark", "data:image/svg+xml;base64,"]]);- assert.deepEqual(replies[2].result.tools.map((tool: any) => tool.name), ["cam_panel", "cam_set_selection", "cam_image"]);+ assert.deepEqual(replies[2].result.tools.map((tool: any) => tool.name), ["cam_panel", "cam_set_selection", "cam_image", "cam_setup"]);assert.equal(replies[3].result.structuredContent.images.length, 3);assert.equal(replies[3].result.structuredContent.engineRunning, null, "engine supervision is off in this test");assert.equal(replies[4].result.isError, true);diff --git a/spike/src/scripts-smoke.ts b/spike/src/scripts-smoke.tsnew file mode 100644index 0000000..7508463--- /dev/null+++ b/spike/src/scripts-smoke.ts@@ -0,0 +1,87 @@+// Purpose: v0.1-5 — the one-line install and uninstall scripts, run for real on this platform against a throwaway+// Codex home that already holds the user's own settings: install adds the plugin and points Codex at the engine+// (which starts), uninstall gives back config.toml and .env exactly as they were and removes the plugin. The+// marketplace is this checkout (CAM_SOURCE), so nothing is fetched from GitHub. CI runs it on Windows, macOS and Linux.+// Input: a Codex command line (CODEX_CLI_PATH, a desktop app's copy, or codex on PATH); [--port 17894] for the test+// engine. Output: a JSON summary on stdout; exit code 1 when a check fails.++import { spawn } from "node:child_process";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";+import { setTimeout as sleep } from "node:timers/promises";+import { findCodexCli } from "../../plugin/src/codexcli.ts";+import { buildOf, engineHealth } from "../../plugin/src/engine.ts";+import { MARKETPLACE, PLUGIN, pluginStatus } from "../../plugin/src/install.ts";++type Json = Record<string, any>;+const root = resolve(import.meta.dirname, "..", "..");+const option = (name: string, fallback: string) => (process.argv.includes(name) ? process.argv[process.argv.indexOf(name) + 1] : fallback);+const port = Number(option("--port", "17894"));+const windows = process.platform === "win32";+const eol = windows ? "\r\n" : "\n";++// Done when the script exits, not when its output closes: on Windows the engine it starts inherits the output pipe+// and would hold it open until the engine itself exits.+function run(script: "install" | "uninstall", env: NodeJS.ProcessEnv): Promise<{ ok: boolean; output: string }> {+ const file = join(root, "scripts", windows ? `${script}.ps1` : `${script}.sh`);+ const [command, args] = windows ? ["powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", file]] : ["sh", [file]];+ return new Promise((done) => {+ const child = spawn(command, args, { env, windowsHide: true });+ let output = "";+ child.stdout.on("data", (chunk: Buffer) => { output += chunk.toString("utf8"); });+ child.stderr.on("data", (chunk: Buffer) => { output += chunk.toString("utf8"); });+ child.on("exit", (code) => setTimeout(() => done({ ok: code === 0, output: output.trim() }), 200));+ });+}++async function main(): Promise<boolean> {+ const scratch = mkdtempSync(join(tmpdir(), "cam-scripts-"));+ const [home, data] = ["codex-home", "data"].map((name) => join(scratch, name));+ for (const dir of [home, data]) mkdirSync(dir, { recursive: true });+ const cli = findCodexCli();+ if (!cli) throw new Error("no Codex command line found (set CODEX_CLI_PATH or put codex on PATH)");+ // The user's own settings, in this platform's line endings; they must come back byte for byte.+ const config = ['model = "gpt-6-sol"', "", "[features]", "view_image = true", ""].join(eol);+ const dotenv = `OTHER_SETTING=1${eol}`;+ writeFileSync(join(home, "config.toml"), config);+ writeFileSync(join(home, ".env"), dotenv);+ const env = { ...process.env, CODEX_HOME: home, CAM_DATA_DIR: data, CAM_ENGINE_PORT: String(port), CAM_SOURCE: root, CODEX_CLI_PATH: cli };+ const summary: Json = { platform: process.platform, cli, scratch, checks: {} };+ const checks: Record<string, boolean> = summary.checks;++ const installed = await run("install", env);+ summary.install = installed.output.split(/\r?\n/).slice(-12);+ const afterInstall = readFileSync(join(home, "config.toml"), "utf8");+ const cache = join(home, "plugins", "cache", MARKETPLACE, PLUGIN);+ checks.installScriptSucceeded = installed.ok;+ checks.pluginInstalled = pluginStatus(afterInstall).installed && existsSync(cache);+ checks.pointsAtEngine = afterInstall.includes(`openai_base_url = "http://localhost:${port}/backend-api/codex"`);+ let health = null;+ for (let i = 0; i < 20 && !health; i++) {+ health = await engineHealth(port);+ if (!health) await sleep(250);+ }+ const version = JSON.parse(readFileSync(join(root, "plugin", ".codex-plugin", "plugin.json"), "utf8")).version;+ summary.engine = health ? { pid: health.pid, build: health.build, installedBuild: buildOf(join(cache, version, "src")) } : null;+ checks.engineFromInstalledCopy = !!health && health.build === buildOf(join(cache, version, "src"));++ const removed = await run("uninstall", env);+ summary.uninstall = removed.output.split(/\r?\n/).slice(-8);+ checks.uninstallScriptSucceeded = removed.ok;+ const afterUninstall = readFileSync(join(home, "config.toml"), "utf8");+ // Codex's own command line writes config.toml with LF when it adds or removes the plugin's entries, so line endings+ // are compared loosely here; the plugin's own blocks keep them (unit tests check that byte for byte).+ const lf = (text: string) => text.replaceAll("\r\n", "\n");+ summary.configAfterUninstall = afterUninstall === config ? "identical" : lf(afterUninstall) === lf(config) ? "identical apart from line endings" : afterUninstall;+ checks.configRestored = lf(afterUninstall) === lf(config);+ checks.dotenvRestored = readFileSync(join(home, ".env"), "utf8") === dotenv;+ checks.pluginRemoved = !pluginStatus(afterUninstall).installed && !existsSync(cache);++ if (health) try { process.kill(health.pid); } catch { /* already gone */ }+ const ok = Object.values(checks).every(Boolean);+ console.log(JSON.stringify({ ok, ...summary }, null, 2));+ return ok;+}++if (!(await main())) process.exitCode = 1;diff --git a/spike/src/setup.test.ts b/spike/src/setup.test.tsnew file mode 100644index 0000000..07e4e3d--- /dev/null+++ b/spike/src/setup.test.ts@@ -0,0 +1,70 @@+// Purpose: v0.1-5 — switching Codex between the engine and a direct connection: 启用 writes the settings with a+// backup, 停用 gives back the very same files; only the panel may switch, never the model; and the plugin counts as+// gone only on clear signs (no folder in Codex's cache, or turned off in config.toml).+// Input: a temporary Codex home and data folder; output: Node test assertions only.++import assert from "node:assert/strict";+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test, { type TestContext } from "node:test";+import { callTool } from "../../plugin/src/plugin-server.ts";+import { connectDirectly, pluginGone, useEngine, usesEngine } from "../../plugin/src/setup.ts";+import { sampleSessions, THREAD } from "./testfixtures.ts";++const CONFIG = 'model = "gpt-6-sol"\n\n[features]\nview_image = true\n\n[plugins."codex-attachment-manager@codex-attachment-manager"]\nenabled = true\n';++function tempHome(t: TestContext): { home: string; data: string } {+ const home = mkdtempSync(join(tmpdir(), "cam-setup-home-"));+ const data = mkdtempSync(join(tmpdir(), "cam-setup-data-"));+ const saved = { CODEX_HOME: process.env.CODEX_HOME, CAM_DATA_DIR: process.env.CAM_DATA_DIR };+ process.env.CODEX_HOME = home;+ process.env.CAM_DATA_DIR = data;+ t.after(() => {+ for (const [name, value] of Object.entries(saved)) if (value === undefined) delete process.env[name]; else process.env[name] = value;+ });+ return { home, data };+}++test("启用 points Codex at the engine with a backup first; 停用 gives back the very same files", (t) => {+ const { home, data } = tempHome(t);+ writeFileSync(join(home, "config.toml"), CONFIG);+ writeFileSync(join(home, ".env"), "OTHER=1\n");+ useEngine(17891);+ assert.equal(usesEngine(), true);+ assert.match(readFileSync(join(home, "config.toml"), "utf8"), /^# >>> codex-attachment-manager[^\n]*\nopenai_base_url = "http:\/\/localhost:17891\/backend-api\/codex"/);+ assert.equal(readdirSync(join(data, "config-backup")).length, 1, "config.toml was copied before the change");+ connectDirectly();+ assert.equal(usesEngine(), false);+ assert.equal(readFileSync(join(home, "config.toml"), "utf8"), CONFIG);+ assert.equal(readFileSync(join(home, ".env"), "utf8"), "OTHER=1\n");+ assert.equal(existsSync(join(home, "config.toml.cam-tmp")), false, "no temporary file is left behind");+});++test("only the panel may switch the setting; a call from the model is refused", (t) => {+ const { home } = tempHome(t);+ writeFileSync(join(home, "config.toml"), CONFIG);+ const { sessionsDir } = sampleSessions();+ const panelMeta = { threadId: THREAD };+ const modelMeta = { "x-codex-turn-metadata": { thread_id: THREAD, turn_id: "t9" } };+ assert.throws(() => callTool("cam_setup", { enable: true }, modelMeta, sessionsDir), /只有用户能启用或停用/);+ assert.equal(usesEngine(), false);+ const on = callTool("cam_setup", { enable: true }, panelMeta, sessionsDir).structuredContent;+ assert.deepEqual(on.setup, { usesEngine: true, changed: "enabled" });+ assert.equal(on.totals.images, 3, "the panel state comes along");+ const off = callTool("cam_setup", { enable: false }, panelMeta, sessionsDir).structuredContent;+ assert.deepEqual(off.setup, { usesEngine: false, changed: "disabled" });+ assert.equal(readFileSync(join(home, "config.toml"), "utf8"), CONFIG);+});++test("the plugin counts as gone only when its cache folder is missing or config.toml turns it off", (t) => {+ const { home } = tempHome(t);+ writeFileSync(join(home, "config.toml"), CONFIG);+ assert.equal(pluginGone(), "removed");+ mkdirSync(join(home, "plugins", "cache", "codex-attachment-manager", "codex-attachment-manager", "0.1.0"), { recursive: true });+ assert.equal(pluginGone(), null);+ writeFileSync(join(home, "config.toml"), CONFIG.replace("enabled = true", "enabled = false"));+ assert.equal(pluginGone(), "disabled");+ writeFileSync(join(home, "config.toml"), 'model = "gpt-6-sol"\n');+ assert.equal(pluginGone(), null, "an entry written some other way is not taken as a removal");+});