Skip to content

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.

feat(platform): macOS、Linux 适配——一份 .mcp.json 通用三个平台,CI 实装冒烟测试

chipfighterd5b721d415d0
diff --git a/.gitattributes b/.gitattributes
index db7e1d2..1d03dbf 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1 +1,5 @@
*.cmd text eol=crlf
+# Shell scripts run on macOS and Linux; a CR would break them even when checked out on Windows.
+*.sh text eol=lf
+plugin/scripts/launch text eol=lf
+cam text eol=lf
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 7cea914..2709eb9 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1,5 +1,5 @@
-# Unit tests on the three platforms Codex runs on. Only Windows is tested by hand, so these runs are the first check
-# that the plugin still starts on macOS and Linux.
+# Unit tests and an install-and-start smoke test on the three platforms Codex runs on. Only Windows is tested by hand,
+# so these runs are the first check that the plugin still starts on macOS and Linux.
name: CI
on:
@@ -33,3 +33,9 @@ jobs:
- name: Unit tests
working-directory: spike
run: node --test
+ # The plugin as a user gets it: Codex's own command line installs it, a Codex thread starts its MCP server
+ # through .mcp.json and the launcher, and the MCP server starts the engine. No login needed.
+ - name: Install the Codex command line
+ run: npm install --global @openai/codex
+ - name: Plugin smoke test
+ run: node spike/src/plugin-smoke.ts
diff --git a/cam b/cam
new file mode 100755
index 0000000..bc61897
--- /dev/null
+++ b/cam
@@ -0,0 +1,5 @@
+#!/bin/sh
+# Purpose: the tool's command line on macOS and Linux without a separate Node install: runs plugin/src/cam.ts with the
+# same Node the plugin uses (the one Codex ships, else node 24+ on PATH). Usage: ./cam install | uninstall | status | ...
+here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
+exec "$here/plugin/scripts/launch" "$here/plugin/src/cam.ts" "$@"
diff --git a/plugin/.mcp.json b/plugin/.mcp.json
index c59076e..f31c184 100644
--- a/plugin/.mcp.json
+++ b/plugin/.mcp.json
@@ -1,8 +1,8 @@
{
"mcpServers": {
"codex_attachment_manager": {
- "command": "cmd.exe",
- "args": ["/d", "/s", "/c", "call", "./scripts/launch.cmd", "./src/plugin-server.ts"],
+ "command": "./scripts/launch",
+ "args": ["./src/plugin-server.ts"],
"cwd": ".",
"default_tools_approval_mode": "approve",
"env_vars": [
@@ -11,6 +11,8 @@
"CAM_ENGINE_PORT",
"CODEX_MCP_NODE_PATH",
"CODEX_BROWSER_USE_NODE_PATH",
+ "CODEX_ELECTRON_RESOURCES_PATH",
+ "CODEX_CLI_PATH",
"HTTPS_PROXY",
"HTTP_PROXY",
"ALL_PROXY",
@@ -19,6 +21,9 @@
"http_proxy",
"all_proxy",
"no_proxy",
+ "HOME",
+ "XDG_CACHE_HOME",
+ "XDG_DATA_HOME",
"USERPROFILE",
"LOCALAPPDATA",
"APPDATA",
diff --git a/plugin/scripts/launch b/plugin/scripts/launch
new file mode 100755
index 0000000..4f6b88d
--- /dev/null
+++ b/plugin/scripts/launch
@@ -0,0 +1,40 @@
+#!/bin/sh
+# Purpose: v0.1 - start one of the plugin's scripts (the MCP server, the command line) on macOS and Linux with a Node
+# that runs TypeScript directly (Node 24 or newer). Tries the Node runtimes that Codex ships first, then a node on PATH.
+# Codex runs this file for the plugin's MCP server (.mcp.json: ./scripts/launch); on Windows it finds launch.cmd.
+# Input: the script to run and its arguments. Output: whatever the script prints (the MCP stdio stream).
+set -eu
+
+if [ "$#" -lt 1 ]; then
+ printf '%s\n' 'codex-attachment-manager: missing script path' >&2
+ exit 64
+fi
+
+# Apps started from the desktop get a short PATH.
+PATH="${PATH:-/usr/bin:/bin}:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin"
+export PATH
+
+cache_root=${XDG_CACHE_HOME:-${HOME:-}/.cache}
+codex_dir=
+case "${CODEX_CLI_PATH:-}" in
+ */*) codex_dir=${CODEX_CLI_PATH%/*} ;;
+esac
+for candidate in \
+ "${CODEX_MCP_NODE_PATH:-}" \
+ "${CODEX_BROWSER_USE_NODE_PATH:-}" \
+ "${CODEX_ELECTRON_RESOURCES_PATH:+$CODEX_ELECTRON_RESOURCES_PATH/cua_node/bin/node}" \
+ "${codex_dir:+$codex_dir/cua_node/bin/node}" \
+ "$cache_root/codex-runtimes/codex-primary-runtime/dependencies/node/bin/node"
+do
+ if [ -n "$candidate" ] && [ -x "$candidate" ]; then
+ exec "$candidate" "$@"
+ fi
+done
+
+# A node of the user's own must be new enough to run TypeScript directly.
+if node_path=$(command -v node 2>/dev/null) && "$node_path" -e 'process.exit(Number(process.versions.node.split(".")[0]) >= 24 ? 0 : 1)' 2>/dev/null; then
+ exec "$node_path" "$@"
+fi
+
+printf '%s\n' 'codex-attachment-manager: no Node 24 or newer found; update Codex or install Node 24' >&2
+exit 127
diff --git a/plugin/scripts/launch.cmd b/plugin/scripts/launch.cmd
index 11f853c..180fc33 100644
--- a/plugin/scripts/launch.cmd
+++ b/plugin/scripts/launch.cmd
@@ -1,7 +1,8 @@
@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).
+rem Purpose: P5 - start one of the plugin's scripts (the MCP server, the command line) with a Node that runs TypeScript
+rem directly (Node 24 or newer). Tries the Node runtimes that Codex ships first, then a node on PATH.
+rem Codex finds this file for the plugin's MCP server (.mcp.json: ./scripts/launch); scripts/launch is the macOS and
+rem Linux version. Input: the script to run and its arguments. Output: whatever the script prints (the MCP stdio stream).
setlocal
if "%~1"=="" (
@@ -17,6 +18,14 @@ if defined CODEX_BROWSER_USE_NODE_PATH if exist "%CODEX_BROWSER_USE_NODE_PATH%"
"%CODEX_BROWSER_USE_NODE_PATH%" %*
exit /b
)
+if defined CODEX_ELECTRON_RESOURCES_PATH if exist "%CODEX_ELECTRON_RESOURCES_PATH%\cua_node\bin\node.exe" (
+ "%CODEX_ELECTRON_RESOURCES_PATH%\cua_node\bin\node.exe" %*
+ exit /b
+)
+if defined CODEX_CLI_PATH for %%I in ("%CODEX_CLI_PATH%") do if exist "%%~dpIcua_node\bin\node.exe" (
+ "%%~dpIcua_node\bin\node.exe" %*
+ 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
@@ -26,11 +35,14 @@ if defined USERPROFILE if exist "%USERPROFILE%\.cache\codex-runtimes\codex-prima
exit /b
)
+rem A node of the user's own must be new enough to run TypeScript directly.
where node >nul 2>&1
-if not errorlevel 1 (
- node %*
- exit /b
-)
+if errorlevel 1 goto missing
+node -e "process.exit(Number(process.versions.node.split('.')[0]) >= 24 ? 0 : 1)" >nul 2>&1
+if errorlevel 1 goto missing
+node %*
+exit /b
-echo codex-attachment-manager: no Node runtime found; update Codex or install Node 24 1>&2
+:missing
+echo codex-attachment-manager: no Node 24 or newer found; update Codex or install Node 24 1>&2
exit /b 127
diff --git a/plugin/src/cam.ts b/plugin/src/cam.ts
index 33ae22f..544a931 100644
--- a/plugin/src/cam.ts
+++ b/plugin/src/cam.ts
@@ -81,11 +81,17 @@ function codex(cli: string, args: string[]): string {
return output;
}
+// How Codex starts the plugin's MCP server (.mcp.json: ./scripts/launch in the plugin folder): on Windows it finds
+// launch.cmd, which only cmd.exe runs; on macOS and Linux it runs the shell script itself (so it must be executable).
+export const launcher = (script: string, platform: NodeJS.Platform = process.platform): [string, string[]] =>
+ platform === "win32" ? ["cmd.exe", ["/d", "/s", "/c", "call", "./scripts/launch.cmd", script]] : ["./scripts/launch", [script]];
+
// 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"], {
+ const [command, args] = launcher("./src/plugin-server.ts");
+ const child = spawn(command, args, {
cwd: dir, windowsHide: true, stdio: ["pipe", "pipe", "pipe"],
env: { ...process.env, CAM_NO_ENGINE: "1", CAM_DATA_DIR: scratch },
});
@@ -148,7 +154,7 @@ async function main(): Promise<void> {
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 桌面版,并至少打开过一次。");
+ 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 });
diff --git a/plugin/src/codexcli.ts b/plugin/src/codexcli.ts
index 66dff7d..51e6278 100644
--- a/plugin/src/codexcli.ts
+++ b/plugin/src/codexcli.ts
@@ -1,6 +1,8 @@
// 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.
+// (copying them into Codex's plugin cache). The desktop app ships one; a codex installed on its own is the fallback.
+// v0.1: macOS and Linux as well.
+// Input: CODEX_CLI_PATH; the desktop app's copy (Windows: %LOCALAPPDATA%\OpenAI\Codex\bin\<build>\codex.exe, macOS:
+// <app>/Contents/Resources/codex); ~/.local/bin/codex (Codex's own installer); 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";
@@ -8,26 +10,36 @@ 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") {
+// Where a desktop app or Codex's installer puts the command line, most specific first. The Linux desktop app sets
+// CODEX_CLI_PATH for the plugins it starts; from a terminal it is found on PATH.
+export function cliCandidates(env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform, home = homedir()): string[] {
+ if (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 root = join(env.LOCALAPPDATA || join(home, "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];
+ return builds.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs);
}
+ const apps = platform === "darwin" ? ["/Applications", join(home, "Applications")].flatMap((dir) => ["ChatGPT.app", "Codex.app"].map((app) => join(dir, app, "Contents", "Resources", "codex"))) : [];
+ return [...apps, join(home, ".local", "bin", "codex")];
+}
+
+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;
+ const found = cliCandidates(env).find((file) => existsSync(file));
+ if (found) return found;
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;
+ const windows = process.platform === "win32";
+ const onPath = execFileSync(windows ? "where" : "which", ["codex"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
+ // On Windows, npm also leaves an extensionless shell script next to its codex.cmd.
+ return onPath.split(/\r?\n/).map((line) => line.trim()).find((line) => line && (!windows || /\.(exe|cmd)$/i.test(line))) ?? null;
} catch {
return null;
}
}
-export function runCodex(cli: string, args: string[]): { ok: boolean; output: string } {
+export function runCodex(cli: string, args: string[], env: NodeJS.ProcessEnv = process.env): { 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 });
+ const result = spawnSync(shim ? "cmd.exe" : cli, shim ? ["/d", "/s", "/c", cli, ...args] : args, { encoding: "utf8", windowsHide: true, env });
return { ok: result.status === 0, output: `${result.stdout ?? ""}${result.stderr ?? ""}`.trim() };
}
diff --git a/plugin/src/codexconfig.ts b/plugin/src/codexconfig.ts
index e7e0ecb..d2a2d3e 100644
--- a/plugin/src/codexconfig.ts
+++ b/plugin/src/codexconfig.ts
@@ -4,7 +4,7 @@
// client (which ignores respect_system_proxy before upstream #47742) reaches the local proxy too.
// Nothing else in either file is touched.
// 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.
+// Input: file texts. Codex home comes from CODEX_HOME or ~/.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";
@@ -155,9 +155,10 @@ export function noProxyStatus(text: string): { managed: boolean; value: string |
return { managed: begin >= 0, value: line ? line.slice(line.indexOf("=") + 1).trim() : null, conflict: base.body.split(base.eol).some((l) => NO_PROXY_LINE.test(l)) };
}
-// What the desktop app inherits: the user's variable overrides the machine's.
+// What the desktop app inherits: on Windows the user's variable overrides the machine's. On macOS and Linux there is
+// no such store; the environment of the shell that runs the command is the closest guess (v0.1).
export function persistedEnv(name: string): string | null {
- if (process.platform !== "win32") return null;
+ if (process.platform !== "win32") return process.env[name] || process.env[name.toLowerCase()] || null;
for (const key of ["HKCU\\Environment", "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"]) {
try {
const out = execFileSync("reg", ["query", key, "/v", name], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
diff --git a/plugin/src/engine.ts b/plugin/src/engine.ts
index dd0aeb6..dc99369 100644
--- a/plugin/src/engine.ts
+++ b/plugin/src/engine.ts
@@ -1,9 +1,10 @@
// Purpose: P3-2 — lifecycle of the engine (the local proxy): one instance per machine, `ensure` starts it in the
// background when it is not running, and it exits by itself once no Codex process is left.
-// Input: the port; process lists from `tasklist` on Windows. Output: health checks, a detached engine process.
+// Input: the port; process lists from `tasklist` on Windows and `ps` on macOS and Linux. Output: health checks, a
+// detached engine process.
import { execFile, spawn } from "node:child_process";
-import { dirname, join } from "node:path";
+import { dirname, join, posix } from "node:path";
import { fileURLToPath } from "node:url";
export const ENGINE_SERVICE = "codex-attachment-manager";
@@ -54,12 +55,19 @@ export function countCodexProcesses(tasklistCsv: string): number {
return tasklistCsv.split(/\r?\n/).filter((line) => /^"codex\.exe",/i.test(line.trim())).length;
}
+// v0.1: `ps -A -o comm=` prints one executable per line: the bare name on Linux, the full path on macOS. Codex's
+// command line and the app-server inside the desktop app are both named `codex`.
+export function countCodexInPs(psOutput: string): number {
+ return psOutput.split(/\r?\n/).filter((line) => posix.basename(line.trim()) === "codex").length;
+}
+
export function listCodexProcesses(): Promise<number> {
- if (process.platform !== "win32") return Promise.resolve(1);
+ const windows = process.platform === "win32";
+ const [file, args] = windows ? ["tasklist", ["/FI", "IMAGENAME eq codex.exe", "/FO", "CSV", "/NH"]] : ["ps", ["-A", "-o", "comm="]];
return new Promise((resolve) => {
- execFile("tasklist", ["/FI", "IMAGENAME eq codex.exe", "/FO", "CSV", "/NH"], { windowsHide: true }, (error, stdout) => {
+ execFile(file, args, { windowsHide: true }, (error, stdout) => {
// If the check itself fails, assume Codex is still there rather than shutting down under it.
- resolve(error ? 1 : countCodexProcesses(stdout));
+ resolve(error ? 1 : windows ? countCodexProcesses(stdout) : countCodexInPs(stdout));
});
});
}
diff --git a/plugin/src/paths.ts b/plugin/src/paths.ts
index d3bab18..d85fb96 100644
--- a/plugin/src/paths.ts
+++ b/plugin/src/paths.ts
@@ -1,17 +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.
+// ~/Library/Application Support/codex-attachment-manager on macOS, $XDG_DATA_HOME (or ~/.local/share)/
+// codex-attachment-manager on Linux. 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();
+export function dataDir(env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform, home = homedir()): string {
+ const chosen = 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");
+ if (platform === "win32") return join(env.LOCALAPPDATA || join(home, "AppData", "Local"), "codex-attachment-manager");
+ if (platform === "darwin") return join(home, "Library", "Application Support", "codex-attachment-manager");
+ return join(env.XDG_DATA_HOME || join(home, ".local", "share"), "codex-attachment-manager");
}
export const selectionDirOf = (root = dataDir()) => join(root, "selection");
diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.ts
index 930486c..f7a62a4 100644
--- a/plugin/src/proxy.ts
+++ b/plugin/src/proxy.ts
@@ -5,7 +5,7 @@
// WebSocket turn that kept running after images were unchecked (it cannot be rewritten).
// Only metadata is logged (never auth headers or conversation content).
// Input: [--port 17891] [--stay (no auto-exit)] [--force-http] [--dump-requests (synthetic test threads only)];
-// the outbound proxy is taken from HTTPS_PROXY/HTTP_PROXY or the Windows proxy settings.
+// the outbound proxy is taken from HTTPS_PROXY/HTTP_PROXY or the system proxy settings (Windows, macOS).
// Output: responses streamed back to Codex; <data dir>/proxy/<date>.jsonl; <data dir>/state/requests/<thread>.json.
import { execFileSync } from "node:child_process";
@@ -31,12 +31,13 @@ type Json = Record<string, any>;
const UPSTREAM_HOST = "chatgpt.com";
const HOP_BY_HOP = new Set(["connection", "keep-alive", "proxy-connection", "transfer-encoding", "te", "trailer", "upgrade", "host"]);
-// Outbound proxy: environment first, then the Windows per-user setting; NO_PROXY is honoured for the upstream host.
-export function outboundProxy(env = process.env, windowsSetting = readWindowsProxy): { host: string; port: number } | null {
+// Outbound proxy: environment first, then the system setting (Windows per-user, macOS); NO_PROXY is honoured for the
+// upstream host.
+export function outboundProxy(env = process.env, systemSetting = readSystemProxy): { host: string; port: number } | null {
const noProxy = (env.NO_PROXY ?? env.no_proxy ?? "").split(",").map((s) => s.trim().replace(/^\./, "")).filter(Boolean);
if (noProxy.some((entry) => entry === "*" || UPSTREAM_HOST === entry || UPSTREAM_HOST.endsWith(`.${entry}`))) return null;
const fromEnv = env.HTTPS_PROXY ?? env.https_proxy ?? env.HTTP_PROXY ?? env.http_proxy;
- let value = fromEnv || windowsSetting();
+ let value = fromEnv || systemSetting();
if (!value) return null;
// Windows may store per-protocol entries: "http=host:port;https=host:port".
if (value.includes("=")) value = /https=([^;]+)/.exec(value)?.[1] ?? /http=([^;]+)/.exec(value)?.[1] ?? "";
@@ -45,15 +46,28 @@ export function outboundProxy(env = process.env, windowsSetting = readWindowsPro
return { host: url.hostname, port: Number(url.port || 80) };
}
-function readWindowsProxy(): string | null {
- if (process.platform !== "win32") return null;
+function readSystemProxy(): string | null {
try {
- const out = execFileSync("reg", ["query", "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"], { encoding: "utf8" });
- if (!/ProxyEnable\s+REG_DWORD\s+0x1/.test(out)) return null;
- return /ProxyServer\s+REG_SZ\s+(\S+)/.exec(out)?.[1] ?? null;
- } catch {
- return null;
+ if (process.platform === "win32") {
+ const out = execFileSync("reg", ["query", "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"], { encoding: "utf8" });
+ if (!/ProxyEnable\s+REG_DWORD\s+0x1/.test(out)) return null;
+ return /ProxyServer\s+REG_SZ\s+(\S+)/.exec(out)?.[1] ?? null;
+ }
+ if (process.platform === "darwin") return macProxy(execFileSync("scutil", ["--proxy"], { encoding: "utf8" }));
+ } catch { /* no setting readable: connect directly */ }
+ return null;
+}
+
+// v0.1: `scutil --proxy` lists the macOS system proxies as "Key : value" lines. Only HTTP(S) proxies are usable here
+// (the engine tunnels with CONNECT); PAC files and SOCKS are not read. Linux has no system setting beyond the
+// environment.
+export function macProxy(scutil: string): string | null {
+ const field = (key: string) => new RegExp(`^\\s*${key}\\s*:\\s*(\\S+)\\s*$`, "m").exec(scutil)?.[1] ?? null;
+ for (const scheme of ["HTTPS", "HTTP"]) {
+ const host = field(`${scheme}Proxy`);
+ if (field(`${scheme}Enable`) === "1" && host) return `${host}:${field(`${scheme}Port`) ?? "80"}`;
}
+ return null;
}
function connectUpstream(via: { host: string; port: number } | null): Promise<tls.TLSSocket> {
diff --git a/spike/src/appserver.ts b/spike/src/appserver.ts
index 1362b96..f26cc3b 100644
--- a/spike/src/appserver.ts
+++ b/spike/src/appserver.ts
@@ -47,7 +47,9 @@ export class AppServer {
this.#onServerRequest = onServerRequest;
const childEnv: Record<string, string | undefined> = { ...process.env, ...env };
for (const [name, value] of Object.entries(childEnv)) if (value === undefined) delete childEnv[name];
- this.#child = spawn(codexPath, ["app-server", ...args], { env: childEnv, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
+ // An npm-installed codex on Windows (as in CI) is a .cmd shim, which only cmd.exe can start.
+ const shim = /\.cmd$/i.test(codexPath);
+ this.#child = spawn(shim ? "cmd.exe" : codexPath, shim ? ["/d", "/s", "/c", codexPath, "app-server", ...args] : ["app-server", ...args], { env: childEnv, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
this.#child.stderr.pipe(this.#log);
this.#exited = new Promise((resolve) => this.#child.on("exit", (code) => resolve(code)));
this.#child.on("exit", (code) => {
diff --git a/spike/src/engine.test.ts b/spike/src/engine.test.ts
index bf895a0..ed3c1b5 100644
--- a/spike/src/engine.test.ts
+++ b/spike/src/engine.test.ts
@@ -1,7 +1,7 @@
// Purpose: P3-2 — engine lifecycle: health identity, Codex process detection, auto-exit after consecutive misses,
// one instance per port (a real engine is started on a spare port with its data in a temporary folder), and the
// per-thread request statistics.
-// Input: synthetic tasklist output and a temporary data folder; output: Node test assertions only.
+// Input: synthetic tasklist and ps output and a temporary data folder; output: Node test assertions only.
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
@@ -10,7 +10,7 @@ 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 "../../plugin/src/engine.ts";
+import { countCodexInPs, 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));
@@ -30,6 +30,13 @@ test("Codex processes are counted from tasklist CSV, in any Windows language", (
assert.equal(countCodexProcesses('"ChatGPT.exe","23816","Console","1","200,000 K"\r\n'), 0);
});
+test("on macOS and Linux, Codex processes are counted from ps by executable name", () => {
+ const mac = "/sbin/launchd\n/Applications/ChatGPT.app/Contents/MacOS/ChatGPT\n/Applications/ChatGPT.app/Contents/Resources/codex\n/Applications/ChatGPT.app/Contents/Frameworks/ChatGPT Helper.app/Contents/MacOS/ChatGPT Helper\n";
+ assert.equal(countCodexInPs(mac), 1);
+ assert.equal(countCodexInPs("systemd\nbash\ncodex\nnode\ncodex\ncodex-code-mode-host\n"), 2);
+ assert.equal(countCodexInPs("systemd\nbash\nnode\n"), 0);
+});
+
test("the engine gives up only after consecutive checks without Codex", async () => {
const run = (counts: number[]) => new Promise<number>((resolve) => {
let calls = 0;
diff --git a/spike/src/platform.test.ts b/spike/src/platform.test.ts
new file mode 100644
index 0000000..f537618
--- /dev/null
+++ b/spike/src/platform.test.ts
@@ -0,0 +1,33 @@
+// Purpose: v0.1 — the places that differ between Windows, macOS and Linux: the data folder, where Codex's command line
+// is looked for, and how the plugin's launcher is started. Each platform is checked on any machine.
+// Input: synthetic environments and home folders; output: Node test assertions only.
+
+import assert from "node:assert/strict";
+import { join } from "node:path";
+import test from "node:test";
+import { launcher } from "../../plugin/src/cam.ts";
+import { cliCandidates } from "../../plugin/src/codexcli.ts";
+import { dataDir } from "../../plugin/src/paths.ts";
+
+const home = join("/", "home", "someone");
+
+test("the data folder follows each platform's convention, and CAM_DATA_DIR wins", () => {
+ assert.equal(dataDir({ LOCALAPPDATA: join("C:", "Users", "someone", "AppData", "Local") }, "win32", home), join("C:", "Users", "someone", "AppData", "Local", "codex-attachment-manager"));
+ assert.equal(dataDir({}, "darwin", home), join(home, "Library", "Application Support", "codex-attachment-manager"));
+ assert.equal(dataDir({}, "linux", home), join(home, ".local", "share", "codex-attachment-manager"));
+ assert.equal(dataDir({ XDG_DATA_HOME: join(home, "data") }, "linux", home), join(home, "data", "codex-attachment-manager"));
+ assert.equal(dataDir({ CAM_DATA_DIR: join(home, "chosen") }, "darwin", home), join(home, "chosen"));
+});
+
+test("Codex's command line is looked for in the desktop app first, then where Codex's installer puts it", () => {
+ const mac = cliCandidates({}, "darwin", home);
+ assert.equal(mac[0], join("/Applications", "ChatGPT.app", "Contents", "Resources", "codex"));
+ assert.ok(mac.includes(join("/Applications", "Codex.app", "Contents", "Resources", "codex")));
+ assert.equal(mac.at(-1), join(home, ".local", "bin", "codex"));
+ assert.deepEqual(cliCandidates({}, "linux", home), [join(home, ".local", "bin", "codex")]);
+});
+
+test("the launcher runs through cmd.exe on Windows and as an executable script elsewhere", () => {
+ assert.deepEqual(launcher("./src/cam.ts", "win32"), ["cmd.exe", ["/d", "/s", "/c", "call", "./scripts/launch.cmd", "./src/cam.ts"]]);
+ assert.deepEqual(launcher("./src/cam.ts", "linux"), ["./scripts/launch", ["./src/cam.ts"]]);
+});
diff --git a/spike/src/plugin-smoke.ts b/spike/src/plugin-smoke.ts
new file mode 100644
index 0000000..0b044ad
--- /dev/null
+++ b/spike/src/plugin-smoke.ts
@@ -0,0 +1,77 @@
+// Purpose: v0.1 — the plugin as a user gets it, on any platform. Codex's own command line installs it from this
+// checkout into a throwaway Codex home; a Codex app-server then starts a thread, which must bring up the plugin's MCP
+// server through .mcp.json and the launcher, list its tools, serve the panel, and start the engine. CI runs this on
+// Windows, macOS and Linux, where nobody has tried the plugin by hand. It never touches the real ~/.codex or the
+// tool's real data folder, and needs no login.
+// Input: a Codex command line (CODEX_CLI_PATH, a desktop app's copy, or codex on PATH); [--port 17893] for the test
+// engine. Output: a JSON summary on stdout, exit code 1 when a check fails; the app-server's stderr in the temp folder.
+
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, statSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { setTimeout as sleep } from "node:timers/promises";
+import { AppServer, type Notification } from "./appserver.ts";
+import { findCodexCli, runCodex } from "../../plugin/src/codexcli.ts";
+import { engineHealth, type Health } from "../../plugin/src/engine.ts";
+import { MARKETPLACE, PLUGIN, PLUGIN_ID, SERVER_NAME } 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", "17893"));
+const version: string = JSON.parse(readFileSync(join(root, "plugin", ".codex-plugin", "plugin.json"), "utf8")).version;
+const TOOLS = ["cam_panel", "cam_set_selection", "cam_image"];
+
+async function main(): Promise<boolean> {
+ const scratch = mkdtempSync(join(tmpdir(), "cam-smoke-"));
+ const [home, data, work] = ["codex-home", "data", "work"].map((name) => join(scratch, name));
+ for (const dir of [home, data, work]) mkdirSync(dir, { recursive: true });
+ const overrides = { CODEX_HOME: home, CAM_DATA_DIR: data, CAM_ENGINE_PORT: String(port) };
+ const cli = findCodexCli();
+ if (!cli) throw new Error("no Codex command line found (set CODEX_CLI_PATH or put codex on PATH)");
+ const summary: Json = { platform: process.platform, cli, codex: runCodex(cli, ["--version"]).output, scratch, checks: {} };
+ const checks: Record<string, boolean> = summary.checks;
+
+ // 1. Installed the way users install it: Codex's command line copies the plugin into its cache.
+ const env = { ...process.env, ...overrides };
+ const steps = [["plugin", "marketplace", "add", root], ["plugin", "add", PLUGIN_ID]].map((args) => ({ args: args.join(" "), ...runCodex(cli, args, env) }));
+ summary.install = steps;
+ const cached = join(home, "plugins", "cache", MARKETPLACE, PLUGIN, version);
+ checks.installedIntoCache = steps.every((step) => step.ok) && existsSync(join(cached, ".mcp.json"));
+ // Codex runs ./scripts/launch itself on macOS and Linux, so the copy must keep the executable bit.
+ if (process.platform !== "win32") checks.launcherExecutable = existsSync(join(cached, "scripts", "launch")) && (statSync(join(cached, "scripts", "launch")).mode & 0o111) !== 0;
+
+ // 2. A thread brings the plugin's MCP server up, as in the desktop app.
+ const server = new AppServer(cli, [], overrides, join(scratch, "app-server.log"));
+ let health: Health | null = null;
+ try {
+ await server.initialize();
+ const { thread } = await server.request<{ thread: Json }>("thread/start", { cwd: work, approvalPolicy: "never", sandbox: "read-only", ephemeral: true });
+ const ours = (n: Notification) => n.method === "mcpServer/startupStatus/updated" && String(n.params.name).endsWith(SERVER_NAME);
+ const settled = await server.waitFor((n) => ours(n) && n.params.status !== "starting", 90_000).catch(() => null);
+ summary.startup = server.notifications.filter(ours).map((n) => ({ name: n.params.name, status: n.params.status, error: n.params.error }));
+ checks.serverReady = settled?.params.status === "ready";
+ const listed = await server.request<{ data: Json[] }>("mcpServerStatus/list", { threadId: thread.id }, 60_000);
+ const status = listed.data.find((entry) => String(entry.name).endsWith(SERVER_NAME));
+ summary.server = status ? { name: status.name, pluginId: status.pluginId, serverInfo: status.serverInfo?.name ?? null, tools: Object.keys(status.tools ?? {}), resources: status.resources?.map((r: Json) => r.uri) } : null;
+ checks.toolsListed = TOOLS.every((tool) => summary.server?.tools.includes(tool));
+ checks.panelListed = !!summary.server?.resources?.includes("ui://codex-attachment-manager/panel.html");
+
+ // 3. The MCP server starts the engine, which answers on loopback.
+ for (let i = 0; i < 40 && !health; i++) {
+ health = await engineHealth(port);
+ if (!health) await sleep(250);
+ }
+ summary.engine = health ? { pid: health.pid, port: health.port } : null;
+ checks.engineStarted = !!health;
+ } finally {
+ await server.stop();
+ // On Windows the engine ends with the MCP server's job; elsewhere it would outlive this test.
+ 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/proxy.test.ts b/spike/src/proxy.test.ts
index af20c1d..481a0fb 100644
--- a/spike/src/proxy.test.ts
+++ b/spike/src/proxy.test.ts
@@ -8,7 +8,7 @@ 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 "../../plugin/src/proxy.ts";
+import { describeBody, hasUnchecked, hasUnsafeInteger, imageSizesOf, macProxy, outboundProxy, rewriteBody, requestIdentity } from "../../plugin/src/proxy.ts";
import { writeSelection } from "../../plugin/src/selection.ts";
import { png } from "./testkit.ts";
@@ -21,6 +21,14 @@ test("outbound proxy comes from the environment, then Windows settings", () => {
assert.equal(outboundProxy({}, none), null);
});
+test("the macOS system proxy is read from scutil: HTTPS first, then HTTP, only when enabled", () => {
+ const scutil = (lines: string[]) => `<dictionary> {\n ExceptionsList : <array> {\n 0 : *.local\n }\n${lines.map((line) => ` ${line}\n`).join("")}}\n`;
+ assert.equal(macProxy(scutil(["HTTPEnable : 1", "HTTPPort : 8080", "HTTPProxy : 10.0.0.1", "HTTPSEnable : 1", "HTTPSPort : 7890", "HTTPSProxy : 127.0.0.1"])), "127.0.0.1:7890");
+ assert.equal(macProxy(scutil(["HTTPEnable : 1", "HTTPPort : 8080", "HTTPProxy : 10.0.0.1", "HTTPSEnable : 0"])), "10.0.0.1:8080");
+ assert.equal(macProxy(scutil(["HTTPSEnable : 0", "SOCKSEnable : 1", "SOCKSPort : 1080", "SOCKSProxy : 127.0.0.1"])), null);
+ assert.deepEqual(outboundProxy({}, () => macProxy(scutil(["HTTPSEnable : 1", "HTTPSPort : 7890", "HTTPSProxy : 127.0.0.1"]))), { host: "127.0.0.1", port: 7890 });
+});
+
test("NO_PROXY entries covering the upstream host mean a direct connection", () => {
for (const entry of ["chatgpt.com", ".chatgpt.com", "*"]) {
assert.equal(outboundProxy({ HTTPS_PROXY: "http://127.0.0.1:8888", NO_PROXY: `localhost,${entry}` }, none), null);