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(spike): P3-2 引擎——全机单实例、ensure 后台拉起、Codex 退出后自动退出、按任务记录最近一次请求

chipfighter11e5bb93a688
diff --git a/spike/src/engine.test.ts b/spike/src/engine.test.ts
new file mode 100644
index 0000000..89a8229
--- /dev/null
+++ b/spike/src/engine.test.ts
@@ -0,0 +1,66 @@
+// 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.
+
+import assert from "node:assert/strict";
+import { execFile } from "node:child_process";
+import { existsSync, mkdtempSync, readFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+import { countCodexProcesses, engineHealth, ensureEngine, isEngineHealth, watchForCodex } from "./engine.ts";
+import { recordRequest } from "./proxy.ts";
+
+const here = dirname(fileURLToPath(import.meta.url));
+
+test("only our own engine counts as healthy", () => {
+ assert.equal(isEngineHealth({ ok: true, service: "codex-attachment-manager", pid: 1 }), true);
+ assert.equal(isEngineHealth({ ok: true, service: "something-else", pid: 1 }), false);
+ assert.equal(isEngineHealth({ ok: true }), false);
+ assert.equal(isEngineHealth(null), false);
+});
+
+test("Codex processes are counted from tasklist CSV, in any Windows language", () => {
+ const two = '"codex.exe","23984","Console","1","123,456 K"\r\n"codex.exe","11111","Console","1","9,000 K"\r\n';
+ assert.equal(countCodexProcesses(two), 2);
+ assert.equal(countCodexProcesses("INFO: No tasks are running which match the specified criteria.\r\n"), 0);
+ assert.equal(countCodexProcesses("信息: 没有运行的任务匹配指定标准。\r\n"), 0);
+ assert.equal(countCodexProcesses('"ChatGPT.exe","23816","Console","1","200,000 K"\r\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;
+ const stop = watchForCodex(() => resolve(calls), { intervalMs: 5, misses: 2, count: async () => counts[Math.min(calls++, counts.length - 1)] });
+ setTimeout(() => { stop(); resolve(-1); }, 500);
+ });
+ assert.equal(await run([1, 0, 0]), 3);
+ assert.equal(await run([0, 1, 0, 1, 0, 0]), 6, "a Codex restart in between resets the count");
+ assert.equal(await run([1]), -1, "never exits while Codex runs");
+});
+
+test("ensure starts one engine; a second start on the same port leaves it alone", async (t) => {
+ const port = 20000 + Math.floor(Math.random() * 20000);
+ process.env.CAM_DATA_DIR = mkdtempSync(join(tmpdir(), "cam-engine-"));
+ t.after(() => { delete process.env.CAM_DATA_DIR; });
+ const first = await ensureEngine({ port, extraArgs: ["--stay"] });
+ assert.equal(first.state, "started");
+ t.after(() => { try { process.kill(first.health!.pid); } catch { /* already gone */ } });
+ const again = await ensureEngine({ port });
+ assert.deepEqual([again.state, again.health?.pid], ["running", first.health!.pid]);
+ const second = await new Promise<string>((resolve) => execFile(process.execPath, [join(here, "proxy.ts"), "--port", String(port), "--stay"], (_error, stdout) => resolve(stdout)));
+ assert.match(second, /"alreadyRunning":true/);
+ assert.equal((await engineHealth(port))?.pid, first.health!.pid);
+});
+
+test("request statistics are written per thread, and only for real thread ids", () => {
+ const dir = mkdtempSync(join(tmpdir(), "cam-stats-"));
+ const thread = "01a0d301-0000-7000-8000-000000000001";
+ recordRequest(thread, { at: "2026-09-24T12:00:00Z", images: 3 }, dir);
+ assert.equal(JSON.parse(readFileSync(join(dir, `${thread}.json`), "utf8")).images, 3);
+ recordRequest("../escape", { images: 1 }, dir);
+ recordRequest(null, { images: 1 }, dir);
+ assert.equal(existsSync(join(dir, "..", "escape.json")), false);
+});
diff --git a/spike/src/engine.ts b/spike/src/engine.ts
new file mode 100644
index 0000000..dd0aeb6
--- /dev/null
+++ b/spike/src/engine.ts
@@ -0,0 +1,78 @@
+// 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.
+
+import { execFile, spawn } from "node:child_process";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+export const ENGINE_SERVICE = "codex-attachment-manager";
+export const DEFAULT_PORT = 17891;
+const here = dirname(fileURLToPath(import.meta.url));
+
+export type Health = { ok: true; service: string; pid: number; startedAt: string; port: number };
+
+export function isEngineHealth(value: unknown): value is Health {
+ const health = value as Partial<Health> | null;
+ return !!health && health.ok === true && health.service === ENGINE_SERVICE && typeof health.pid === "number";
+}
+
+// Loopback only, and never through a system proxy: plain http.get on 127.0.0.1.
+export async function engineHealth(port = DEFAULT_PORT, timeoutMs = 800): Promise<Health | null> {
+ try {
+ const response = await fetch(`http://127.0.0.1:${port}/__cam/health`, { signal: AbortSignal.timeout(timeoutMs) });
+ const body = await response.json();
+ return isEngineHealth(body) ? body : null;
+ } catch {
+ return null;
+ }
+}
+
+// Detached and hidden, so it outlives whoever asked for it (a plugin server instance, the CLI).
+export function spawnEngine(port = DEFAULT_PORT, extraArgs: string[] = []): number | undefined {
+ const child = spawn(process.execPath, [join(here, "proxy.ts"), "--port", String(port), ...extraArgs], { detached: true, stdio: "ignore", windowsHide: true });
+ child.unref();
+ return child.pid;
+}
+
+export async function ensureEngine(options: { port?: number; waitMs?: number; extraArgs?: string[] } = {}): Promise<{ state: "running" | "started" | "failed"; health: Health | null }> {
+ const port = options.port ?? DEFAULT_PORT;
+ const existing = await engineHealth(port);
+ if (existing) return { state: "running", health: existing };
+ spawnEngine(port, options.extraArgs);
+ const deadline = Date.now() + (options.waitMs ?? 8000);
+ while (Date.now() < deadline) {
+ await new Promise((resolve) => setTimeout(resolve, 150));
+ const health = await engineHealth(port);
+ if (health) return { state: "started", health };
+ }
+ return { state: "failed", health: null };
+}
+
+// `tasklist /FO CSV /NH` prints one quoted CSV row per process, or an INFO line when nothing matches.
+export function countCodexProcesses(tasklistCsv: string): number {
+ return tasklistCsv.split(/\r?\n/).filter((line) => /^"codex\.exe",/i.test(line.trim())).length;
+}
+
+export function listCodexProcesses(): Promise<number> {
+ if (process.platform !== "win32") return Promise.resolve(1);
+ return new Promise((resolve) => {
+ execFile("tasklist", ["/FI", "IMAGENAME eq codex.exe", "/FO", "CSV", "/NH"], { 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));
+ });
+ });
+}
+
+// Exit only after `misses` checks in a row found no Codex, so a Codex restart does not stop the engine.
+export function watchForCodex(onGone: () => void, options: { intervalMs?: number; misses?: number; count?: () => Promise<number> } = {}): () => void {
+ const count = options.count ?? listCodexProcesses;
+ const needed = options.misses ?? 2;
+ let missed = 0;
+ const timer = setInterval(async () => {
+ missed = (await count()) > 0 ? 0 : missed + 1;
+ if (missed >= needed) { clearInterval(timer); onGone(); }
+ }, options.intervalMs ?? 15_000);
+ timer.unref();
+ return () => clearInterval(timer);
+}
diff --git a/spike/src/paths.ts b/spike/src/paths.ts
new file mode 100644
index 0000000..f99bd6d
--- /dev/null
+++ b/spike/src/paths.ts
@@ -0,0 +1,14 @@
+// Purpose: one place for where the tool keeps its own data (selection state, request statistics, logs).
+// Input: CAM_DATA_DIR when set; otherwise the repository's git-ignored local/ folder (spike phase).
+// Output: absolute directory paths. Nothing here writes to ~/.codex.
+
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+export function dataDir(): string {
+ return process.env.CAM_DATA_DIR?.trim() || join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");
+}
+
+export const selectionDirOf = (root = dataDir()) => join(root, "selection");
+export const requestStatsDirOf = (root = dataDir()) => join(root, "state", "requests");
+export const proxyLogDirOf = (root = dataDir()) => join(root, "proxy");
diff --git a/spike/src/proxy.ts b/spike/src/proxy.ts
index acf3e87..53bc089 100644
--- a/spike/src/proxy.ts
+++ b/spike/src/proxy.ts
@@ -1,21 +1,25 @@
-// Purpose: P1-2 — transparent local proxy between Codex and the ChatGPT backend. HTTP requests and WebSocket
-// upgrades are forwarded byte for byte; only metadata is logged (never auth headers or conversation content).
-// Input: [--port 17891] [--force-http] [--dump-requests (synthetic test threads only)]; the outbound proxy is taken
-// from HTTPS_PROXY/HTTP_PROXY or the Windows proxy settings.
-// Output: responses streamed back to Codex; one JSON line per request in local/proxy/<date>.jsonl.
+// Purpose: the engine — local proxy between Codex and the ChatGPT backend. P1: HTTP requests and WebSocket upgrades
+// are forwarded byte for byte. P2: requests of threads with unchecked images are rewritten. P3: one instance per
+// machine, exits once no Codex process is left, and keeps per-thread statistics of the latest request.
+// 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.
+// Output: responses streamed back to Codex; <data dir>/proxy/<date>.jsonl; <data dir>/state/requests/<thread>.json.
import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
-import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
+import { appendFileSync, mkdirSync, renameSync, writeFileSync } from "node:fs";
import http, { type IncomingHttpHeaders } from "node:http";
import net from "node:net";
-import { dirname, join, resolve } from "node:path";
+import { join } from "node:path";
import type { Duplex } from "node:stream";
import tls from "node:tls";
-import { fileURLToPath, pathToFileURL } from "node:url";
+import { pathToFileURL } from "node:url";
import zlib from "node:zlib";
import { codexHome } from "./codexconfig.ts";
+import { DEFAULT_PORT, ENGINE_SERVICE, engineHealth, watchForCodex } from "./engine.ts";
import type { ImageRef } from "./images.ts";
+import { dataDir, proxyLogDirOf, requestStatsDirOf } from "./paths.ts";
import { rewriteItems, type Described } from "./rewrite.ts";
import { readSelection, selectionDir } from "./selection.ts";
import { loadThreadIndex, pixelHashOf, type ThreadIndex } from "./thread-index.ts";
@@ -23,7 +27,7 @@ import { loadThreadIndex, pixelHashOf, type ThreadIndex } from "./thread-index.t
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"]);
-const localRoot = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");
+const THREAD_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
// 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 {
@@ -121,8 +125,18 @@ export function describeBody(path: string, json: Json): Json {
}
function log(entry: Json): void {
- mkdirSync(join(localRoot, "proxy"), { recursive: true });
- appendFileSync(join(localRoot, "proxy", `${new Date().toISOString().slice(0, 10)}.jsonl`), `${JSON.stringify(entry)}\n`);
+ const dir = proxyLogDirOf();
+ mkdirSync(dir, { recursive: true });
+ appendFileSync(join(dir, `${new Date().toISOString().slice(0, 10)}.jsonl`), `${JSON.stringify(entry)}\n`);
+}
+
+// P3: the latest /responses request of each thread, for the panel's "what was sent" view. Metadata only.
+export function recordRequest(threadId: string | null, stats: Json, dir = requestStatsDirOf()): void {
+ if (!threadId || !THREAD_ID.test(threadId)) return;
+ mkdirSync(dir, { recursive: true });
+ const file = join(dir, `${threadId}.json`);
+ writeFileSync(`${file}.tmp`, JSON.stringify(stats, null, 2));
+ renameSync(`${file}.tmp`, file);
}
// P2-1 debugging aid for synthetic test threads only: the request with every inline image reduced to its hash and size.
@@ -193,15 +207,29 @@ export function rewriteBody(original: Buffer, encoding: string | undefined, thre
return { body, report: { ...summary, decodedBefore: decoded.length, decodedAfter: next.length, encodedBefore: original.length, encodedAfter: body.length } };
}
-function main(): void {
+async function main(): Promise<void> {
const portIndex = process.argv.indexOf("--port");
- const port = Number(portIndex >= 0 ? process.argv[portIndex + 1] : 17891);
+ const port = Number(portIndex >= 0 ? process.argv[portIndex + 1] : DEFAULT_PORT);
+ // One engine per machine: a second start leaves the running one alone.
+ const running = await engineHealth(port);
+ if (running) {
+ console.log(JSON.stringify({ alreadyRunning: true, pid: running.pid, port }));
+ return;
+ }
// --force-http answers every Responses WebSocket upgrade with 426, Codex's own signal to use HTTP for the session.
const forceHttp = process.argv.includes("--force-http");
- const dumpDir = process.argv.includes("--dump-requests") ? join(localRoot, "p2", "requests") : null;
+ const dumpDir = process.argv.includes("--dump-requests") ? join(dataDir(), "p2", "requests") : null;
const sessionsDir = join(codexHome(), "sessions");
const via = outboundProxy();
+ const startedAt = new Date().toISOString();
let sequence = 0;
+ log({ at: startedAt, event: "engine-start", pid: process.pid, port });
+ if (!process.argv.includes("--stay")) {
+ watchForCodex(() => {
+ log({ at: new Date().toISOString(), event: "engine-exit", pid: process.pid, reason: "no Codex process left" });
+ process.exit(0);
+ });
+ }
// Open WebSocket connections per thread. Over WebSocket Codex only sends new items and the server keeps the rest,
// so a thread with unchecked images must move to HTTP: its idle connections are closed, and its next upgrade gets 426.
const live = new Map<string, Set<{ client: Duplex; socket: tls.TLSSocket; last: number; closedForSelection: boolean }>>();
@@ -220,7 +248,7 @@ function main(): void {
const onRequest = (req: http.IncomingMessage, res: http.ServerResponse) => {
if (req.url === "/__cam/health") {
res.writeHead(200, { "content-type": "application/json" });
- res.end(JSON.stringify({ ok: true, upstream: UPSTREAM_HOST, via: via ? `${via.host}:${via.port}` : "direct" }));
+ res.end(JSON.stringify({ ok: true, service: ENGINE_SERVICE, pid: process.pid, startedAt, port, upstream: UPSTREAM_HOST, via: via ? `${via.host}:${via.port}` : "direct" }));
return;
}
const id = ++sequence;
@@ -252,7 +280,9 @@ function main(): void {
}
} catch { details = { kind: "unparsed" }; }
}
- log({ at: new Date(started).toISOString(), id, transport: "http", method: req.method, path, status, requestBytes, decodedBytes: decoded?.length ?? null, contentEncoding: req.headers["content-encoding"] ?? null, responseBytes, ms: Date.now() - started, ...identity, ...details, ...extra, error: error ?? null });
+ const entry = { at: new Date(started).toISOString(), id, transport: "http", method: req.method, path, status, requestBytes, decodedBytes: decoded?.length ?? null, contentEncoding: req.headers["content-encoding"] ?? null, responseBytes, ms: Date.now() - started, ...identity, ...details, ...extra, error: error ?? null };
+ log(entry);
+ if (/\/responses$/.test(path)) recordRequest(identity.threadId, entry);
};
// body === null streams the request through unchanged.
const send = (headers: Record<string, string | string[]>, body: Buffer | null) => connectUpstream(via).then((socket) => {
@@ -329,7 +359,9 @@ function main(): void {
socket.destroy();
client.destroy();
if (identity.threadId) live.get(identity.threadId)?.delete(connection);
- log({ at: new Date(started).toISOString(), id, transport: "websocket", path, upstreamStatus, upBytes: up, downBytes: down, ms: Date.now() - started, closedForSelection: connection.closedForSelection, ...identity });
+ const entry = { at: new Date(started).toISOString(), id, transport: "websocket", path, upstreamStatus, upBytes: up, downBytes: down, ms: Date.now() - started, closedForSelection: connection.closedForSelection, ...identity };
+ log(entry);
+ recordRequest(identity.threadId, entry);
};
socket.on("close", close);
client.on("close", close);
@@ -346,11 +378,18 @@ function main(): void {
const server = http.createServer(onRequest);
server.on("upgrade", onUpgrade);
server.requestTimeout = 0;
- server.on("error", (error) => console.error(JSON.stringify({ host, error: String(error) })));
+ server.on("error", (error: NodeJS.ErrnoException) => {
+ console.error(JSON.stringify({ host, error: String(error) }));
+ // Another program holds the port (or a second engine won a race): this one must not run half-bound.
+ if (error.code === "EADDRINUSE") {
+ log({ at: new Date().toISOString(), event: "engine-exit", pid: process.pid, reason: `port ${port} in use on ${host}` });
+ process.exit(1);
+ }
+ });
server.listen(port, host, () => {
console.log(JSON.stringify({ listening: `http://${host.includes(":") ? `[${host}]` : host}:${port}/backend-api/codex`, upstream: UPSTREAM_HOST, via: via ? `${via.host}:${via.port}` : "direct" }));
});
}
}
-if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) main();
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) await main();
diff --git a/spike/src/selection.ts b/spike/src/selection.ts
index a968536..354088b 100644
--- a/spike/src/selection.ts
+++ b/spike/src/selection.ts
@@ -1,14 +1,14 @@
// Purpose: P2 — per-thread selection state: which image occurrences the user unchecked. Written by the CLI (later
// the panel), read by the proxy on every request of that thread.
-// Input/Output: local/selection/<thread id>.json, e.g. { "threadId": "…", "unchecked": { "<key>": { "id": "IMG-003", "at": "…" } } }.
+// Input/Output: <data dir>/selection/<thread id>.json, e.g. { "threadId": "…", "unchecked": { "<key>": { "id": "IMG-003", "at": "…" } } }.
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
-import { dirname, join, resolve } from "node:path";
-import { fileURLToPath } from "node:url";
+import { join } from "node:path";
+import { selectionDirOf } from "./paths.ts";
export type Selection = { threadId: string; unchecked: Record<string, { id: string; at: string }> };
-export const selectionDir = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local", "selection");
+export const selectionDir = selectionDirOf();
const THREAD_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const cache = new Map<string, { mtimeMs: number; size: number; selection: Selection }>();