Skip to content

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.

feat(spike): 代理验证 P2——按勾选把图片换成占位符

chipfighter255aba954ad2
diff --git a/spike/src/cam.ts b/spike/src/cam.ts
new file mode 100644
index 0000000..5d33a36
--- /dev/null
+++ b/spike/src/cam.ts
@@ -0,0 +1,54 @@
+// Purpose: P2 — command-line stand-in for the panel: list a thread's images and check/uncheck them.
+// Input: list <thread> | uncheck <thread> IMG-… | check <thread> IMG-… | check-all <thread>.
+// Output: the selection file under local/selection/ and a table on stdout. Rollouts are only read.
+
+import { join } from "node:path";
+import { pathToFileURL } from "node:url";
+import { codexHome } from "./codexconfig.ts";
+import { readSelection, writeSelection } from "./selection.ts";
+import { loadThreadIndex, type IndexedImage, type ThreadIndex } from "./thread-index.ts";
+
+export function sameContent(index: ThreadIndex, image: IndexedImage): string[] {
+ return index.images
+ .filter((other) => other !== image && (other.contentId === image.contentId || (image.pixelSha256 !== null && other.pixelSha256 === image.pixelSha256)))
+ .map((other) => other.id);
+}
+
+function table(index: ThreadIndex): string {
+ const unchecked = new Set(Object.keys(readSelection(index.threadId).unchecked));
+ const rows = index.images.map((image) => [
+ image.id,
+ !image.replaceable ? "锁定" : unchecked.has(image.key) ? "取消" : "勾选",
+ image.kind,
+ image.name ?? "—",
+ image.turn ?? "—",
+ image.width && image.height ? `${image.width}×${image.height}` : "—",
+ `${(image.bytes / 1024).toFixed(0)} KB`,
+ sameContent(index, image).join(",") || "—",
+ ].join(" | "));
+ return [`thread ${index.threadId}: ${index.images.length} images, ${index.turns} turns`, "id | 状态 | 种类 | 名称 | 轮次 | 尺寸 | 大小 | 内容相同", ...rows].join("\n");
+}
+
+function main(): void {
+ const [command, threadId, ...ids] = process.argv.slice(2);
+ if (!command || !threadId) throw new Error("usage: cam.ts list|uncheck|check|check-all <thread id> [IMG-…]");
+ const index = loadThreadIndex(join(codexHome(), "sessions"), threadId);
+ if (command !== "list") {
+ const selection = readSelection(threadId);
+ const unchecked = { ...selection.unchecked };
+ if (command === "check-all") for (const key of Object.keys(unchecked)) delete unchecked[key];
+ for (const id of ids) {
+ const image = index.images.find((candidate) => candidate.id === id);
+ if (!image) throw new Error(`${id} is not an image of this thread`);
+ if (command === "uncheck") {
+ if (!image.replaceable) throw new Error(`${id} cannot be unchecked yet (hosted image generation result)`);
+ unchecked[image.key] = { id, at: new Date().toISOString() };
+ } else if (command === "check") delete unchecked[image.key];
+ else throw new Error(`unknown command ${command}`);
+ }
+ writeSelection({ threadId, unchecked });
+ }
+ console.log(table(index));
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) main();
diff --git a/spike/src/images.test.ts b/spike/src/images.test.ts
new file mode 100644
index 0000000..20df0a9
--- /dev/null
+++ b/spike/src/images.test.ts
@@ -0,0 +1,75 @@
+// Purpose: P2 — image discovery in Responses items: keys, kinds, names, Codex's upload tags and header sizes.
+// Input: synthetic items shaped like the P2-1 request dumps; output: Node test assertions only.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import { findImages, imageSize } from "./images.ts";
+import { png } from "./testkit.ts";
+
+const url = (bytes: Buffer) => `data:image/png;base64,${bytes.toString("base64")}`;
+const red = png(4, 3, () => [255, 0, 0]);
+const blue = png(5, 5, () => [0, 0, 255]);
+
+const upload = (id: string, turn: string, names: string[], images: Buffer[]) => ({
+ type: "message",
+ id,
+ role: "user",
+ content: [
+ { type: "input_text", text: "看看这些图" },
+ ...names.flatMap((name, i) => [
+ { type: "input_text", text: `<image name=[Image #${i + 1}] path="C:\\work\\shots\\${name}">` },
+ { type: "input_image", image_url: url(images[i]), detail: "high" },
+ { type: "input_text", text: "</image>" },
+ ]),
+ ],
+ internal_chat_message_metadata_passthrough: { turn_id: turn },
+});
+
+test("uploads: key from the item id, name and label from Codex's tag, tags recorded for replacement", () => {
+ const refs = findImages([upload("msg_1", "turn-1", ["a.png", "a copy.png"], [red, red])]);
+ assert.equal(refs.length, 2);
+ assert.deepEqual(refs.map((r) => [r.key, r.kind, r.name, r.label, r.openTag, r.part, r.closeTag, r.turnId]), [
+ ["msg_1#0", "upload", "a.png", "[Image #1]", 1, 2, 3, "turn-1"],
+ ["msg_1#1", "upload", "a copy.png", "[Image #2]", 4, 5, 6, "turn-1"],
+ ]);
+ assert.equal(refs[0].contentId, refs[1].contentId, "same bytes, same content id, whatever the name");
+ assert.deepEqual([refs[0].width, refs[0].height, refs[0].mime], [4, 3, "image/png"]);
+});
+
+test("code-mode tool outputs: view_image paths and generated-image hints name the images", () => {
+ const items = [
+ { type: "custom_tool_call", call_id: "c1", name: "exec", input: 'const r = await tools.view_image({path:"D:\\\\shots\\\\c.png"}); image(r.image_url);' },
+ { type: "custom_tool_call_output", id: "ctco_1", call_id: "c1", output: [{ type: "input_text", text: "Script completed" }, { type: "input_image", image_url: url(blue) }] },
+ { type: "custom_tool_call", call_id: "c2", name: "exec", input: 'const r = await tools.image_gen__imagegen({prompt:"x"}); generatedImage(r);' },
+ { type: "custom_tool_call_output", id: "ctco_2", call_id: "c2", output: [{ type: "input_image", image_url: url(red) }, { type: "input_text", text: "Generated images are saved to C:\\g\\t as C:\\g\\t\\exec-1.png by default.\nIf you need…" }] },
+ { type: "function_call", call_id: "c3", name: "view_image", arguments: JSON.stringify({ path: "/tmp/d.png" }) },
+ { type: "function_call_output", call_id: "c3", output: [{ type: "input_image", image_url: url(blue) }] },
+ ];
+ assert.deepEqual(findImages(items).map((r) => [r.key, r.kind, r.name, r.openTag]), [
+ ["ctco_1#0", "view", "c.png", null],
+ ["ctco_2#0", "generated", "exec-1.png", null],
+ ["function_call_output:c3#0", "view", "d.png", null],
+ ]);
+});
+
+test("hosted image generation results are found but cannot be replaced", () => {
+ const [ref] = findImages([{ type: "image_generation_call", id: "ig_1", status: "completed", result: red.toString("base64") }]);
+ assert.deepEqual([ref.key, ref.kind, ref.replaceable, ref.part], ["ig_1#0", "generated", false, null]);
+});
+
+test("items without ids fall back to type, turn and content, numbered in order", () => {
+ const plain = (text: string) => ({ type: "message", role: "user", content: [{ type: "input_text", text }, { type: "input_image", image_url: url(red) }] });
+ const refs = findImages([plain("one"), plain("two")]);
+ assert.equal(refs.length, 2);
+ assert.notEqual(refs[0].key, refs[1].key);
+ assert.match(refs[0].key, new RegExp(`^message:user::${refs[0].contentId}#0$`));
+});
+
+test("image sizes come from PNG, GIF and JPEG headers", () => {
+ assert.deepEqual(imageSize(blue), { width: 5, height: 5 });
+ const gif = Buffer.from("474946383961" + "0a00" + "0700", "hex");
+ assert.deepEqual(imageSize(gif), { width: 10, height: 7 });
+ // SOI, an APP0 segment, then SOF0 with height 300 and width 400.
+ const jpeg = Buffer.from("ffd8" + "ffe00004" + "0000" + "ffc0000b08012c0190030100", "hex");
+ assert.deepEqual(imageSize(jpeg), { width: 400, height: 300 });
+});
diff --git a/spike/src/images.ts b/spike/src/images.ts
new file mode 100644
index 0000000..e7c910f
--- /dev/null
+++ b/spike/src/images.ts
@@ -0,0 +1,151 @@
+// Purpose: P2 — find every image in a list of Responses items (a request's `input`, or a rollout's response_items)
+// and describe it: a key that names the same occurrence in both places, its kind and name, and a content digest.
+// Input: items as parsed JSON. Output: ImageRef[] in item order (pure, no I/O).
+
+import { createHash } from "node:crypto";
+
+type Json = Record<string, any>;
+export type ImageKind = "upload" | "view" | "generated" | "tool";
+export type ImageDigest = { contentId: string; mime: string | null; base64Chars: number; width: number | null; height: number | null };
+
+export type ImageRef = ImageDigest & {
+ key: string;
+ item: number;
+ // Index in the item's content/output array; null for a hosted image_generation_call result.
+ part: number | null;
+ // Codex's own `<image name=[Image #N] path="…">` and `</image>` parts around an upload, replaced together with it.
+ openTag: number | null;
+ closeTag: number | null;
+ kind: ImageKind;
+ // A hosted image_generation_call keeps its image in a required `result` field that cannot become text.
+ replaceable: boolean;
+ name: string | null;
+ label: string | null;
+ turnId: string | null;
+};
+
+const OPEN_TAG = /^<image name=(\[Image #\d+\]) path="(.*)">$/s;
+
+export function baseName(path: string): string {
+ return path.split(/[\\/]/).filter(Boolean).pop() ?? path;
+}
+
+// Width and height from the image header only, so large images are not decoded.
+export function imageSize(bytes: Buffer): { width: number; height: number } | null {
+ if (bytes.length >= 24 && bytes.readUInt32BE(0) === 0x89504e47) return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
+ if (bytes.length >= 10 && bytes.toString("ascii", 0, 3) === "GIF") return { width: bytes.readUInt16LE(6), height: bytes.readUInt16LE(8) };
+ if (bytes.length >= 30 && bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP") {
+ const chunk = bytes.toString("ascii", 12, 16);
+ if (chunk === "VP8X") return { width: bytes.readUIntLE(24, 3) + 1, height: bytes.readUIntLE(27, 3) + 1 };
+ if (chunk === "VP8 ") return { width: bytes.readUInt16LE(26) & 0x3fff, height: bytes.readUInt16LE(28) & 0x3fff };
+ if (chunk === "VP8L") { const bits = bytes.readUInt32LE(21); return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 }; }
+ return null;
+ }
+ if (bytes.length >= 4 && bytes[0] === 0xff && bytes[1] === 0xd8) {
+ let offset = 2;
+ while (offset + 9 < bytes.length) {
+ if (bytes[offset] !== 0xff) return null;
+ const marker = bytes[offset + 1];
+ if (marker === 0xff) { offset++; continue; }
+ const length = bytes.readUInt16BE(offset + 2);
+ // SOF0–SOF15 carry the frame size, except DHT (C4), JPG (C8) and DAC (CC).
+ if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) return { width: bytes.readUInt16BE(offset + 7), height: bytes.readUInt16BE(offset + 5) };
+ offset += 2 + length;
+ }
+ }
+ return null;
+}
+
+const digests = new WeakMap<object, ImageDigest>();
+
+// Keyed by the part object, so re-reading the same cached rollout records does not hash the same images again.
+function digest(owner: object, value: string, mime: string | null): ImageDigest {
+ const known = digests.get(owner);
+ if (known) return known;
+ const header = Buffer.from(value.slice(0, 96 * 1024), "base64");
+ const size = imageSize(header);
+ const result = { contentId: createHash("sha256").update(value).digest("hex"), mime, base64Chars: value.length, width: size?.width ?? null, height: size?.height ?? null };
+ digests.set(owner, result);
+ return result;
+}
+
+function partDigest(part: Json): ImageDigest | null {
+ if (part?.type !== "input_image" && part?.type !== "output_image") return null;
+ if (typeof part.file_id === "string") return { contentId: `file:${part.file_id}`, mime: null, base64Chars: 0, width: null, height: null };
+ const inline = typeof part.image_url === "string" ? /^data:([^;,]+);base64,/.exec(part.image_url) : null;
+ return inline ? digest(part, part.image_url.slice(inline[0].length), inline[1]) : null;
+}
+
+// A tool output's images get names from the call that produced them: view_image paths, or the saved-image hint
+// that Codex's image generation adds next to its result.
+function toolContext(call: Json | undefined, output: Json[]): { kind: ImageKind; names: string[] } {
+ const hints = output.flatMap((part) => (typeof part?.text === "string" ? [...part.text.matchAll(/Generated images are saved to .*? as (.+?\.png) by default/g)].map((m) => baseName(m[1])) : []));
+ if (hints.length) return { kind: "generated", names: hints };
+ if (!call) return { kind: "tool", names: [] };
+ if (call.type === "function_call") {
+ if (call.name === "view_image") {
+ try { return { kind: "view", names: [baseName(JSON.parse(call.arguments).path)] }; } catch { return { kind: "view", names: [] }; }
+ }
+ return { kind: /imagegen|image_gen/.test(call.name ?? "") ? "generated" : "tool", names: [] };
+ }
+ const source = String(call.input ?? "");
+ const views = [...source.matchAll(/view_image\(\s*\{\s*path\s*:\s*"((?:[^"\\]|\\.)*)"/g)].map((m) => {
+ try { return baseName(JSON.parse(`"${m[1]}"`)); } catch { return baseName(m[1]); }
+ });
+ if (views.length) return { kind: "view", names: views };
+ return { kind: /image_gen|imagegen|generatedImage\(/.test(source) ? "generated" : "tool", names: [] };
+}
+
+export function findImages(items: Json[]): ImageRef[] {
+ const calls = new Map<string, Json>();
+ const seenFallback = new Map<string, number>();
+ const refs: ImageRef[] = [];
+ items.forEach((item, index) => {
+ if (!item || typeof item !== "object") return;
+ if ((item.type === "function_call" || item.type === "custom_tool_call") && item.call_id) calls.set(item.call_id, item);
+ const turnId: string | null = item.internal_chat_message_metadata_passthrough?.turn_id ?? null;
+ const keyFor = (n: number, contentId: string) => {
+ if (typeof item.id === "string" && item.id) return `${item.id}#${n}`;
+ if (typeof item.call_id === "string" && item.call_id) return `${item.type}:${item.call_id}#${n}`;
+ const base = `${item.type}:${item.role ?? ""}:${turnId ?? ""}:${contentId}`;
+ const seen = seenFallback.get(base) ?? 0;
+ seenFallback.set(base, seen + 1);
+ return `${base}#${seen}`;
+ };
+
+ if (item.type === "image_generation_call" && typeof item.result === "string" && item.result) {
+ const found = digest(item, item.result, "image/png");
+ refs.push({ ...found, key: keyFor(0, found.contentId), item: index, part: null, openTag: null, closeTag: null, kind: "generated", replaceable: false, name: null, label: null, turnId });
+ return;
+ }
+ const field = item.type === "message" ? item.content : item.type === "function_call_output" || item.type === "custom_tool_call_output" ? item.output : null;
+ if (!Array.isArray(field)) return;
+ const context = item.type === "message" ? null : toolContext(calls.get(item.call_id), field);
+ let n = 0;
+ field.forEach((part: Json, partIndex: number) => {
+ const found = partDigest(part);
+ if (!found) return;
+ const before = field[partIndex - 1]?.type === "input_text" ? String(field[partIndex - 1].text) : null;
+ const after = field[partIndex + 1]?.type === "input_text" ? String(field[partIndex + 1].text) : null;
+ const open = before !== null && (OPEN_TAG.test(before) || before === "<image>");
+ const close = open && after === "</image>";
+ const tag = before ? OPEN_TAG.exec(before) : null;
+ const kind: ImageKind = context?.kind ?? (item.role === "user" ? "upload" : "tool");
+ refs.push({
+ ...found,
+ key: keyFor(n, found.contentId),
+ item: index,
+ part: partIndex,
+ openTag: open ? partIndex - 1 : null,
+ closeTag: close ? partIndex + 1 : null,
+ kind,
+ replaceable: true,
+ name: tag ? baseName(tag[2]) : context?.names[n] ?? null,
+ label: tag ? tag[1] : null,
+ turnId,
+ });
+ n++;
+ });
+ });
+ return refs;
+}
diff --git a/spike/src/p2-capture.ts b/spike/src/p2-capture.ts
new file mode 100644
index 0000000..0e8a6e0
--- /dev/null
+++ b/spike/src/p2-capture.ts
@@ -0,0 +1,47 @@
+// Purpose: P2-1 — produce Responses requests that contain every kind of image (uploads incl. a renamed byte copy,
+// a view_image result, a generated image) in a synthetic test thread, so the proxy's --dump-requests output shows
+// where images sit in the request. The proxy must already run with --force-http --dump-requests.
+// Input: [--port 17891] [--label name]. Output: local/p2/capture-<label>.json; request dumps come from the proxy.
+
+import { copyFileSync, mkdirSync, writeFileSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { AppServer, findBundledCodex } from "./appserver.ts";
+import { runTurn, testImages, text } from "./testkit.ts";
+
+type Json = Record<string, any>;
+const localRoot = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");
+
+async function main(): Promise<void> {
+ const option = (name: string, fallback: string) => (process.argv.includes(name) ? process.argv[process.argv.indexOf(name) + 1] : fallback);
+ const port = Number(option("--port", "17891"));
+ const label = option("--label", "default");
+ const workDir = join(localRoot, "p2", "work");
+ mkdirSync(workDir, { recursive: true });
+ mkdirSync(join(localRoot, "logs"), { recursive: true });
+ const file = (name: string) => join(workDir, name);
+ writeFileSync(file("a.png"), testImages.redSquare());
+ writeFileSync(file("b.png"), testImages.blueCircle());
+ copyFileSync(file("b.png"), file("b-copy.png"));
+ writeFileSync(file("c.png"), testImages.whiteTriangle());
+
+ const startedAt = new Date().toISOString();
+ const server = new AppServer(findBundledCodex(), ["-c", `openai_base_url="http://localhost:${port}/backend-api/codex"`, "-c", "features.respect_system_proxy=true"], {}, join(localRoot, "logs", `p2-capture-${label}-${startedAt.replaceAll(":", "-")}.log`));
+ const result: Json = { createdAt: startedAt, label, turns: {} };
+ try {
+ await server.initialize();
+ const { thread } = await server.request<{ thread: Json }>("thread/start", { cwd: workDir, approvalPolicy: "never", sandbox: "read-only", ephemeral: false });
+ result.threadId = thread.id;
+ await server.request("thread/name/set", { threadId: thread.id, name: `[CAM测试] P2-1 请求结构 ${label}` });
+ result.turns.upload = await runTurn(server, thread.id, [text("这是三张测试图,先不用描述,只回复“收到”。"), ...["a.png", "b.png", "b-copy.png"].map((name) => ({ type: "localImage", path: file(name) }))]);
+ result.turns.viewImage = await runTurn(server, thread.id, [text(`请用 view_image 工具查看这个文件:${file("c.png")},然后用一句话说出它的背景色和主要形状。`)]);
+ result.turns.generate = await runTurn(server, thread.id, [text("请用内置的生图工具生成一张简单的图片:浅绿色背景,正中间一个橙色正方形。生成 1 张即可。")]);
+ result.turns.last = await runTurn(server, thread.id, [text("请只回复“好的”。")]);
+ } finally {
+ await server.stop();
+ writeFileSync(join(localRoot, "p2", `capture-${label}.json`), JSON.stringify(result, null, 2));
+ console.log(JSON.stringify(result, (key, value) => (key === "reply" && typeof value === "string" ? value.slice(0, 160) : value), 2));
+ }
+}
+
+await main();
diff --git a/spike/src/p2-selftest.ts b/spike/src/p2-selftest.ts
new file mode 100644
index 0000000..9bfebfc
--- /dev/null
+++ b/spike/src/p2-selftest.ts
@@ -0,0 +1,103 @@
+// Purpose: P2-5 — end-to-end check of rewriting in one thread with our own app-server in the desktop's environment
+// (NO_PROXY removed, respect_system_proxy on, localhost base URL; config.toml untouched):
+// upload four synthetic images (one a renamed byte copy, one ~3 MB of noise) → uncheck the original, the copy and the
+// large one → ask about the first two → re-check the original → ask again → check everything → one more turn.
+// The proxy must already run (no flags).
+// Input: [--port 17891] [--label name]. Output: local/p2/selftest-<label>.json (synthetic test thread only).
+
+import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
+import { setTimeout as sleep } from "node:timers/promises";
+import { fileURLToPath } from "node:url";
+import { AppServer, findBundledCodex } from "./appserver.ts";
+import { codexHome } from "./codexconfig.ts";
+import { readSelection, writeSelection } from "./selection.ts";
+import { runTurn, testImages, text } from "./testkit.ts";
+import { loadThreadIndex } from "./thread-index.ts";
+
+type Json = Record<string, any>;
+const localRoot = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");
+
+function setChecked(threadId: string, keys: Record<string, string>, uncheck: string[]): void {
+ writeSelection({ threadId, unchecked: Object.fromEntries(uncheck.map((id) => [keys[id], { id, at: new Date().toISOString() }])) });
+}
+
+async function main(): Promise<void> {
+ const option = (name: string, fallback: string) => (process.argv.includes(name) ? process.argv[process.argv.indexOf(name) + 1] : fallback);
+ const port = Number(option("--port", "17891"));
+ const label = option("--label", "default");
+ const workDir = join(localRoot, "p2", "work");
+ mkdirSync(workDir, { recursive: true });
+ const file = (name: string) => join(workDir, name);
+ writeFileSync(file("a.png"), testImages.redSquare());
+ writeFileSync(file("b.png"), testImages.blueCircle());
+ copyFileSync(file("b.png"), file("b-copy.png"));
+ writeFileSync(file("noise.png"), testImages.noise());
+
+ const startedAt = new Date().toISOString();
+ const server = new AppServer(findBundledCodex(), ["-c", `openai_base_url="http://localhost:${port}/backend-api/codex"`, "-c", "features.respect_system_proxy=true"], { NO_PROXY: undefined, no_proxy: undefined }, join(localRoot, "logs", `p2-selftest-${label}-${startedAt.replaceAll(":", "-")}.log`));
+ const result: Json = { createdAt: startedAt, label, turns: {} };
+ let threadId = "";
+ try {
+ await server.initialize();
+ const { thread } = await server.request<{ thread: Json }>("thread/start", { cwd: workDir, approvalPolicy: "never", sandbox: "read-only", ephemeral: false });
+ threadId = thread.id;
+ result.threadId = threadId;
+ await server.request("thread/name/set", { threadId, name: `[CAM测试] P2 改写自测 ${label}` });
+
+ result.turns.upload = await runTurn(server, threadId, [text("这是四张测试图,先不用描述,只回复“收到”。"), ...["a.png", "b.png", "b-copy.png", "noise.png"].map((name) => ({ type: "localImage", path: file(name) }))]);
+ const index = loadThreadIndex(join(codexHome(), "sessions"), threadId);
+ result.index = index.images.map((image) => ({ id: image.id, name: image.name, kind: image.kind, turn: image.turn, contentHash: image.contentId.slice(0, 16) }));
+ const keys = Object.fromEntries(index.images.map((image) => [image.id, image.key]));
+
+ setChecked(threadId, keys, ["IMG-001", "IMG-003", "IMG-004"]);
+ result.selectionAfterUncheck = Object.values(readSelection(threadId).unchecked).map((entry) => entry.id);
+ await sleep(3000);
+ const question = "请分别回答:1)第一张图 a.png 是什么背景色、什么主要形状,角落里有什么小标记,在哪个角?2)第三张图 b-copy.png 呢?不要调用任何工具。";
+ result.turns.unchecked = await runTurn(server, threadId, [text(question)]);
+
+ setChecked(threadId, keys, ["IMG-003", "IMG-004"]);
+ result.turns.rechecked = await runTurn(server, threadId, [text("我重新提供了 a.png。请再回答一次第 1 个问题:它是什么背景色、什么主要形状,角落里有什么小标记,在哪个角?不要调用任何工具。")]);
+
+ setChecked(threadId, keys, []);
+ result.turns.allChecked = await runTurn(server, threadId, [text("请只回复“好的”。")]);
+
+ const read = await server.request<{ thread: Json }>("thread/read", { threadId, includeTurns: true });
+ result.threadTurns = read.thread.turns?.length ?? null;
+ } finally {
+ await server.stop();
+ }
+
+ const entries: Json[] = readFileSync(join(localRoot, "proxy", `${new Date().toISOString().slice(0, 10)}.jsonl`), "utf8")
+ .trim().split("\n").map((line) => JSON.parse(line)).filter((entry) => entry.at >= startedAt && entry.threadId === threadId);
+ const turnIds = Object.fromEntries(Object.entries(result.turns as Record<string, Json>).map(([name, turn]) => [turn.turnId, name]));
+ result.proxy = entries.map((entry) => ({
+ turn: turnIds[entry.turnId] ?? entry.turnId,
+ transport: entry.transport,
+ what: entry.declined ? `declined ${entry.declined}` : entry.transport === "websocket" ? `${entry.upstreamStatus} closedForSelection=${entry.closedForSelection}` : `${entry.method} ${entry.path.split("/").pop()} ${entry.status}`,
+ rewrite: entry.rewrite ? { replaced: entry.rewrite.replaced?.map((r: Json) => `${r.id}:${r.mode}${r.sameAs ? `->${r.sameAs}` : ""}`), sent: entry.rewrite.sentImageHashes, skipped: entry.rewrite.skipped, roundTripExact: entry.rewrite.roundTripExact, decoded: [entry.rewrite.decodedBefore, entry.rewrite.decodedAfter], encoded: [entry.rewrite.encodedBefore, entry.rewrite.encodedAfter] } : null,
+ requestBytes: entry.requestBytes ?? entry.upBytes,
+ }));
+
+ const hash = (id: string) => (result.index as Json[]).find((image) => image.id === id)?.contentHash;
+ const posts = (turn: string) => (result.proxy as Json[]).filter((entry) => entry.turn === turn && entry.transport === "http" && /responses/.test(entry.what));
+ const turn2 = posts("unchecked");
+ const turn3 = posts("rechecked");
+ const turn4 = posts("allChecked");
+ result.checks = {
+ indexFoundCopy: JSON.stringify((result.index as Json[]).map((image) => image.name)) === JSON.stringify(["a.png", "b.png", "b-copy.png", "noise.png"]) && hash("IMG-002") === hash("IMG-003"),
+ websocketClosedAfterUncheck: (result.proxy as Json[]).some((entry) => /closedForSelection=true/.test(entry.what)) || !(result.proxy as Json[]).some((entry) => entry.transport === "websocket" && entry.turn === "upload"),
+ turn2Rewritten: turn2.length > 0 && turn2.every((entry) => JSON.stringify(entry.rewrite?.replaced) === JSON.stringify(["IMG-001:plain", "IMG-003:duplicate->IMG-002", "IMG-004:plain"]) && !entry.rewrite.sent.includes(hash("IMG-001")) && !entry.rewrite.sent.includes(hash("IMG-004"))),
+ turn2Smaller: turn2.length > 0 && turn2.every((entry) => entry.rewrite.encoded[1] < entry.rewrite.encoded[0] - 1_000_000),
+ turn2AsksForImage: /IMG-001/.test(result.turns.unchecked.reply),
+ turn3SendsImageAgain: turn3.length > 0 && turn3.every((entry) => JSON.stringify(entry.rewrite?.replaced) === JSON.stringify(["IMG-003:duplicate->IMG-002", "IMG-004:plain"]) && entry.rewrite.sent.includes(hash("IMG-001"))),
+ turn3SeesImage: /红/.test(result.turns.rechecked.reply) && /黑/.test(result.turns.rechecked.reply),
+ turn4PassThrough: turn4.length > 0 && turn4.every((entry) => entry.rewrite === null),
+ noErrors: Object.values(result.turns as Record<string, Json>).every((turn) => turn.status === "completed" && !turn.errors.length),
+ sameThreadAllTurns: result.threadTurns === 4,
+ };
+ writeFileSync(join(localRoot, "p2", `selftest-${label}.json`), JSON.stringify(result, null, 2));
+ console.log(JSON.stringify({ threadId, checks: result.checks, replies: Object.fromEntries(Object.entries(result.turns as Record<string, Json>).map(([name, turn]) => [name, turn.reply])), proxy: result.proxy }, null, 2));
+}
+
+await main();
diff --git a/spike/src/proxy.test.ts b/spike/src/proxy.test.ts
index 8d65e93..b6b881b 100644
--- a/spike/src/proxy.test.ts
+++ b/spike/src/proxy.test.ts
@@ -1,9 +1,16 @@
-// Purpose: P1-2 — pure helpers of the transparent proxy: outbound proxy detection, task identity, body metadata.
-// Input: synthetic env, headers and request bodies; output: Node test assertions only.
+// Purpose: P1-2/P2 — proxy helpers: outbound proxy detection, task identity, body metadata, and the request rewrite
+// (placeholder swap, re-encoding, and the cases where the original bytes must be forwarded).
+// Input: synthetic env, headers, request bodies and temporary rollouts; output: Node test assertions only.
import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import test from "node:test";
-import { describeBody, outboundProxy, requestIdentity } from "./proxy.ts";
+import zlib from "node:zlib";
+import { describeBody, hasUnchecked, hasUnsafeInteger, outboundProxy, rewriteBody, requestIdentity } from "./proxy.ts";
+import { writeSelection } from "./selection.ts";
+import { png } from "./testkit.ts";
const none = () => null;
@@ -41,3 +48,62 @@ test("request metadata counts images in messages and in tool outputs, without co
assert.doesNotMatch(JSON.stringify(described), /secret words/);
assert.equal(describeBody("/backend-api/codex/images/edits", { model: "gpt-image", images: [{}, {}], size: "1024x1024" }).kind, "image_edit");
});
+
+test("integers JavaScript cannot hold exactly are detected outside strings only", () => {
+ assert.equal(hasUnsafeInteger('{"a":12345678901234567}'), true);
+ assert.equal(hasUnsafeInteger('{"a":"order 12345678901234567","b":1790246521.5642291234567,"c":[1,-2,3e25]}'), false);
+ assert.equal(hasUnsafeInteger('{"a":9007199254740991}'), false);
+});
+
+// P2: a zstd request for a thread whose rollout and selection live in temporary directories.
+function fixture() {
+ const threadId = "01a0d301-0000-7000-8000-00000000000c";
+ const root = mkdtempSync(join(tmpdir(), "cam-proxy-"));
+ const sessions = join(root, "sessions");
+ const selections = join(root, "selection");
+ mkdirSync(join(sessions, "2026", "09", "24"), { recursive: true });
+ // A noisy 64×64 image, large enough that its placeholder is smaller than the image itself.
+ const red = `data:image/png;base64,${png(64, 64, (x, y) => [255, (x * 37 + y * 101) % 256, (x * y) % 256]).toString("base64")}`;
+ const blue = `data:image/png;base64,${png(8, 8, () => [0, 0, 255]).toString("base64")}`;
+ const message = {
+ type: "message", id: "msg_1", role: "user",
+ content: [
+ { type: "input_text", text: "两张图" },
+ { type: "input_text", text: String.raw`<image name=[Image #1] path="C:\w\a.png">` }, { type: "input_image", image_url: red }, { type: "input_text", text: "</image>" },
+ { type: "input_text", text: String.raw`<image name=[Image #2] path="C:\w\b.png">` }, { type: "input_image", image_url: blue }, { type: "input_text", text: "</image>" },
+ ],
+ internal_chat_message_metadata_passthrough: { turn_id: "t1" },
+ };
+ const rollout = [{ type: "session_meta", payload: { id: threadId } }, { type: "event_msg", payload: { type: "task_started", turn_id: "t1" } }, { type: "response_item", payload: message }];
+ writeFileSync(join(sessions, "2026", "09", "24", `rollout-2026-09-24T10-00-00-${threadId}.jsonl`), rollout.map((r) => JSON.stringify(r)).join("\n") + "\n");
+ const body = (extra = "") => zlib.zstdCompressSync(Buffer.from(`{"model":"m","input":[${JSON.stringify(message)}],"stream":true${extra}}`));
+ return { threadId, sessions, selections, red, blue, body };
+}
+
+test("rewriteBody swaps the unchecked image for a placeholder and re-encodes the body", () => {
+ const { threadId, sessions, selections, red, blue, body } = fixture();
+ assert.equal(hasUnchecked(threadId, selections), false);
+ writeSelection({ threadId, unchecked: { "msg_1#0": { id: "IMG-001", at: "2026-09-24T10:00:00Z" } } }, selections);
+ assert.equal(hasUnchecked(threadId, selections), true);
+ const original = body();
+ const { body: out, report } = rewriteBody(original, "zstd", threadId, sessions, selections);
+ const text = zlib.zstdDecompressSync(out).toString("utf8");
+ assert.ok(!text.includes(red.slice(30)), "the unchecked image is gone");
+ assert.ok(text.includes(blue.slice(30)), "the checked image is still there");
+ assert.match(text, /\[图片 IMG-001(\[Image #1\]) 未提供|a\.png|用户上传|第 1 轮|64×64]/);
+ assert.deepEqual(report.replaced, [{ id: "IMG-001", kind: "upload", mode: "plain", sameAs: null, base64Chars: red.length - "data:image/png;base64,".length }]);
+ assert.equal(report.roundTripExact, true);
+ assert.ok(report.decodedAfter < report.decodedBefore);
+});
+
+test("rewriteBody forwards the original bytes when nothing applies or the body is not safe to re-serialize", () => {
+ const { threadId, sessions, selections, body } = fixture();
+ writeSelection({ threadId, unchecked: { "msg_other#0": { id: "IMG-009", at: "2026-09-24T10:00:00Z" } } }, selections);
+ const original = body();
+ assert.equal(rewriteBody(original, "zstd", threadId, sessions, selections).body, original);
+ writeSelection({ threadId, unchecked: { "msg_1#0": { id: "IMG-001", at: "2026-09-24T10:00:00Z" } } }, selections);
+ const risky = body(',"big":12345678901234567');
+ const { body: out, report } = rewriteBody(risky, "zstd", threadId, sessions, selections);
+ assert.equal(out, risky);
+ assert.match(report.skipped, /2\^53/);
+});
diff --git a/spike/src/proxy.ts b/spike/src/proxy.ts
index 6eb79b8..cad18a9 100644
--- a/spike/src/proxy.ts
+++ b/spike/src/proxy.ts
@@ -1,10 +1,12 @@
// 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]; the outbound proxy is taken from HTTPS_PROXY/HTTP_PROXY or the Windows proxy settings.
+// 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.
import { execFileSync } from "node:child_process";
-import { appendFileSync, mkdirSync } from "node:fs";
+import { createHash } from "node:crypto";
+import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
import http, { type IncomingHttpHeaders } from "node:http";
import net from "node:net";
import { dirname, join, resolve } from "node:path";
@@ -12,6 +14,11 @@ import type { Duplex } from "node:stream";
import tls from "node:tls";
import { fileURLToPath, pathToFileURL } from "node:url";
import zlib from "node:zlib";
+import { codexHome } from "./codexconfig.ts";
+import type { ImageRef } from "./images.ts";
+import { rewriteItems, type Described } from "./rewrite.ts";
+import { readSelection, selectionDir } from "./selection.ts";
+import { loadThreadIndex, pixelHashOf, type ThreadIndex } from "./thread-index.ts";
type Json = Record<string, any>;
const UPSTREAM_HOST = "chatgpt.com";
@@ -118,11 +125,98 @@ function log(entry: Json): void {
appendFileSync(join(localRoot, "proxy", `${new Date().toISOString().slice(0, 10)}.jsonl`), `${JSON.stringify(entry)}\n`);
}
+// P2-1 debugging aid for synthetic test threads only: the request with every inline image reduced to its hash and size.
+export function redactImages(value: unknown, key = ""): unknown {
+ if (typeof value === "string") {
+ const inline = /^data:([^;,]+);base64,/.exec(value);
+ const raw = inline ? value.slice(inline[0].length) : key === "result" && value.length > 256 ? value : null;
+ if (raw === null) return value;
+ const digest = createHash("sha256").update(raw).digest("hex").slice(0, 16);
+ return `${inline ? `data:${inline[1]};base64,` : ""}<sha256:${digest} chars:${raw.length}>`;
+ }
+ if (Array.isArray(value)) return value.map((item) => redactImages(item));
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([name, child]) => [name, redactImages(child, name)]));
+ return value;
+}
+
+function encodeBody(body: Buffer, encoding: string | undefined): Buffer {
+ if (encoding === "zstd") return zlib.zstdCompressSync(body);
+ if (encoding === "gzip") return zlib.gzipSync(body);
+ if (encoding === "br") return zlib.brotliCompressSync(body);
+ return body;
+}
+
+// Number tokens outside strings that JavaScript cannot represent exactly.
+export function hasUnsafeInteger(json: string): boolean {
+ for (const match of json.matchAll(/"(?:[^"\\]|\\.)*"|(?<![\d.eE+-])(-?\d+)(?![.\deE])/g)) {
+ if (match[1] && !Number.isSafeInteger(Number(match[1]))) return true;
+ }
+ return false;
+}
+
+export function hasUnchecked(threadId: string | null, dir = selectionDir): boolean {
+ if (!threadId) return false;
+ try { return Object.keys(readSelection(threadId, dir).unchecked).length > 0; } catch { return false; }
+}
+
+// P2: replace the thread's unchecked images with placeholders. Whenever the body cannot be handled safely it is
+// forwarded unchanged and the reason is logged; the report never contains conversation content.
+export function rewriteBody(original: Buffer, encoding: string | undefined, threadId: string, sessionsDir: string, dir = selectionDir): { body: Buffer; report: Json } {
+ const decoded = decodeBody(original, encoding);
+ if (!decoded) return { body: original, report: { skipped: "undecodable body" } };
+ const text = decoded.toString("utf8");
+ let json: Json;
+ try { json = JSON.parse(text); } catch { return { body: original, report: { skipped: "unparsable body" } }; }
+ if (!Array.isArray(json.input)) return { body: original, report: { skipped: "no input array" } };
+ if (hasUnsafeInteger(text)) return { body: original, report: { skipped: "integer beyond 2^53 would change when re-serialized" } };
+ let index: ThreadIndex;
+ try { index = loadThreadIndex(sessionsDir, threadId); } catch (error) { return { body: original, report: { skipped: `thread index: ${String(error)}` } }; }
+ const selection = readSelection(threadId, dir);
+ const describe = (ref: ImageRef): Described | undefined => {
+ const known = index.byKey.get(ref.key);
+ if (known) return known;
+ const stored = selection.unchecked[ref.key];
+ return stored ? { id: stored.id, name: ref.name, label: ref.label, kind: ref.kind, turn: null, width: ref.width, height: ref.height } : undefined;
+ };
+ const pixels = (ref: ImageRef) => index.byKey.get(ref.key)?.pixelSha256 ?? pixelHashOf(json.input, ref);
+ const { items, report } = rewriteItems(json.input, describe, new Set(Object.keys(selection.unchecked)), pixels);
+ const summary: Json = {
+ images: report.images,
+ replaced: report.replaced.map(({ key: _key, ...rest }) => rest),
+ locked: report.locked,
+ sentImageHashes: report.sentContentIds.map((id) => id.slice(0, 16)),
+ roundTripExact: JSON.stringify(json) === text,
+ };
+ if (!report.replaced.length) return { body: original, report: summary };
+ json.input = items;
+ const next = Buffer.from(JSON.stringify(json), "utf8");
+ const body = encodeBody(next, encoding);
+ return { body, report: { ...summary, decodedBefore: decoded.length, decodedAfter: next.length, encodedBefore: original.length, encodedAfter: body.length } };
+}
+
function main(): void {
const portIndex = process.argv.indexOf("--port");
const port = Number(portIndex >= 0 ? process.argv[portIndex + 1] : 17891);
+ // --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 sessionsDir = join(codexHome(), "sessions");
const via = outboundProxy();
let sequence = 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 }>>();
+ setInterval(() => {
+ for (const [threadId, connections] of live) {
+ if (!hasUnchecked(threadId)) continue;
+ for (const connection of connections) {
+ if (Date.now() - connection.last < 1500) continue;
+ connection.closedForSelection = true;
+ connection.socket.destroy();
+ connection.client.destroy();
+ }
+ }
+ }, 500).unref();
const onRequest = (req: http.IncomingMessage, res: http.ServerResponse) => {
if (req.url === "/__cam/health") {
@@ -133,23 +227,38 @@ function main(): void {
const id = ++sequence;
const started = Date.now();
const path = (req.url ?? "/").split("?")[0];
+ const identity = requestIdentity(req.headers);
+ const rewrite = req.method === "POST" && /\/responses(\/compact)?$/.test(path) && hasUnchecked(identity.threadId);
const chunks: Buffer[] = [];
let requestBytes = 0;
let responseBytes = 0;
let status = 0;
let finished = false;
+ let extra: Json = {};
+ const collect = () => req.on("data", (chunk: Buffer) => { chunks.push(chunk); requestBytes += chunk.length; });
const finish = (error?: string) => {
if (finished) return;
finished = true;
const body = Buffer.concat(chunks);
const decoded = req.method === "POST" ? decodeBody(body, req.headers["content-encoding"] as string | undefined) : null;
let details: Json = {};
- if (decoded) { try { details = describeBody(path, JSON.parse(decoded.toString("utf8"))); } 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, ...requestIdentity(req.headers), ...details, error: error ?? null });
+ if (decoded) {
+ try {
+ const json = JSON.parse(decoded.toString("utf8"));
+ details = describeBody(path, json);
+ if (dumpDir && /\/responses$/.test(path)) {
+ mkdirSync(dumpDir, { recursive: true });
+ const headers = Object.fromEntries(Object.entries(req.headers).filter(([name]) => /^(x-codex|session_id|conversation_id|openai-beta|content-)/.test(name)));
+ writeFileSync(join(dumpDir, `${new Date(started).toISOString().replaceAll(":", "-")}-${id}.json`), JSON.stringify({ path, headers, body: redactImages(json) }, null, 2));
+ }
+ } 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 });
};
- connectUpstream(via).then((socket) => {
+ // body === null streams the request through unchanged.
+ const send = (headers: Record<string, string | string[]>, body: Buffer | null) => connectUpstream(via).then((socket) => {
// No `agent` option: with agent:false Node ignores createConnection and dials the host directly.
- const upstream = http.request({ host: UPSTREAM_HOST, method: req.method, path: req.url, headers: forwardHeaders(req.headers), createConnection: () => socket }, (answer) => {
+ const upstream = http.request({ host: UPSTREAM_HOST, method: req.method, path: req.url, headers, createConnection: () => socket }, (answer) => {
status = answer.statusCode ?? 0;
const headers: Record<string, string | string[]> = {};
for (const [name, value] of Object.entries(answer.headers)) if (value !== undefined && !HOP_BY_HOP.has(name)) headers[name] = value;
@@ -162,22 +271,46 @@ function main(): void {
upstream.on("error", (error) => { if (!res.headersSent) res.writeHead(502); res.end(); finish(String(error)); });
// Codex may drop the connection mid-stream; still log the request once.
res.on("close", () => finish(res.writableFinished ? undefined : "client closed before the response ended"));
- req.on("data", (chunk: Buffer) => { chunks.push(chunk); requestBytes += chunk.length; });
- req.pipe(upstream);
+ if (body) upstream.end(body);
+ else { collect(); req.pipe(upstream); }
}, (error) => {
res.writeHead(502, { "content-type": "text/plain" });
res.end(`codex-attachment-manager proxy: cannot reach ${UPSTREAM_HOST}`);
finish(String(error));
});
+ if (!rewrite) { send(forwardHeaders(req.headers), null); return; }
+ collect();
+ req.on("end", () => {
+ const original = Buffer.concat(chunks);
+ let out: { body: Buffer; report: Json };
+ try { out = rewriteBody(original, req.headers["content-encoding"] as string | undefined, identity.threadId!, sessionsDir); }
+ catch (error) { out = { body: original, report: { skipped: `rewrite failed: ${String(error)}` } }; }
+ extra = { rewrite: out.report };
+ const headers = forwardHeaders(req.headers);
+ headers["content-length"] = String(out.body.length);
+ send(headers, out.body);
+ });
};
const onUpgrade = (req: http.IncomingMessage, client: Duplex, head: Buffer) => {
const id = ++sequence;
const started = Date.now();
+ const path = (req.url ?? "/").split("?")[0];
+ const identity = requestIdentity(req.headers);
+ if (/\/responses$/.test(path) && (forceHttp || hasUnchecked(identity.threadId))) {
+ client.end("HTTP/1.1 426 Upgrade Required\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
+ log({ at: new Date(started).toISOString(), id, transport: "websocket", path, declined: 426, reason: forceHttp ? "--force-http" : "thread has unchecked images", ...identity });
+ return;
+ }
let up = head.length;
let down = 0;
let upstreamStatus: string | null = null;
connectUpstream(via).then((socket) => {
+ const connection = { client, socket, last: Date.now(), closedForSelection: false };
+ if (identity.threadId) {
+ if (!live.has(identity.threadId)) live.set(identity.threadId, new Set());
+ live.get(identity.threadId)!.add(connection);
+ }
const lines = [`${req.method} ${req.url} HTTP/1.1`];
for (let i = 0; i < req.rawHeaders.length; i += 2) {
const name = req.rawHeaders[i];
@@ -186,8 +319,8 @@ function main(): void {
socket.write(`${lines.join("\r\n")}\r\n\r\n`);
if (head.length) socket.write(head);
socket.once("data", (chunk: Buffer) => { upstreamStatus = chunk.toString("latin1", 0, Math.min(chunk.length, 40)).split("\r\n")[0]; });
- socket.on("data", (chunk: Buffer) => { down += chunk.length; });
- client.on("data", (chunk: Buffer) => { up += chunk.length; });
+ socket.on("data", (chunk: Buffer) => { down += chunk.length; connection.last = Date.now(); });
+ client.on("data", (chunk: Buffer) => { up += chunk.length; connection.last = Date.now(); });
socket.pipe(client);
client.pipe(socket);
let logged = false;
@@ -196,7 +329,8 @@ function main(): void {
logged = true;
socket.destroy();
client.destroy();
- log({ at: new Date(started).toISOString(), id, transport: "websocket", path: (req.url ?? "/").split("?")[0], upstreamStatus, upBytes: up, downBytes: down, ms: Date.now() - started, ...requestIdentity(req.headers) });
+ 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 });
};
socket.on("close", close);
client.on("close", close);
diff --git a/spike/src/rewrite.test.ts b/spike/src/rewrite.test.ts
new file mode 100644
index 0000000..d4bc2c7
--- /dev/null
+++ b/spike/src/rewrite.test.ts
@@ -0,0 +1,106 @@
+// Purpose: P2 — the rewrite rules: only unchecked images change; duplicate vs plain placeholders; locked results.
+// Input: synthetic request items; output: Node test assertions only.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import { findImages, type ImageRef } from "./images.ts";
+import { rewriteItems, type Described } from "./rewrite.ts";
+import { png } from "./testkit.ts";
+
+const url = (bytes: Buffer) => `data:image/png;base64,${bytes.toString("base64")}`;
+const red = png(4, 4, () => [255, 0, 0]);
+const blue = png(4, 4, () => [0, 0, 255]);
+const green = png(4, 4, () => [0, 255, 0]);
+
+const tagged = (name: string, n: number, bytes: Buffer) => [
+ { type: "input_text", text: `<image name=[Image #${n}] path="C:\\work\\${name}">` },
+ { type: "input_image", image_url: url(bytes), detail: "high" },
+ { type: "input_text", text: "</image>" },
+];
+// IMG-001 a.png (red), IMG-002 b.png (blue), IMG-003 b copy.png (blue), IMG-004 view_image of a.png (red),
+// IMG-005 hosted generation result (green).
+const items = () => [
+ { type: "message", id: "msg_dev", role: "developer", content: [{ type: "input_text", text: "instructions" }] },
+ { type: "message", id: "msg_1", role: "user", content: [{ type: "input_text", text: "三张图" }, ...tagged("a.png", 1, red), ...tagged("b.png", 2, blue), ...tagged("b copy.png", 3, blue)] },
+ { type: "message", id: "msg_2", role: "assistant", content: [{ type: "output_text", text: "收到" }] },
+ { type: "custom_tool_call", call_id: "c1", name: "exec", input: 'await tools.view_image({path:"C:\\\\work\\\\a.png"})' },
+ { type: "custom_tool_call_output", id: "ctco_1", call_id: "c1", output: [{ type: "input_text", text: "Script completed" }, { type: "input_image", image_url: url(red) }] },
+ { type: "image_generation_call", id: "ig_1", status: "completed", result: green.toString("base64") },
+];
+
+// Ids in order of appearance, as the thread index assigns them.
+function index(list: Array<Record<string, any>>) {
+ const refs = findImages(list);
+ const byKey = new Map(refs.map((ref, i) => [ref.key, { id: `IMG-00${i + 1}`, name: ref.name, label: ref.label, kind: ref.kind, turn: 1, width: ref.width, height: ref.height } satisfies Described]));
+ return { describe: (ref: ImageRef) => byKey.get(ref.key), keys: (...ids: string[]) => new Set(ids.map((id) => [...byKey].find(([, v]) => v.id === id)![0])) };
+}
+const noPixels = () => null;
+const texts = (item: Record<string, any>): string[] => (item.content ?? item.output).map((part: Record<string, any>) => part.text ?? part.type);
+const modes = (report: { replaced: Array<{ id: string; mode: string; sameAs: string | null }> }) => report.replaced.map((r) => [r.id, r.mode, r.sameAs]);
+
+test("nothing unchecked: the very same items come back", () => {
+ const input = items();
+ const { items: out, report } = rewriteItems(input, index(input).describe, new Set(), noPixels);
+ assert.equal(out, input);
+ assert.deepEqual([report.images, report.replaced.length], [5, 0]);
+});
+
+test("an unchecked upload becomes one plain placeholder in place of Codex's tag, image and closing tag", () => {
+ const input = items();
+ const { describe, keys } = index(input);
+ const { items: out, report } = rewriteItems(input, describe, keys("IMG-001", "IMG-004"), noPixels);
+ const parts = texts(out[1]);
+ assert.equal(parts.length, 1 + 1 + 3 + 3);
+ assert.match(parts[1], /^\[图片 IMG-001(\[Image #1\]) 未提供|a\.png|用户上传|第 1 轮|4×4\]\n/);
+ assert.match(parts[1], /需要 IMG-001/);
+ assert.doesNotMatch(parts[1], /C:\\work/, "no local path in the placeholder");
+ assert.match(texts(out[4])[1], /^\[图片 IMG-004 未提供|a\.png|工具查看的图片|第 1 轮|4×4\]/);
+ assert.deepEqual(modes(report), [["IMG-001", "plain", null], ["IMG-004", "plain", null]]);
+ assert.equal(out[0], input[0], "untouched items keep their identity");
+ assert.equal(input[1].content.length, 10, "the input is not mutated");
+});
+
+test("an unchecked copy points at the identical image that is still sent, in either direction", () => {
+ const input = items();
+ const { describe, keys } = index(input);
+ const later = rewriteItems(input, describe, keys("IMG-003"), noPixels);
+ assert.match(texts(later.items[1])[7], /^\[图片 IMG-003(\[Image #3\]) 未重复提供|b copy\.png|用户上传|第 1 轮|4×4\]\n这张图和 IMG-002(b\.png,第 1 轮)内容完全相同/);
+ assert.deepEqual(modes(later.report), [["IMG-003", "duplicate", "IMG-002"]]);
+ assert.deepEqual(modes(rewriteItems(input, describe, keys("IMG-001"), noPixels).report), [["IMG-001", "duplicate", "IMG-004"]]);
+});
+
+test("when every copy is unchecked, each gets a plain placeholder", () => {
+ const input = items();
+ const { describe, keys } = index(input);
+ assert.deepEqual(modes(rewriteItems(input, describe, keys("IMG-002", "IMG-003"), noPixels).report), [["IMG-002", "plain", null], ["IMG-003", "plain", null]]);
+});
+
+test("pixel-identical images with different bytes also count as the same content", () => {
+ const input = items();
+ const { describe, keys } = index(input);
+ const redId = findImages(input)[0].contentId;
+ const [blueKey] = keys("IMG-002");
+ const pixels = (ref: ImageRef) => (ref.contentId === redId || ref.key === blueKey ? "same-pixels" : null);
+ assert.deepEqual(modes(rewriteItems(input, describe, keys("IMG-002", "IMG-003", "IMG-004"), pixels).report), [
+ ["IMG-002", "duplicate", "IMG-001"],
+ ["IMG-003", "plain", null],
+ ["IMG-004", "duplicate", "IMG-001"],
+ ]);
+});
+
+test("tool-output images become text parts; hosted generation results stay and are reported as locked", () => {
+ const input = items();
+ const { describe, keys } = index(input);
+ const { items: out, report } = rewriteItems(input, describe, keys("IMG-004", "IMG-005"), noPixels);
+ assert.equal(texts(out[4])[0], "Script completed");
+ assert.match(texts(out[4])[1], /^\[图片 IMG-004 未重复提供|a\.png|工具查看的图片|第 1 轮|4×4\]\n这张图和 IMG-001(a\.png,第 1 轮)/);
+ assert.equal(out[5], input[5]);
+ assert.deepEqual(report.locked, ["IMG-005"]);
+});
+
+test("the same selection always produces the same text", () => {
+ const input = items();
+ const { describe, keys } = index(input);
+ const selected = keys("IMG-001", "IMG-003");
+ assert.equal(JSON.stringify(rewriteItems(input, describe, selected, noPixels).items), JSON.stringify(rewriteItems(items(), describe, selected, noPixels).items));
+});
diff --git a/spike/src/rewrite.ts b/spike/src/rewrite.ts
new file mode 100644
index 0000000..366013d
--- /dev/null
+++ b/spike/src/rewrite.ts
@@ -0,0 +1,70 @@
+// Purpose: P2 — replace the images the user unchecked with placeholder text in a Responses request's `input`.
+// Nothing else changes: checked images, unknown images and all other items are forwarded as they are.
+// Input: request items, a lookup into the thread index, the unchecked keys. Output: new items plus a metadata report.
+
+import { findImages, type ImageKind, type ImageRef } from "./images.ts";
+
+type Json = Record<string, any>;
+export type Described = { id: string; name: string | null; label: string | null; kind: ImageKind; turn: number | null; width: number | null; height: number | null };
+export type Replacement = { id: string; key: string; kind: ImageKind; mode: "plain" | "duplicate"; sameAs: string | null; base64Chars: number };
+export type RewriteReport = { images: number; replaced: Replacement[]; locked: string[]; sentContentIds: string[] };
+
+const KIND_TEXT: Record<ImageKind, string> = { upload: "用户上传", view: "工具查看的图片", generated: "生成的图片", tool: "工具结果里的图片" };
+
+function heading(image: Described, state: string): string {
+ const fields = [image.name ?? "未命名", KIND_TEXT[image.kind]];
+ if (image.turn !== null) fields.push(`第 ${image.turn} 轮`);
+ if (image.width && image.height) fields.push(`${image.width}×${image.height}`);
+ return `[图片 ${image.id}${image.label ? `(${image.label})` : ""} ${state}|${fields.join("|")}]`;
+}
+
+export function plainPlaceholder(image: Described): string {
+ return `${heading(image, "未提供")}\n用户为了控制上下文,这次没有提供这张图,你看不到它的内容,不要猜测或描述画面细节。如果回答需要看这张图,请在回复里写出“需要 ${image.id}”,用户可以在下一轮重新勾选提供;不要自己用工具去读取它。`;
+}
+
+export function duplicatePlaceholder(image: Described, same: Described): string {
+ const where = [same.name, same.turn !== null ? `第 ${same.turn} 轮` : "本轮"].filter(Boolean).join(",");
+ return `${heading(image, "未重复提供")}\n这张图和 ${same.id}(${where})内容完全相同,那一条在本次请求里照常提供,请直接参考那一条。`;
+}
+
+export function rewriteItems(
+ items: Json[],
+ describe: (ref: ImageRef) => Described | undefined,
+ unchecked: Set<string>,
+ pixelHash: (ref: ImageRef) => string | null,
+): { items: Json[]; report: RewriteReport } {
+ const refs = findImages(items);
+ const report: RewriteReport = { images: refs.length, replaced: [], locked: [], sentContentIds: [] };
+ const drop = refs.filter((ref) => unchecked.has(ref.key) && ref.replaceable && describe(ref));
+ for (const ref of refs) if (unchecked.has(ref.key) && !ref.replaceable) report.locked.push(describe(ref)?.id ?? ref.key);
+ const sent = refs.filter((ref) => !drop.includes(ref));
+ report.sentContentIds = sent.map((ref) => ref.contentId);
+ if (!drop.length) return { items, report };
+
+ const same = (a: ImageRef, b: ImageRef) => {
+ if (a.contentId === b.contentId) return true;
+ if (a.width !== b.width || a.height !== b.height) return false;
+ const pixels = pixelHash(a);
+ return pixels !== null && pixels === pixelHash(b);
+ };
+ const edits = new Map<number, Array<{ from: number; to: number; text: string }>>();
+ for (const ref of drop) {
+ const image = describe(ref)!;
+ const copy = sent.find((other) => same(other, ref));
+ const copyImage = copy ? describe(copy) ?? { id: "(新图片)", name: copy.name, label: copy.label, kind: copy.kind, turn: null, width: copy.width, height: copy.height } : null;
+ const text = copyImage ? duplicatePlaceholder(image, copyImage) : plainPlaceholder(image);
+ report.replaced.push({ id: image.id, key: ref.key, kind: ref.kind, mode: copyImage ? "duplicate" : "plain", sameAs: copyImage?.id ?? null, base64Chars: ref.base64Chars });
+ const list = edits.get(ref.item) ?? [];
+ list.push({ from: ref.openTag ?? ref.part!, to: ref.closeTag ?? ref.part!, text });
+ edits.set(ref.item, list);
+ }
+ const next = items.map((item, index) => {
+ const list = edits.get(index);
+ if (!list) return item;
+ const field = item.type === "message" ? "content" : "output";
+ const parts: Json[] = [...item[field]];
+ for (const edit of list.sort((a, b) => b.from - a.from)) parts.splice(edit.from, edit.to - edit.from + 1, { type: "input_text", text: edit.text });
+ return { ...item, [field]: parts };
+ });
+ return { items: next, report };
+}
diff --git a/spike/src/selection.ts b/spike/src/selection.ts
new file mode 100644
index 0000000..a968536
--- /dev/null
+++ b/spike/src/selection.ts
@@ -0,0 +1,37 @@
+// 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": "…" } } }.
+
+import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+export type Selection = { threadId: string; unchecked: Record<string, { id: string; at: string }> };
+
+export const selectionDir = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local", "selection");
+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 }>();
+
+function fileFor(threadId: string, dir: string): string {
+ if (!THREAD_ID.test(threadId)) throw new Error(`not a thread id: ${threadId}`);
+ return join(dir, `${threadId}.json`);
+}
+
+export function readSelection(threadId: string, dir = selectionDir): Selection {
+ const file = fileFor(threadId, dir);
+ if (!existsSync(file)) return { threadId, unchecked: {} };
+ const { mtimeMs, size } = statSync(file);
+ const known = cache.get(file);
+ if (known && known.mtimeMs === mtimeMs && known.size === size) return known.selection;
+ const selection = JSON.parse(readFileSync(file, "utf8")) as Selection;
+ cache.set(file, { mtimeMs, size, selection });
+ return selection;
+}
+
+// Written to a temporary file first, so the proxy never reads a half-written selection.
+export function writeSelection(selection: Selection, dir = selectionDir): void {
+ const file = fileFor(selection.threadId, dir);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(`${file}.tmp`, JSON.stringify(selection, null, 2));
+ renameSync(`${file}.tmp`, file);
+}
diff --git a/spike/src/testkit.ts b/spike/src/testkit.ts
new file mode 100644
index 0000000..c51584c
--- /dev/null
+++ b/spike/src/testkit.ts
@@ -0,0 +1,70 @@
+// Purpose: shared helpers for the P2 self-tests — synthetic PNG test images (no user material is ever sent) and a
+// turn runner for our own app-server.
+// Input: drawing callbacks / app-server handles. Output: PNG bytes, turn summaries.
+
+import zlib from "node:zlib";
+import type { AppServer } from "./appserver.ts";
+
+type Json = Record<string, any>;
+type Rgb = [number, number, number];
+
+export function png(width: number, height: number, pixel: (x: number, y: number) => Rgb): Buffer {
+ const raw = Buffer.alloc((width * 3 + 1) * height);
+ for (let y = 0; y < height; y++) {
+ const row = y * (width * 3 + 1);
+ for (let x = 0; x < width; x++) raw.set(pixel(x, y), row + 1 + x * 3);
+ }
+ const chunk = (type: string, data: Buffer) => {
+ const length = Buffer.alloc(4);
+ length.writeUInt32BE(data.length);
+ const crc = Buffer.alloc(4);
+ crc.writeUInt32BE(zlib.crc32(Buffer.concat([Buffer.from(type, "ascii"), data])));
+ return Buffer.concat([length, Buffer.from(type, "ascii"), data, crc]);
+ };
+ const header = Buffer.alloc(13);
+ header.writeUInt32BE(width, 0);
+ header.writeUInt32BE(height, 4);
+ header[8] = 8;
+ header[9] = 2;
+ return Buffer.concat([Buffer.from("89504e470d0a1a0a", "hex"), chunk("IHDR", header), chunk("IDAT", zlib.deflateSync(raw)), chunk("IEND", Buffer.alloc(0))]);
+}
+
+// Each image has one large shape and one small corner mark, so a test can ask about a detail
+// that a one-line description would not mention.
+const SIZE = 512;
+const inBox = (x: number, y: number, left: number, top: number, size: number) => x >= left && x < left + size && y >= top && y < top + size;
+
+export const testImages = {
+ // White background, red square in the middle, small black square in the bottom-right corner.
+ redSquare: () => png(SIZE, SIZE, (x, y) => inBox(x, y, 440, 440, 48) ? [0, 0, 0] : inBox(x, y, 136, 136, 240) ? [220, 30, 30] : [255, 255, 255]),
+ // Yellow background, blue disc in the middle, small green square in the top-left corner.
+ blueCircle: () => png(SIZE, SIZE, (x, y) => inBox(x, y, 24, 24, 48) ? [30, 160, 60] : (x - 256) ** 2 + (y - 256) ** 2 < 130 ** 2 ? [40, 70, 210] : [250, 220, 60]),
+ // Purple background, white upward triangle, small orange square in the top-right corner.
+ whiteTriangle: () => png(SIZE, SIZE, (x, y) => inBox(x, y, 440, 24, 48) ? [250, 140, 20] : y > 120 && y < 400 && Math.abs(x - 256) < (y - 120) * 0.6 ? [255, 255, 255] : [120, 50, 160]),
+ // 1024×1024 of reproducible noise (about 3 MB): shows what unchecking a large image saves, since it cannot compress.
+ noise: () => {
+ let state = 0x2545f491;
+ const next = () => { state ^= state << 13; state ^= state >>> 17; state ^= state << 5; return state & 0xff; };
+ return png(1024, 1024, () => [next(), next(), next()]);
+ },
+};
+
+export const text = (value: string) => ({ type: "text", text: value, text_elements: [] });
+
+export async function runTurn(server: AppServer, threadId: string, input: Json[], timeoutMs = 20 * 60_000): Promise<Json> {
+ const started = Date.now();
+ const before = server.notifications.length;
+ const { turn } = await server.request<{ turn: Json }>("turn/start", { threadId, input, effort: "low" }, 120_000);
+ const done = await server.waitFor((n) => n.method === "turn/completed" && n.params.turn?.id === turn.id, timeoutMs);
+ const mine = server.notifications.slice(before).filter((n) => n.params?.turnId === turn.id || n.params?.turn?.id === turn.id);
+ const items = mine.filter((n) => n.method === "item/completed").map((n) => n.params.item);
+ return {
+ turnId: turn.id,
+ status: done.params.turn.status,
+ error: done.params.turn.error ?? null,
+ ms: Date.now() - started,
+ tools: items.filter((item) => !["agentMessage", "reasoning", "userMessage"].includes(item.type)).map((item) => `${item.type}:${item.status ?? ""}`),
+ reply: items.filter((item) => item.type === "agentMessage").map((item) => item.text).join(" "),
+ errors: mine.filter((n) => n.method === "error").map((n) => ({ message: n.params.error?.message ?? "error", willRetry: n.params.willRetry ?? null })),
+ };
+}
diff --git a/spike/src/thread-index.test.ts b/spike/src/thread-index.test.ts
new file mode 100644
index 0000000..be0c88d
--- /dev/null
+++ b/spike/src/thread-index.test.ts
@@ -0,0 +1,63 @@
+// Purpose: P2 — the thread index read from rollouts: stable ids in history order, turn numbers, incremental
+// re-reads of an appended file, and paginated segments chained through history_base.
+// Input: synthetic rollouts in a temporary directory; output: Node test assertions only.
+
+import assert from "node:assert/strict";
+import { appendFileSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import { loadThreadIndex } from "./thread-index.ts";
+import { png } from "./testkit.ts";
+
+const THREAD = "01a0d301-0000-7000-8000-000000000001";
+const url = (bytes: Buffer) => `data:image/png;base64,${bytes.toString("base64")}`;
+const red = png(4, 4, () => [255, 0, 0]);
+const blue = png(6, 2, () => [0, 0, 255]);
+
+const line = (type: string, payload: Record<string, any>) => `${JSON.stringify({ timestamp: "2026-09-24T10:00:00Z", type, payload })}\n`;
+const turn = (id: string) => line("event_msg", { type: "task_started", turn_id: id });
+const upload = (id: string, turnId: string, name: string, bytes: Buffer) => line("response_item", {
+ type: "message", id, role: "user",
+ content: [{ type: "input_text", text: `<image name=[Image #1] path="C:\\w\\${name}">` }, { type: "input_image", image_url: url(bytes) }, { type: "input_text", text: "</image>" }],
+ internal_chat_message_metadata_passthrough: { turn_id: turnId },
+});
+
+function sessions(): { dir: string; day: string } {
+ const dir = mkdtempSync(join(tmpdir(), "cam-sessions-"));
+ const day = join(dir, "2026", "09", "24");
+ mkdirSync(day, { recursive: true });
+ return { dir, day };
+}
+
+test("ids follow history order, turns come from task_started, and a repeated item is counted once", () => {
+ const { dir, day } = sessions();
+ writeFileSync(join(day, `rollout-2026-09-24T10-00-00-${THREAD}.jsonl`),
+ line("session_meta", { id: THREAD }) + turn("t1") + upload("msg_1", "t1", "a.png", red) + turn("t2") + upload("msg_2", "t2", "b.png", blue) + upload("msg_1", "t1", "a.png", red));
+ const index = loadThreadIndex(dir, THREAD);
+ assert.deepEqual(index.images.map((i) => [i.id, i.name, i.turn, i.width, i.height]), [["IMG-001", "a.png", 1, 4, 4], ["IMG-002", "b.png", 2, 6, 2]]);
+ assert.equal(index.turns, 2);
+ assert.ok(index.images[0].pixelSha256);
+});
+
+test("appending to the rollout adds new ids and keeps the old ones", () => {
+ const { dir, day } = sessions();
+ const file = join(day, `rollout-2026-09-24T10-00-00-${THREAD}.jsonl`);
+ writeFileSync(file, line("session_meta", { id: THREAD }) + turn("t1") + upload("msg_1", "t1", "a.png", red));
+ assert.deepEqual(loadThreadIndex(dir, THREAD).images.map((i) => i.id), ["IMG-001"]);
+ // A half-written last line is left for the next read.
+ appendFileSync(file, turn("t2") + upload("msg_2", "t2", "b.png", blue).slice(0, 40));
+ assert.deepEqual(loadThreadIndex(dir, THREAD).images.map((i) => i.name), ["a.png"]);
+ appendFileSync(file, upload("msg_2", "t2", "b.png", blue).slice(40));
+ assert.deepEqual(loadThreadIndex(dir, THREAD).images.map((i) => [i.id, i.name, i.turn]), [["IMG-001", "a.png", 1], ["IMG-002", "b.png", 2]]);
+});
+
+test("a later segment inherits its base segment only up to history_base.end_byte_offset", () => {
+ const { dir, day } = sessions();
+ const first = line("session_meta", { id: THREAD }) + turn("t1") + upload("msg_1", "t1", "a.png", red);
+ writeFileSync(join(day, `rollout-2026-09-24T10-00-00-${THREAD}.jsonl`), first + upload("msg_x", "t1", "dropped.png", blue));
+ const segment = "01a0d301-0000-7000-8000-00000000000b";
+ writeFileSync(join(day, `rollout-2026-09-24T10-05-00-${THREAD}_${segment}.jsonl`),
+ line("session_meta", { id: THREAD, history_base: { thread_id: THREAD, end_byte_offset: Buffer.byteLength(first) } }) + turn("t2") + upload("msg_2", "t2", "b.png", blue));
+ assert.deepEqual(loadThreadIndex(dir, THREAD).images.map((i) => [i.id, i.name]), [["IMG-001", "a.png"], ["IMG-002", "b.png"]]);
+});
diff --git a/spike/src/thread-index.ts b/spike/src/thread-index.ts
new file mode 100644
index 0000000..42818d7
--- /dev/null
+++ b/spike/src/thread-index.ts
@@ -0,0 +1,132 @@
+// Purpose: P2 — the image timeline of one thread, read from its rollout (read-only): every image occurrence in
+// history order with a stable id (IMG-001…), turn number, name, size and content hashes. The CLI and the proxy both
+// derive it from the same files, so they agree on ids without sharing state.
+// Input: the sessions directory and a thread id. Output: ThreadIndex (in memory; files are parsed incrementally).
+
+import { closeSync, openSync, readdirSync, readSync, statSync } from "node:fs";
+import { basename, join } from "node:path";
+import { findImages, type ImageRef } from "./images.ts";
+import { decodePng } from "./png.ts";
+
+type Json = Record<string, any>;
+export type IndexedImage = ImageRef & { id: string; turn: number | null; bytes: number; pixelSha256: string | null };
+export type ThreadIndex = { threadId: string; images: IndexedImage[]; byKey: Map<string, IndexedImage>; turns: number };
+type Parsed = { offset: number; type: string; payload: Json };
+type FileCache = { size: number; mtimeMs: number; parsedTo: number; records: Parsed[] };
+
+const SEGMENT_NAME = /rollout-[0-9T:-]+-([0-9a-f-]{36})(?:_([0-9a-f-]{36}))?\.jsonl$/;
+const files = new Map<string, FileCache>();
+const pixelHashes = new Map<string, string | null>();
+
+function walk(directory: string): string[] {
+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
+ const full = join(directory, entry.name);
+ return entry.isDirectory() ? walk(full) : entry.isFile() ? [full] : [];
+ });
+}
+
+// Rollouts are append-only: parse only the complete lines added since the last read.
+function records(file: string): Parsed[] {
+ const stat = statSync(file);
+ let cache = files.get(file);
+ if (!cache || stat.size < cache.parsedTo) cache = { size: 0, mtimeMs: 0, parsedTo: 0, records: [] };
+ if (stat.size !== cache.size || stat.mtimeMs !== cache.mtimeMs) {
+ const length = stat.size - cache.parsedTo;
+ const buffer = Buffer.alloc(length);
+ const fd = openSync(file, "r");
+ try { readSync(fd, buffer, 0, length, cache.parsedTo); } finally { closeSync(fd); }
+ let start = 0;
+ for (let end = buffer.indexOf(0x0a); end >= 0; end = buffer.indexOf(0x0a, start)) {
+ const text = buffer.toString("utf8", start, end).replace(/\r$/, "");
+ // A damaged line is skipped rather than failing the whole index; unknown images are sent unchanged anyway.
+ let record: Json | null = null;
+ if (text.trim()) { try { record = JSON.parse(text); } catch { record = null; } }
+ if (record) cache.records.push({ offset: cache.parsedTo + start, type: record.type, payload: record.payload ?? {} });
+ start = end + 1;
+ }
+ cache.parsedTo += start;
+ cache.size = stat.size;
+ cache.mtimeMs = stat.mtimeMs;
+ files.set(file, cache);
+ }
+ return cache.records;
+}
+
+// The thread's segments: the first uses the thread id itself, later pages are named <thread>_<segment>.
+function segmentsOf(sessionsDir: string, threadId: string): Map<string, string> {
+ const segments = new Map<string, string>();
+ for (const file of walk(sessionsDir)) {
+ const match = SEGMENT_NAME.exec(basename(file));
+ if (match && match[1] === threadId) segments.set(match[2] ?? match[1], file);
+ }
+ return segments;
+}
+
+const baseOf = (file: string): Json | null => (records(file)[0]?.type === "session_meta" ? records(file)[0].payload.history_base ?? null : null);
+
+function effective(segments: Map<string, string>, segmentId: string, endOffset = Number.POSITIVE_INFINITY): Parsed[] {
+ const file = segments.get(segmentId);
+ if (!file) throw new Error(`rollout segment not found: ${segmentId}`);
+ const base = baseOf(file);
+ const inherited = base ? effective(segments, base.thread_id, base.end_byte_offset) : [];
+ return [...inherited, ...records(file).filter((record) => record.offset < endOffset)];
+}
+
+function pixelHash(ref: ImageRef, value: string): string | null {
+ if (ref.mime !== "image/png") return null;
+ if (!pixelHashes.has(ref.contentId)) {
+ try { pixelHashes.set(ref.contentId, decodePng(Buffer.from(value, "base64")).pixelSha256); } catch { pixelHashes.set(ref.contentId, null); }
+ }
+ return pixelHashes.get(ref.contentId) ?? null;
+}
+
+export function imageData(items: Json[], ref: ImageRef): string | null {
+ const item = items[ref.item];
+ if (ref.part === null) return typeof item?.result === "string" ? item.result : null;
+ const url = (item?.content ?? item?.output)?.[ref.part]?.image_url;
+ return typeof url === "string" ? url.slice(url.indexOf(",") + 1) : null;
+}
+
+export function pixelHashOf(items: Json[], ref: ImageRef): string | null {
+ const value = imageData(items, ref);
+ return value === null ? null : pixelHash(ref, value);
+}
+
+export function buildIndex(threadId: string, history: Parsed[]): ThreadIndex {
+ const turnNumbers = new Map<string, number>();
+ const items: Json[] = [];
+ const activeTurn: Array<string | null> = [];
+ let current: string | null = null;
+ for (const record of history) {
+ if (record.type === "event_msg" && record.payload.type === "task_started" && record.payload.turn_id) {
+ current = record.payload.turn_id;
+ if (!turnNumbers.has(current!)) turnNumbers.set(current!, turnNumbers.size + 1);
+ }
+ if (record.type === "response_item") { items.push(record.payload); activeTurn.push(current); }
+ }
+ const images: IndexedImage[] = [];
+ const byKey = new Map<string, IndexedImage>();
+ for (const ref of findImages(items)) {
+ if (byKey.has(ref.key)) continue;
+ const turnId = ref.turnId ?? activeTurn[ref.item];
+ const entry: IndexedImage = {
+ ...ref,
+ id: `IMG-${String(images.length + 1).padStart(3, "0")}`,
+ turn: turnId ? turnNumbers.get(turnId) ?? null : null,
+ bytes: Math.floor((ref.base64Chars * 3) / 4),
+ pixelSha256: pixelHashOf(items, ref),
+ };
+ images.push(entry);
+ byKey.set(ref.key, entry);
+ }
+ return { threadId, images, byKey, turns: turnNumbers.size };
+}
+
+export function loadThreadIndex(sessionsDir: string, threadId: string): ThreadIndex {
+ const segments = segmentsOf(sessionsDir, threadId);
+ if (!segments.size) throw new Error(`no rollout found for thread ${threadId}`);
+ const bases = new Set([...segments.values()].map((file) => baseOf(file)?.thread_id).filter(Boolean));
+ const heads = [...segments.keys()].filter((id) => !bases.has(id));
+ if (heads.length !== 1) throw new Error(`expected one latest rollout segment for ${threadId}, found ${heads.length}`);
+ return buildIndex(threadId, effective(segments, heads[0]));
+}