Stop paying the multimodal tax. Your AI agent keeps every image it has seen but only sends the ones it needs: lighter chats, no endless reconnecting, no starting over. Works with Codex, Claude Code, Cline, Gemini CLI, OpenCode, WorkBuddy and more. Install once, forget it.
TypeScript ai-agentsai-imageclaude-codeclaude-code-pluginclinecodexcodex-plugincomputer-usecontext-engineeringcontext-managementdeveloper-toolsgemini-cliimage-generationmcpmultimodalmultimodal-aiopencodeqwen-codetoken-optimizationvision-language-model
feat(compaction): put dropped images back as one line each, Codex too
chipfighter08c6a9c27d17
diff --git a/plugin/src/claude-rewrite.ts b/plugin/src/claude-rewrite.tsindex 13e00da..853cc8b 100644--- a/plugin/src/claude-rewrite.ts+++ b/plugin/src/claude-rewrite.ts@@ -17,7 +17,7 @@import type { ClaudeIndex, ClaudeImage } from "./claude-index.ts";import { imageDigest, type ImageDigest, type ImageKind } from "./images.ts";import type { Lang } from "./language.ts";-import { autoPlaceholder, claudeNote, compactedNote, copyNote, duplicatePlaceholder, featureNote, hereNote, includedLabel, newImageWord, plainPlaceholder, type Described, type RewriteReport } from "./rewrite.ts";+import { autoPlaceholder, claudeNote, compactedNote, compactList, copyNote, duplicatePlaceholder, featureNote, hereNote, includedLabel, newImageWord, plainPlaceholder, type Described, type RewriteReport } from "./rewrite.ts";type Json = Record<string, any>;// msg: the message; part: the block in its content; sub: for an image in a tool result, its position in that result.@@ -249,11 +249,14 @@ export function addCompacted(messages: Json[], summary: string, listed: Describeconst message = messages[at];const content: Json[] = typeof message.content === "string" ? [{ type: "text", text: message.content }] : [...message.content];const sent = new Map(resend.map(({ image, block }) => [image.id, block]));- const added = listed.flatMap((image): Json[] => {+ // v0.10: the ones still sent with their labels, then the others one line each (compactList), not a placeholder+ // apiece.+ const resent = listed.flatMap((image): Json[] => {const block = sent.get(image.id);- if (block) return [{ type: "text", text: includedLabel(image, lang) }, block];- return [{ type: "text", text: auto ? autoPlaceholder(image, lang) : plainPlaceholder(image, lang) }];+ return block ? [{ type: "text", text: includedLabel(image, lang) }, block] : [];});+ const missing = listed.filter((image) => !sent.has(image.id));+ const added: Json[] = [...resent, ...(missing.length ? [{ type: "text", text: compactList(missing, lang) }] : [])];content.splice(content.findIndex(holdsSummary(summary)) + 1, 0, ...added);const next = [...messages];next[at] = { ...message, content };diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.tsindex 74d3962..d3fd705 100644--- a/plugin/src/proxy.ts+++ b/plugin/src/proxy.ts@@ -42,10 +42,10 @@ import { applyClaudeSelection, claudeImageFor, loadClaudePanelState, type Claudeimport { claudeRequestStatsDirOf, claudeSelectionDirOf, dataDir, pixelCacheDirOf, proxyLogDirOf, selectionDirOf } from "./paths.ts";import { recordRequest } from "./request-stats.ts";import { readRoute, registerRoute, routeBaseUrl, routingPort, validateBaseUrl, type Platform } from "./routes.ts";-import { rewriteItems, type Described } from "./rewrite.ts";+import { addCodexCompacted, rewriteItems, type Described } from "./rewrite.ts";import { connectDirectly, pluginGone, usesEngine } from "./setup.ts";import { claudeSelection, effectiveSelection, ensureAutoDefault, ensureStableIds, selectionDir, sideChatSelection, stableIdsSince } from "./selection.ts";-import { loadThreadIndex, pixelHashOf, pixelHashOfData, setPixelCache, sideChatOrigin, writesNotes, type ThreadIndex } from "./thread-index.ts";+import { imageData, loadThreadIndex, pixelHashOf, pixelHashOfData, setPixelCache, sideChatOrigin, writesNotes, type ThreadIndex } from "./thread-index.ts";type Json = Record<string, any>;const here = dirname(fileURLToPath(import.meta.url));@@ -352,7 +352,26 @@ export function rewriteBody(original: Buffer, encoding: string | undefined, thre}// v0.8: feature lines in a task's own requests, not a side chat's or a subagent's.const features = !origin && writesNotes(sessionsDir, threadId);- const { items, report } = rewriteItems(json.input, describe, leaveOut, pixels, { lang: currentLang(), copies, features, ...(selection.auto ? { auto: { currentTurn: current } } : {}) });+ const rewritten = rewriteItems(json.input, describe, leaveOut, pixels, { lang: currentLang(), copies, features, ...(selection.auto ? { auto: { currentTurn: current } } : {}) });+ const { report } = rewritten;+ let items = rewritten.items;+ // v0.10: after Codex compacted the task, the images its compaction did not keep (thread-index.ts), right after its+ // compaction item: pinned ones (in manual mode, checked ones) as originals, the others one line each.+ let compacted: Json | null = null;+ const dropped = features ? index.images.filter((image) => image.compacted) : [];+ if (dropped.length) {+ const inRequest = new Set(findImages(json.input).map((ref) => ref.key));+ const listed = dropped.filter((image) => !inRequest.has(image.key) && !copies.has(image.key)).map((image) => describe(image)!).filter(Boolean);+ const resend = dropped.filter((image) => !inRequest.has(image.key) && !leaveOut.has(image.key) && !copies.has(image.key)).flatMap((image) => {+ const data = index.items ? imageData(index.items, image) : null;+ return data ? [{ image: describe(image)!, url: `data:${image.mime ?? "image/png"};base64,${data}` }] : [];+ });+ const added = addCodexCompacted(items, listed, resend, { lang: currentLang(), auto: !!selection.auto });+ if (added.at !== null) {+ items = added.items;+ compacted = { at: added.at, listed: listed.length, resent: resend.map(({ image }) => image.id) };+ }+ }const summary: Json = {images: report.images,replaced: report.replaced.map(({ key: _key, ...rest }) => rest),@@ -363,8 +382,9 @@ export function rewriteBody(original: Buffer, encoding: string | undefined, thre...(origin ? { sideChatOf: origin } : {}),...(report.featureAt !== undefined ? { featureAt: report.featureAt, labeled: report.labeled ?? 0 } : {}),...(report.unknown ? { unknown: report.unknown } : {}),+ ...(compacted ? { compacted } : {}),};- if (!report.replaced.length && !report.copies.length && report.featureAt === undefined) return { body: original, report: summary };+ if (!report.replaced.length && !report.copies.length && report.featureAt === undefined && !compacted) return { body: original, report: summary };json.input = items;const next = Buffer.from(JSON.stringify(json), "utf8");const body = encodeBody(next, encoding);diff --git a/plugin/src/rewrite.ts b/plugin/src/rewrite.tsindex afced83..dffbc43 100644--- a/plugin/src/rewrite.ts+++ b/plugin/src/rewrite.ts@@ -41,8 +41,12 @@ type Words = {// each message holding omitted images, naming them.toolNote: string; here: (list: string) => string; hereAuto: (list: string) => string; listItem: (id: string, name: string | null, kind: string) => string;// v0.5, Claude Code only: after a compaction summary, the images from before it, which of them are not sent this- // time, and how to get one back.- compacted: (list: string, missing: string | null, auto: boolean) => string;+ // time, and how to get one back. v0.10: how many and their ids, no longer listed; those not sent are one line each+ // in a list after the summary (compactHeader, compactLine).+ compacted: (count: number, range: string, missing: number, auto: boolean) => string;+ compactHeader: (count: number) => string;+ // v0.10, Codex: the images its compaction did not keep, put back after it: how many, how many sent as originals.+ codexCompacted: (count: number, resent: number, auto: boolean) => string;// v0.8: how to write feature lines and note ratings; the placeholder's line with them; how long each may be shown.featureNote: string; notes: (line: string | null, ratings: Rating[]) => string; caps: { line: number; rating: number };};@@ -99,15 +103,27 @@ const WORDS: Record<Lang, Words> = {// checked again: the model looked for the image it had asked for in the user's new message ("这次消息里没有附上"),// as GPT-6 Luna did in v0.1-25; with nothing left out the full note is not there to say where it comes back. Once it// answered from it, it called its earlier "需要 IMG-001" a mistake ("一直在我的上下文里"), in both languages.- compacted: (list, missing, auto) => [- `${missing === null ? "上下文管理说明(来自用户安装的上下文素材管理工具):" : "上下文管理说明:"}上面这条消息里,摘要之前的对话中有这些图片:${list}。压缩对话时它们被移出了上下文;这个工具把用户${auto ? "固定发送" : "勾选要发送"}的那些放回了摘要后面,前面标着“[图片 IMG-xxx 已提供…]”,紧接着就是原图:它们现在就在你面前,被问到时直接看图回答,不要说看不到。${missing === null ? `即使它之前被省略过${auto ? "" : "、或者正是你要过的图"},也是这样:用户${auto ? "固定发送" : "勾回"}的图回到这里,不会出现在用户的新消息里,不要让用户重新附上。` : ""}这一段是这个工具每次请求时重新放的:图被省略的那些请求里,这里并没有它;它现在出现在你之前的回复前面,只是因为这次放了回来。所以你之前说看不到哪张图,当时是实情,不是错误,不用纠正。`,- ...(missing === null ? [] : [- `这次没有提供的是 ${missing}(${auto ? "自动选图开着,之前各轮的图默认不发" : "用户取消了勾选"},为了节省上下文):摘要后面它们的位置换成了“[图片 IMG-xxx 已省略…]”这样的占位文字,那是这次请求才换上的。你之前看过它们的原图:在压缩之前的对话里,有的在压缩之后也提供过;你对它们的描述和据此做出的判断,不管是在摘要里还是在后面的回复里,都是看着原图做出的,仍然有效,不要收回,也不要说成是猜测或编造。${auto ? "现在你看不到它们,不要补充之前没说过的细节。" : "现在你看不到它们:被问到时,如实说现在看不到(被用户省略了),不要补充之前没说过的细节。"}`,+ compacted: (count, range, missing, auto) => [+ `${missing === 0 ? "上下文管理说明(来自用户安装的上下文素材管理工具):" : "上下文管理说明:"}上面这条消息里,摘要之前的对话中有 ${count} 张图片(${range})。压缩对话时它们被移出了上下文;这个工具把它们放回了摘要后面:用户${auto ? "固定发送" : "勾选要发送"}的那些前面标着“[图片 IMG-xxx 已提供…]”,紧接着就是原图,它们现在就在你面前,被问到时直接看图回答,不要说看不到。${missing === 0 ? `即使它之前被省略过${auto ? "" : "、或者正是你要过的图"},也是这样:用户${auto ? "固定发送" : "勾回"}的图回到这里,不会出现在用户的新消息里,不要让用户重新附上。` : ""}这一段是这个工具每次请求时重新放的:图被省略的那些请求里,这里并没有它;它现在出现在你之前的回复前面,只是因为这次放了回来。所以你之前说看不到哪张图,当时是实情,不是错误,不用纠正。`,+ ...(missing === 0 ? [] : [+ `其余 ${missing} 张这次没有附原图(${auto ? "自动选图开着,之前各轮的图默认不发" : "用户取消了勾选"},为了节省上下文):它们在摘要后面的清单里,一张一行,写着编号、名称和你当时记下的特征与评价,清单是这次请求才放上的。你之前看过它们的原图:在压缩之前的对话里,有的在压缩之后也提供过;你对它们的描述和据此做出的判断,不管是在摘要里还是在后面的回复里,都是看着原图做出的,仍然有效,不要收回,也不要说成是猜测或编造。${auto ? "现在你看不到它们,不要补充之前没说过的细节。" : "现在你看不到它们:被问到时,如实说现在看不到(被用户省略了),不要补充之前没说过的细节。"}`,auto? "之前说过的内容不够用时,调用 cam_view_image 工具,传入编号取回原图;不要让用户重新上传。": "问题得看其中某张图才能回答时,不要只说答不了,在回复里单独写一行“需要 IMG-xxx”(写出编号,几张就都写上):用户看到这一行才知道该勾回哪张图,勾回后原图回到它的位置,你就能看着回答;不要让用户重新上传或重新提供。",]),].join("\n"),+ compactHeader: (count) => `[压缩之前的图片,这次没有附原图的 ${count} 张:编号|名称|来源|轮次|特征和评价]`,+ codexCompacted: (count, resent, auto) => [+ `上下文管理说明(来自用户安装的上下文素材管理工具):这个任务压缩过对话。压缩时,之前各轮里工具查看、生成或返回的 ${count} 张图片没有保留下来,这个工具把它们放回了这里。`,+ resent ? `其中用户${auto ? "固定发送" : "勾选要发送"}的 ${resent} 张,原图就在后面,前面标着“[图片 IMG-xxx 已提供…]”:它们现在就在你面前,被问到时直接看图回答,不要说看不到。` : null,+ count > resent ? `其余 ${count - resent} 张这次没有附原图(${auto ? "自动选图开着,之前各轮的图默认不发" : "用户取消了勾选"},为了节省上下文),在下面的清单里一张一行,写着编号、名称和你当时记下的特征与评价。` : null,+ "这些图片在它们出现的那一轮真实存在,你当时看过;你之前对它们的描述,以及据此做出的判断,都是看着原图做出的,仍然有效,不要收回,也不要说成是猜测或编造。现在看不到原图的,不要补充之前没说过的细节。",+ count > resent+ ? auto+ ? "回答需要看清单里的某张图、而你之前说过的内容不够用时,调用 cam_view_image 工具,传入它的编号(几张就一次传几个),原图会出现在这次的工具结果里;不要让用户重新上传,也不要用其他工具去读取图片文件。"+ : "问题得看清单里某张图才能回答时,在回复里单独写一行“需要 IMG-xxx”(写出编号,几张就都写上):用户勾回后,原图会回到这里;不要让用户重新上传。"+ : null,+ ].filter((line) => line !== null).join("\n"),fetch: {title: "查看被省略的图片",description: "查看这个任务里一张或几张被省略的图片的原图。被省略的图片在对话里显示为“[图片 IMG-xxx 已省略…]”。只在回答需要看图、而你之前对它说过的内容不够用时调用;取回的原图只在本轮提供。",@@ -173,15 +189,27 @@ const WORDS: Record<Lang, Words> = {here: (list) => `Context management note: in the message above, ${list} were original images at the time, and you looked at them then; what you said about them and the judgments you based on it remain valid, so do not take them back or call them guesses or made up. The placeholder text there was put in only for this request; it is not what was there at the time. You cannot see them now: if asked, say so truthfully (the user left them out), and do not add details you did not mention before. When a question can only be answered by looking at one of them, do not just say you cannot answer; write a line "need IMG-xxx" in your reply (with its number; list each one needed): that line is how the user learns which image to check again, and once they do, the original comes back in its place and you can answer from it.`,hereAuto: (list) => `Context management note: in the message above, ${list} were original images at the time, and you looked at them then; what you said about them and the judgments you based on it remain valid, so do not take them back or call them guesses or made up. The placeholder text there was put in only for this request (automatic image selection); it is not what was there at the time. When what you said before is not enough, fetch the original with cam_view_image; do not add details you did not mention before.`,listItem: (id, name, kind) => `${id} (${[name, kind].filter(Boolean).join(", ")})`,- compacted: (list, missing, auto) => [- `${missing === null ? "Context management note (from the context asset manager the user installed): " : "Context management note: "}in the message above, the conversation before the summary had these images: ${list}. Compacting the conversation took them out of context; this tool put the ones the user ${auto ? "pinned" : "checked to send"} back right after the summary, each marked "[Image IMG-xxx included…]" with the original image right after it. They are in front of you now: when asked about one, look at it and answer from it, and do not say you cannot see it.${missing === null ? ` This holds even for an image omitted before${auto ? "" : " or one you asked for"}: an image the user ${auto ? "pins" : "checks again"} comes back there, not in the user's new message, so do not ask for it to be attached again.` : ""} This tool rebuilds this part for every request: in the requests where an image was left out, it was not here; it shows up before your earlier replies now only because it was put back for this request. So if you said before that you could not see an image, that was true then, not a mistake; do not correct it.`,- ...(missing === null ? [] : [- `Not included this time: ${missing} (${auto ? "automatic image selection is on, so images from earlier turns are left out by default" : "the user unchecked them"}, to save context). After the summary, where they would be, there is placeholder text such as "[Image IMG-xxx omitted…]", put in only for this request. You saw their originals: in the conversation before the compaction, and some also after it. What you said about them and the judgments you based on it, in the summary or in your later replies, were made looking at the original images and remain valid; do not take them back or call them guesses or made up. ${auto ? "You cannot see them now, so do not add details you did not mention before." : "You cannot see them now: if asked, say so truthfully (the user left them out), and do not add details you did not mention before."}`,+ compacted: (count, range, missing, auto) => [+ `${missing === 0 ? "Context management note (from the context asset manager the user installed): " : "Context management note: "}in the message above, the conversation before the summary had ${count} images (${range}). Compacting the conversation took them out of context; this tool put them back right after the summary: the ones the user ${auto ? "pinned" : "checked to send"} are marked "[Image IMG-xxx included…]" with the original image right after it. They are in front of you now: when asked about one, look at it and answer from it, and do not say you cannot see it.${missing === 0 ? ` This holds even for an image omitted before${auto ? "" : " or one you asked for"}: an image the user ${auto ? "pins" : "checks again"} comes back there, not in the user's new message, so do not ask for it to be attached again.` : ""} This tool rebuilds this part for every request: in the requests where an image was left out, it was not here; it shows up before your earlier replies now only because it was put back for this request. So if you said before that you could not see an image, that was true then, not a mistake; do not correct it.`,+ ...(missing === 0 ? [] : [+ `The other ${missing} are not included as originals this time (${auto ? "automatic image selection is on, so images from earlier turns are left out by default" : "the user unchecked them"}, to save context): they are in the list after the summary, one line each, with the id, name, and the features and ratings you noted; the list was put there only for this request. You saw their originals: in the conversation before the compaction, and some also after it. What you said about them and the judgments you based on it, in the summary or in your later replies, were made looking at the original images and remain valid; do not take them back or call them guesses or made up. ${auto ? "You cannot see them now, so do not add details you did not mention before." : "You cannot see them now: if asked, say so truthfully (the user left them out), and do not add details you did not mention before."}`,auto? "When what you said before is not enough, call the cam_view_image tool with the id to fetch the original; do not ask the user to upload it again.": "When a question can only be answered by looking at one of them, do not just say you cannot answer; write a line \"need IMG-xxx\" in your reply (with its number; list each one needed): that line is how the user learns which image to check again, and once they do, the original comes back in its place and you can answer from it. Do not ask the user to upload or provide it again.",]),].join("\n"),+ compactHeader: (count) => `[Images from before the compaction, the ${count} not included as originals this time: id | name | source | turn | features and ratings]`,+ codexCompacted: (count, resent, auto) => [+ `Context management note (from the context asset manager the user installed): this task's conversation was compacted. The compaction did not keep ${count} images that tools viewed, generated or returned in earlier turns; this tool put them back here.`,+ resent ? `Of them, the ${resent} the user ${auto ? "pinned" : "checked to send"} follow with their originals, each marked "[Image IMG-xxx included…]": they are in front of you now; when asked about one, look at it and answer from it, and do not say you cannot see it.` : null,+ count > resent ? `The other ${count - resent} are not included as originals this time (${auto ? "automatic image selection is on, so images from earlier turns are left out by default" : "the user unchecked them"}, to save context): they are in the list below, one line each, with the id, name, and the features and ratings you noted.` : null,+ "These images really existed in the turn where they appeared, and you looked at them then; what you said about them, and the judgments you based on it, were made looking at the original images and remain valid; do not take them back or call them guesses or made up. Do not add details you did not mention before about images you cannot see now.",+ count > resent+ ? auto+ ? "When an answer needs an image from the list and what you said about it before is not enough, call the cam_view_image tool with its id (several ids at once if you need several); the original comes back in that tool result. Do not ask the user to upload images again, and do not read image files with other tools."+ : "When a question can only be answered by looking at an image from the list, write a line \"need IMG-xxx\" in your reply (with its number; list each one needed): once the user checks it again, the original comes back here. Do not ask the user to upload it again."+ : null,+ ].filter((line) => line !== null).join("\n"),fetch: {title: "View omitted images",description: "View the originals of one or more omitted images in this task. Omitted images appear in the conversation as \"[Image IMG-xxx omitted…]\". Call it only when an answer needs to look at an image and what you said about it before is not enough; the originals are included only in this turn.",@@ -278,12 +306,48 @@ export function hereNote(images: Described[], lang: Lang = "zh", auto = false):// v0.5, Claude Code only: the note after the message holding a compaction summary, listing the images from before it// and naming the ones not sent this time. Their placeholders are the first in the request, so the full note comes// first, as it does after the first message holding placeholders (claude-rewrite.ts).+// v0.10: the images are no longer listed in the note, only counted with their ids (the ones before the latest+// compaction are the first ids); those not sent are in the list after the summary (compactList).export function compactedNote(images: Described[], sent: Set<string>, lang: Lang = "zh", auto = false): string {const words = WORDS[lang];- const list = (some: Described[]) => some.map((image) => words.listItem(image.id, image.name, words.kind[image.kind])).join(words.separator);- const missing = images.filter((image) => !sent.has(image.id));- const own = words.compacted(list(images), missing.length ? list(missing) : null, auto);- return missing.length ? `${claudeNote(lang, auto)}\n${own}` : own;+ const missing = images.filter((image) => !sent.has(image.id)).length;+ const range = images.length > 1 ? `${images[0].id}${lang === "zh" ? " 到 " : " to "}${images[images.length - 1].id}` : images[0]?.id ?? "";+ const own = words.compacted(images.length, range, missing, auto);+ return missing ? `${claudeNote(lang, auto)}\n${own}` : own;+}++// v0.10: an image put back after a compaction without its original, in one line: id, name, source, turn, and what+// the model noted (as in a placeholder). A placeholder apiece repeated the same words for every image; a session with+// 130 images before its compaction took 1.3–1.9万 tokens per request that way, about 0.4–0.5万 as lines+// (docs/v0.10/plan.md).+export function compactLine(image: Described, lang: Lang = "zh"): string {+ const words = WORDS[lang];+ const fields = [image.id, image.name ?? words.unnamed, words.kind[image.kind]];+ if (image.turn !== null) fields.push(words.turn(image.turn));+ const noted = notesLine(words, image);+ if (noted) fields.push(noted);+ return fields.join(lang === "zh" ? "|" : " | ");+}++export function compactList(images: Described[], lang: Lang = "zh"): string {+ return [WORDS[lang].compactHeader(images.length), ...images.map((image) => compactLine(image, lang))].join("\n");+}++// v0.10, Codex: right after its compaction item, the images that compaction did not keep (thread-index.ts,+// compacted): a developer message with the note and the list, then the ones still sent (pinned, or checked in manual+// mode) as originals with their labels, in a user message. The same selection gives the same items, so the cached+// prefix holds. No compaction item in the request: nothing changes.+export function addCodexCompacted(items: Json[], listed: Described[], resend: Array<{ image: Described; url: string }>, options: { lang?: Lang; auto?: boolean } = {}): { items: Json[]; at: number | null } {+ const { lang = "zh", auto = false } = options;+ let at = -1;+ items.forEach((item, position) => { if (item?.type === "compaction") at = position; });+ if (at < 0 || !listed.length) return { items, at: null };+ const sent = new Set(resend.map(({ image }) => image.id));+ const missing = listed.filter((image) => !sent.has(image.id));+ const text = [WORDS[lang].codexCompacted(listed.length, resend.length, auto), ...(missing.length ? ["", compactList(missing, lang)] : [])].join("\n");+ const added: Json[] = [{ type: "message", role: "developer", content: [{ type: "input_text", text }] }];+ if (resend.length) added.push({ type: "message", role: "user", content: resend.flatMap(({ image, url }) => [{ type: "input_text", text: includedLabel(image, lang) }, { type: "input_image", image_url: url }]) });+ return { items: [...items.slice(0, at + 1), ...added, ...items.slice(at + 1)], at };}export function autoPlaceholder(image: Described, lang: Lang = "zh"): string {diff --git a/plugin/src/thread-index.ts b/plugin/src/thread-index.tsindex ddc4382..72b77b3 100644--- a/plugin/src/thread-index.ts+++ b/plugin/src/thread-index.ts@@ -21,10 +21,13 @@ import { addNotes, type Notes } from "./notes.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 };+// v0.10: compacted, before Codex last compacted the thread and not in the history it kept (its tool outputs): the+// engine puts it back after the compaction (rewrite.ts, addCodexCompacted); for Claude, before the latest compaction.+export type IndexedImage = ImageRef & { id: string; turn: number | null; bytes: number; pixelSha256: string | null; compacted?: boolean };// v0.3: an image the model fetched with our tool, a copy of `of` sent in its own turn only (spec: automatic selection).export type FetchedCopy = { key: string; of: string; turn: number | null };-export type ThreadIndex = { threadId: string; images: IndexedImage[]; byKey: Map<string, IndexedImage>; turns: number; turnNumbers: Map<string, number>; copies: Map<string, FetchedCopy>; notes: Map<string, Notes> };+// v0.10 (Codex): items, the items of the history, which image positions point into.+export type ThreadIndex = { threadId: string; images: IndexedImage[]; byKey: Map<string, IndexedImage>; turns: number; turnNumbers: Map<string, number>; copies: Map<string, FetchedCopy>; notes: Map<string, Notes>; items?: Json[] };export type Parsed = { offset: number; type: string; payload: Json; timestamp: string | null };type FileCache = { size: number; mtimeMs: number; parsedTo: number; records: Parsed[] };@@ -227,7 +230,12 @@ export function buildIndex(threadId: string, history: Parsed[]): ThreadIndex {const activeTurn: Array<string | null> = [];const notes = new Map<string, Notes>();let current: string | null = null;+ // v0.10: the latest compaction of Codex: how many items came before it, and the images of the history it kept.+ let compaction: { before: number; kept: Set<string> } | null = null;for (const record of history) {+ if (record.type === "compacted" && Array.isArray(record.payload.replacement_history)) {+ compaction = { before: items.length, kept: new Set(findImages(record.payload.replacement_history).map((ref) => ref.key)) };+ }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);@@ -267,7 +275,8 @@ export function buildIndex(threadId: string, history: Parsed[]): ThreadIndex {const twin = images.find((other) => other.name && (other.contentId === entry.contentId || (entry.pixelSha256 !== null && other.pixelSha256 === entry.pixelSha256)));if (twin) entry.name = twin.name;}- return { threadId, images, byKey, turns: turnNumbers.size, turnNumbers, copies, notes };+ if (compaction) for (const entry of images) if (entry.item < compaction.before && !compaction.kept.has(entry.key)) entry.compacted = true;+ return { threadId, images, byKey, turns: turnNumbers.size, turnNumbers, copies, notes, items };}// The first line alone (session_meta can be long), read in chunks without parsing the rest of the file.diff --git a/spike/src/claude-rewrite.test.ts b/spike/src/claude-rewrite.test.tsindex 2afc919..a7f199b 100644--- a/spike/src/claude-rewrite.test.ts+++ b/spike/src/claude-rewrite.test.ts@@ -9,7 +9,7 @@ import assert from "node:assert/strict";import test from "node:test";import { buildClaudeIndex } from "../../plugin/src/claude-index.ts";import { addCompacted, findRequestImages, rewriteMessages, summaryAt } from "../../plugin/src/claude-rewrite.ts";-import { autoPlaceholder, claudeNote, compactedNote, hereNote, includedLabel, plainPlaceholder } from "../../plugin/src/rewrite.ts";+import { autoPlaceholder, claudeNote, compactedNote, compactLine, compactList, hereNote, includedLabel, plainPlaceholder } from "../../plugin/src/rewrite.ts";import { image, pngA, pngB, pngC, text, transcript, usualRequest, usualSession } from "./claude-fixtures.ts";const noPixels = () => null;@@ -182,22 +182,23 @@ test("v0.5: after a compaction, the images from before it go back right after thconst request = [{ role: "user", content: "summary" }, { role: "assistant", content: [text("A white rectangle.")] }, { role: "user", content: [text("And now?")] }];const block = (data: string) => ({ type: "image", source: { type: "base64", media_type: "image/png", data } });assert.equal(summaryAt(request, "summary"), 0);- // IMG-001 unchecked: its placeholder stands where it would be, in their order; IMG-002 goes out with its label.+ // IMG-002 goes out with its label; IMG-001, unchecked, is a line in the list after it (v0.10: not a placeholder).const out = addCompacted(request, "summary", [a, c], [{ image: c, block: block(pngC) }], { lang: "en" });assert.deepEqual([out.at, out.inserted], [0, true]);assert.deepEqual(out.messages[0].content, [{ type: "text", text: "summary" },- { type: "text", text: plainPlaceholder(a, "en") },{ type: "text", text: includedLabel(c, "en") },block(pngC),+ { type: "text", text: compactList([a], "en") },]);- // The note follows as a system message: the full note first, since something is left out, then the list.+ assert.equal(compactList([a], "en"), "[Images from before the compaction, the 1 not included as originals this time: id | name | source | turn | features and ratings]\nIMG-001 | unnamed | uploaded by the user | turn 1");+ // The note follows as a system message: the full note first, since something is left out, then the count and ids.assert.deepEqual(out.messages[1], { role: "system", content: compactedNote([a, c], new Set(["IMG-002"]), "en") });const note = out.messages[1].content;assert.ok(note.startsWith(claudeNote("en")));- assert.match(note, /IMG-001 \(uploaded by the user\), IMG-002 \(c\.png, viewed with a tool\)/);- // The one not sent is named, with what was said looking at it standing, and how to get it back.- assert.match(note, /Not included this time: IMG-001 \(uploaded by the user\) \(the user unchecked them/);+ assert.match(note, /the conversation before the summary had 2 images \(IMG-001 to IMG-002\)/);+ // The ones not sent are counted, with what was said looking at them standing, and how to get one back.+ assert.match(note, /The other 1 are not included as originals this time \(the user unchecked them/);assert.match(note, /remain valid; do not take them back/);assert.match(note, /"need IMG-xxx"/);assert.deepEqual(out.messages.slice(2), request.slice(1));@@ -207,7 +208,7 @@ test("v0.5: after a compaction, the images from before it go back right after thconst all = addCompacted(request, "summary", [a, c], [{ image: a, block: block(pngA) }, { image: c, block: block(pngC) }], { lang: "en" });assert.deepEqual(all.messages[0].content.map((b: any) => b.type === "image" ? "image" : b.text), ["summary", includedLabel(a, "en"), "image", includedLabel(c, "en"), "image"]);assert.ok(all.messages[1].content.startsWith("Context management note (from the context asset manager the user installed): "));- assert.doesNotMatch(all.messages[1].content, /Not included this time/);+ assert.doesNotMatch(all.messages[1].content, /not included as originals/);// Without the full note, this one says where an image checked again comes back: not in the user's new message.assert.match(all.messages[1].content, /or one you asked for: an image the user checks again comes back there, not in the user's new message/);assert.doesNotMatch(note, /comes back there, not in the user's new message/);@@ -219,12 +220,14 @@ test("v0.5: after a compaction, the images from before it go back right after thassert.equal(joined.inserted, false);assert.deepEqual(joined.messages[1], { role: "system", content: [{ type: "text", text: note }], output_config: { effort: "low" } });assert.equal(joined.messages.length, marked.length);- // Automatic selection: the placeholder and the note in its words, with the tool to fetch one.+ // Automatic selection: the list and the note in its words, with the tool to fetch one.const blocks = [{ role: "user", content: [text("summary"), text("<system-reminder>x</system-reminder>")] }];const auto = addCompacted(blocks, "summary", [a], [], { lang: "zh", auto: true });- assert.deepEqual(auto.messages[0].content.map((b: any) => b.text), ["summary", autoPlaceholder(a, "zh"), "<system-reminder>x</system-reminder>"]);+ assert.deepEqual(auto.messages[0].content.map((b: any) => b.text), ["summary", compactList([a], "zh"), "<system-reminder>x</system-reminder>"]);+ assert.equal(compactLine(a, "zh"), "IMG-001|未命名|用户上传|第 1 轮");assert.ok(auto.messages[1].content.startsWith(claudeNote("zh", true)));- assert.match(auto.messages[1].content, /这次没有提供的是 IMG-001(用户上传)(自动选图开着/);+ assert.match(auto.messages[1].content, /摘要之前的对话中有 1 张图片(IMG-001)/);+ assert.match(auto.messages[1].content, /其余 1 张这次没有附原图(自动选图开着/);assert.match(auto.messages[1].content, /调用 cam_view_image 工具/);// No summary in the request (before the compaction, or another request): nothing changes.const before = [{ role: "user", content: [text("hello")] }];diff --git a/spike/src/codex-compaction.test.ts b/spike/src/codex-compaction.test.tsnew file mode 100644index 0000000..119d899--- /dev/null+++ b/spike/src/codex-compaction.test.ts@@ -0,0 +1,98 @@+// Purpose: v0.10 — after Codex compacts a task it keeps only the user messages, so the images tools viewed or+// generated drop out of the request: the index marks them (thread-index.ts, compacted) and the engine puts them back+// right after the compaction item (rewrite.ts, addCodexCompacted): pinned ones as originals, the others one line each+// with what the model noted.+// Input: a synthetic rollout and requests in temporary folders; 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 zlib from "node:zlib";+import { rewriteBody } from "../../plugin/src/proxy.ts";+import { addCodexCompacted, compactList } from "../../plugin/src/rewrite.ts";+import { writeSelection } from "../../plugin/src/selection.ts";+import { loadThreadIndex } from "../../plugin/src/thread-index.ts";+import { png } from "./testkit.ts";++type Json = Record<string, any>;+const threadId = "01a0d301-0000-7000-8000-0000000000cc";+const red = `data:image/png;base64,${png(16, 16, () => [220, 30, 30]).toString("base64")}`;+const blue = `data:image/png;base64,${png(8, 8, () => [40, 70, 210]).toString("base64")}`;+const upload: Json = {+ 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>" }],+ internal_chat_message_metadata_passthrough: { turn_id: "t1" },+};+const compaction = { type: "compaction", id: "cmp_1", encrypted_content: "opaque" };++function fixture() {+ const root = mkdtempSync(join(tmpdir(), "cam-codex-compaction-"));+ const sessions = join(root, "sessions");+ const selections = join(root, "selection");+ mkdirSync(join(sessions, "2026", "10", "30"), { recursive: true });+ const item = (payload: Json) => ({ type: "response_item", payload });+ const turn = (id: string) => ({ type: "event_msg", payload: { type: "task_started", turn_id: id } });+ const rollout = [+ { type: "session_meta", payload: { id: threadId } },+ turn("t1"), item(upload),+ item({ type: "message", role: "assistant", content: [{ type: "output_text", text: "[//]: # (cam IMG-001 角色|红衣女生)\n\n收到" }] }),+ turn("t2"), item({ type: "message", id: "msg_2", role: "user", content: [{ type: "input_text", text: "看看 c.png" }] }),+ item({ type: "function_call", name: "view_image", call_id: "call_v", arguments: JSON.stringify({ path: "C:\\w\\c.png" }) }),+ item({ type: "function_call_output", call_id: "call_v", output: [{ type: "input_image", image_url: blue }] }),+ item({ type: "message", role: "assistant", content: [{ type: "output_text", text: "[//]: # (cam IMG-002 街道|蓝色方块,雨夜)\n\n看了" }] }),+ turn("t3"), item({ type: "message", id: "msg_3", role: "user", content: [{ type: "input_text", text: "c.png 那张很好" }] }),+ item({ type: "message", role: "assistant", content: [{ type: "output_text", text: "[//]: # (cam IMG-002 评价:很好)\n\n好" }] }),+ { type: "compacted", payload: { message: "", replacement_history: [{ type: "message", role: "developer", content: [{ type: "input_text", text: "system" }] }, upload, compaction] } },+ turn("t4"),+ ];+ writeFileSync(join(sessions, "2026", "10", "30", `rollout-2026-10-30T10-00-00-${threadId}.jsonl`), rollout.map((record) => JSON.stringify(record)).join("\n") + "\n");+ // What Codex sends in turn 4: the history it kept, the compaction, the new message.+ const body = () => zlib.zstdCompressSync(Buffer.from(JSON.stringify({ model: "m", input: [{ type: "message", role: "developer", content: [{ type: "input_text", text: "system" }] }, upload, compaction, { type: "message", role: "user", content: [{ type: "input_text", text: "现在呢" }] }], stream: true })));+ return { sessions, selections, body };+}++const sent = (out: Buffer) => JSON.parse(zlib.zstdDecompressSync(out).toString("utf8")).input as Json[];++test("the index marks the images Codex's compaction did not keep", () => {+ const { sessions } = fixture();+ const index = loadThreadIndex(sessions, threadId);+ assert.deepEqual(index.images.map((image) => [image.id, image.key, !!image.compacted]), [["IMG-001", "msg_1#0", false], ["IMG-002", "function_call_output:call_v#0", true]]);+});++test("after a Codex compaction, the images it dropped come back right after its compaction item", () => {+ const { sessions, selections, body } = fixture();+ writeSelection({ threadId, unchecked: {}, auto: true, autoAt: "2026-10-30T10:00:00Z", autoSince: "2026-10-30T10:00:00Z" }, selections);+ const { body: out, report } = rewriteBody(body(), "zstd", threadId, sessions, selections, "t4");+ const items = sent(out);+ const at = items.findIndex((item) => item.type === "compaction");+ // (after the notes rewriteItems put before the first turn)+ assert.deepEqual(report.compacted, { at, listed: 1, resent: [] });+ // A developer message with the note and the list, right after the compaction; the new message after it.+ const note = items[at + 1];+ assert.equal(note.role, "developer");+ assert.match(note.content[0].text, /^上下文管理说明(来自用户安装的上下文素材管理工具):这个任务压缩过对话。压缩时,之前各轮里工具查看、生成或返回的 1 张图片没有保留下来/);+ assert.match(note.content[0].text, /调用 cam_view_image 工具/);+ assert.match(note.content[0].text, /\nIMG-002|c\.png|[^|]+|第 2 轮|特征:街道|蓝色方块,雨夜;评价:第 3 轮“很好”$/);+ assert.equal(items[at + 2].content[0].text, "现在呢");+ // The upload Codex kept is still a placeholder where it was (an earlier turn's image, automatic selection).+ assert.match(JSON.stringify(items.find((item) => item.id === "msg_1")), /\[图片 IMG-001(\[Image #1\]) 已省略/);+ // The same request again: the same items, so the cached prefix holds.+ assert.deepEqual(sent(rewriteBody(body(), "zstd", threadId, sessions, selections, "t4").body), items);+ // Pinned: it goes out as its original, labelled, after the note.+ writeSelection({ threadId, unchecked: {}, auto: true, autoAt: "2026-10-30T10:00:00Z", autoSince: "2026-10-30T10:00:00Z", pinned: { "function_call_output:call_v#0": { id: "IMG-002", at: "2026-10-30T10:00:00Z" } } }, selections);+ const pinned = rewriteBody(body(), "zstd", threadId, sessions, selections, "t4");+ const again = sent(pinned.body);+ assert.deepEqual(pinned.report.compacted.resent, ["IMG-002"]);+ assert.deepEqual(again[at + 2].content.map((part: Json) => part.type === "input_image" ? part.image_url === blue : part.text.startsWith("[图片 IMG-002 已提供|c.png")), [true, true]);+ assert.doesNotMatch(again[at + 1].content[0].text, /清单/);+});++test("no compaction item in the request, or nothing dropped: nothing is added", () => {+ const listed = [{ id: "IMG-002", name: "c.png", label: null, kind: "view" as const, turn: 2, width: 8, height: 8 }];+ const items = [{ type: "message", role: "user", content: [{ type: "input_text", text: "hi" }] }];+ assert.deepEqual(addCodexCompacted(items, listed, []), { items, at: null });+ assert.deepEqual(addCodexCompacted([...items, compaction], [], []), { items: [...items, compaction], at: null });+ assert.equal(compactList(listed, "en"), "[Images from before the compaction, the 1 not included as originals this time: id | name | source | turn | features and ratings]\nIMG-002 | c.png | viewed with a tool | turn 2");+});diff --git a/spike/src/proxy.test.ts b/spike/src/proxy.test.tsindex 9f41eeb..f1e05d7 100644--- a/spike/src/proxy.test.ts+++ b/spike/src/proxy.test.ts@@ -382,21 +382,22 @@ test("v0.5: after a compaction, the images from before it go back after the summconst sent = (out: any) => JSON.parse(out.body.toString("utf8")).messages;const partsOf = (message: any) => message.content.map((block: any) =>block.type === "image" ? `image:${block.source.data === pngA ? "A" : block.source.data === pngB ? "B" : "C"}`+ : /^\[压缩之前的图片/.test(block.text) ? `list:${[...block.text.matchAll(/^(IMG-\d+)|/gm)].map((match: any) => match[1]).join(",")}`: /^\[图片 (IMG-\d+) 已提供/.exec(block.text)?.[1] ?? /^\[图片 (IMG-\d+) 已省略/.exec(block.text)?.[1].replace(/^/, "omitted:") ?? block.text);// Nothing unchecked: every image from before the compaction goes out again, and a short note follows.const all = rewriteClaudeBody(request, undefined, session, dir, home, {});assert.deepEqual(all.report.compacted, { at: 0, listed: 2, resent: ["IMG-001", "IMG-002"] });assert.deepEqual(partsOf(sent(all)[0]), ["summary", "IMG-001", "image:A", "IMG-002", "image:C"]);assert.equal(sent(all)[1].role, "system");- assert.match(sent(all)[1].content, /^上下文管理说明(来自用户安装的上下文素材管理工具):上面这条消息里,摘要之前的对话中有这些图片/);+ assert.match(sent(all)[1].content, /^上下文管理说明(来自用户安装的上下文素材管理工具):上面这条消息里,摘要之前的对话中有 2 张图片(IMG-001 到 IMG-002)/);assert.equal(all.report.noteAt, undefined);- // An unchecked one stays out: its placeholder after the summary, and the full note naming it.+ // An unchecked one stays out: a line in the list after the summary (v0.10), and the full note counting it.writeSelection({ threadId: session, unchecked: { [`${p1}#0`]: { id: "IMG-001", at: "2026-10-12T00:00:00Z" } } }, dir);const some = rewriteClaudeBody(request, undefined, session, dir, home, {});assert.deepEqual(some.report.compacted.resent, ["IMG-002"]);- assert.deepEqual(partsOf(sent(some)[0]), ["summary", "omitted:IMG-001", "IMG-002", "image:C"]);+ assert.deepEqual(partsOf(sent(some)[0]), ["summary", "IMG-002", "image:C", "list:IMG-001"]);assert.match(sent(some)[1].content, /^上下文管理说明(来自用户安装的上下文素材管理工具):为了节省上下文/);- assert.match(sent(some)[1].content, /这次没有提供的是 IMG-001/);+ assert.match(sent(some)[1].content, /其余 1 张这次没有附原图/);assert.equal(some.report.noteAt, 1);// One unchecked after the compaction too: its message gets only the short note, the full one being after the summary.writeSelection({ threadId: session, unchecked: { [`${p1}#0`]: { id: "IMG-001", at: "2026-10-12T00:00:00Z" }, [`${p3}#0`]: { id: "IMG-003", at: "2026-10-12T00:00:00Z" } } }, dir);@@ -406,12 +407,12 @@ test("v0.5: after a compaction, the images from before it go back after the summ// v0.8: IMG-003 is also the request's own first image, so the feature line note joins its short note, first.assert.deepEqual(both[4].content.map((block: any) => block.text.slice(0, 5)), ["特征行说明", "上下文管理"]);assert.match(both[4].content[1].text, /^上下文管理说明:上面这条消息里的 IMG-003/);- // Automatic selection: only the pinned ones go out again; the others are placeholders in its words.+ // Automatic selection: only the pinned ones go out again; the others are lines, and the note says how to fetch one.writeSelection({ threadId: session, unchecked: {}, auto: true, autoSince: "2026-10-12T00:00:00Z", pinned: { "tool:toolu_1#0": { id: "IMG-002", at: "2026-10-12T00:00:00Z" } } } as any, dir);const auto = rewriteClaudeBody(request, undefined, session, dir, home, {});assert.deepEqual(auto.report.compacted.resent, ["IMG-002"]);- assert.deepEqual(partsOf(sent(auto)[0]), ["summary", "omitted:IMG-001", "IMG-002", "image:C"]);- assert.match(sent(auto)[0].content[1].text, /cam_view_image/);+ assert.deepEqual(partsOf(sent(auto)[0]), ["summary", "IMG-002", "image:C", "list:IMG-001"]);+ assert.match(sent(auto)[1].content, /cam_view_image/);});test("v0.5: the request writing a second summary is rewritten as usual; after it, the images from before both go back", async () => {