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.

fix(claude): keep the prompt cache readable after the history changes

chipfighterb16d2024858c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3e425b4..b6b9988 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,12 +24,13 @@ Earlier images come back after compaction and resume, with the same IDs, in Code
- In Claude Code, when the model read several images at once and the results came back out of order, an image could get no ID (since 0.4): it went out as an original in every request and was lost after a compaction. Every such image now gets its ID, in the order it was read; feature lines written before are matched to the new IDs.
- In Claude Code, a request sometimes went out a moment before Claude Code had written the turn's newest images to its transcript (about 1 request in 75 in the logs on the development machine). Those images went without IDs, so the model could not note them in that reply. The engine now reads the transcript again for up to 1.5 seconds when that happens.
- The note to the model said not to read image files with other tools, meaning the omitted ones, which it should fetch with the image tool. After a compaction, a small model took it for every image and stopped looking at the new files the user named. The note now names the omitted images only and says new ones are looked at as usual.
+- In Claude Code, leaving earlier images out changed the history before Claude Code's prompt-cache marks, which sit on the last two messages, so many requests read only the system prompt from the cache and wrote the whole conversation again (since 0.4). The engine now places the marks in the messages itself: where an earlier request had one before the first change, and just before the first image that will be left out later. Placeholders now show only the ratings noted by the image's own turn, and the list after a compaction the notes as they stood then; later ratings are in the model's own replies. Both no longer change after they go out.
### Notes
- After updating, reopen Claude sessions that were open: their image tool still runs the earlier code and numbering until then.
- Earlier transcripts are read only up to the compaction, and their image data stays on disk until needed: for the longest real session tested (9 transcripts, 210 images), the engine uses about 60 MB more memory and the first index takes under 2 seconds.
-- Verified so far with 289 unit tests, read-only replays of real Codex and Claude sessions, a live test in Claude Desktop (a compaction, a restart of the session, and an edited earlier message that moved the session to a new transcript), and a long real session replayed turn by turn into a test session with two compactions, where the model picked the right image for all 12 questions asked after them. The model self-tests are still to run.
+- Verified so far with 300 unit tests, read-only replays of real Codex and Claude sessions, a live test in Claude Desktop (a compaction, a restart of the session, and an edited earlier message that moved the session to a new transcript), and a long real session replayed turn by turn into a test session with two compactions, where the model picked the right image for all 12 questions asked after them. The model self-tests are still to run.
## [0.9.1] - 2026-10-29
diff --git a/docs/design.md b/docs/design.md
index d952267..bdec7bf 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -304,6 +304,15 @@
- 去掉了思考时,统计里记下去掉了几段,面板照实提示(Anthropic 文档要求代理不要藏起来);改发原始请求时记下 `fallback`,面板提示这次没能按勾选改写。
- `CAM_EXPERIMENT_BLOCK_BINDING=error` 让老账号也按新账号的方式校验,只用于实验。
- 没用 Anthropic 的 `drop_block`(让服务端丢掉对不上的思考,实测它也保留之后新产生的思考):正式请求要带 beta 请求头,有些思考设置下不能用。用户 2026-10-11 选定由引擎自己去掉。
+- **提示缓存**(v0.10,`claude-cache.ts`、`proxy.ts`):
+ - Claude Code 在每个请求的系统提示里放两个缓存断点,消息里放两个:最后一条助手消息,和它每轮结束后加的那条 `<total_tokens>` 系统消息(一共 4 个,是上限)。缓存只能读在之前请求放过断点的地方,而且从这次的断点往回最多找 20 个位置。
+ - 引擎把之前的图换成占位时,Claude Code 的两个消息断点都在改动之后,读不到;长任务评测里每组有 7 到 9 次请求只命中系统提示,整段对话重写缓存。Anthropic 会从断点往回找之前写下的缓存,但评测里往回 6 个位置的都没找到,断点正好放在那个位置上的每次都读到了。所以消息里的断点由引擎来放:
+ - **读**:引擎在内存里记下每个会话最近 4 次发出的对话请求,各条消息的前缀哈希(和思考记录一样比较值、不看缓存断点)和断点位置。这次要发的不只是在最近那次后面加了内容时,对每一次找出和它第一处不同的地方,取所有排在各自第一处不同之前的断点里最靠后的一个,在这次请求的同一位置放一个断点。
+ - **备**(自动选图时):在第一张还按原图发、以后会换成占位的图(没固定的)前面放一个断点,下一次换掉它时就有现成的位置可读。模型晚一轮才写特征行时,图会多发一轮、在下一轮中间才换掉,那时之前每个请求的断点都在改动之后,只有这个能用。
+ - Claude Code 最末那个断点留着,这次请求照样写下自己的结尾;读和备都要用、又只剩两个位置时,它让出来,下一次请求读备好的位置。空位多时,Claude Code 的其他断点也留着。
+ - 新放的断点用它后面最近那个原有断点的 TTL:TTL 长的必须排在前面。思考块不能放断点,往前找能放的块。放了什么记在日志的 `cacheMarks`(`read`、`prepare`、`dropped`)。
+ - 只记发送成功的对话请求(有工具的;旁路请求不算),最近 50 个会话,不写盘:引擎重启后第一次只放“备”,之后照常。
+ - 往前的内容一变,之前写下的缓存就全用不上。所以 Claude 会话里,占位符只带这张图出现那一轮及以前记下的评价(`notesBy`),压缩后放回的清单用压缩那一刻的特征和评价(`compactedNotes`):之后才记下的在模型自己的回复里,下一次压缩再进清单。
- **面板**(`proxy.ts`、`panel-web.js`、Mod):
- Claude Code 不登记只给应用用的工具,所以用户打不开插件的 MCP 应用;Mod 面板只能画 Claude 自带的元素,也放不进网页。于是由引擎在 `/__cam/panel?session=<id>` 提供 `panel.html`,前面加一段 `panel-web.js` 代替 MCP 应用的宿主:把面板的工具调用转成引擎的本机接口 `/__cam/claude/panel`、`select`、`image`。
- 页面和接口只接受用本机名字(`localhost`、`127.0.0.1`、`[::1]`)访问、不带其他网站 Origin 的请求;接口还要带 `x-cam-panel` 请求头;页面带严格的 CSP。
diff --git a/docs/spec.md b/docs/spec.md
index 6815840..c9453a5 100644
--- a/docs/spec.md
+++ b/docs/spec.md
@@ -66,7 +66,7 @@ v0.9(用户 2026-10-23 定):两平台使用兼容中转时,图片照样
### 占位符
- **普通占位符**:第一行是编号、名称、来源、所在轮次和尺寸;最后一行提示需要时回复“需要 IMG-004”。v0.8 起这一句缩短成“需要重看时,在回复里写“需要 IMG-004”。”,抵掉特征行增加的字数(用户 2026-10-18 定)。
-- **占位符里的特征行**(v0.8):模型给这张图记过特征行或评价时,第一行后面多一行,例如“特征:深蓝雨夜|近景,正脸;评价:第 4 轮“脸最好”,第 6 轮“太暗””。评价按时间累积,只显示最近 3 条,不排序,也不替用户判断褒贬;超长时在上限以内最后一个标点处截断,加“…”。上限按宽度算,和界面语言无关:特征和评价都是 30 个汉字或 100 个字母(v0.10;原来按界面语言数字符,中文界面里模型写的英文特征行被截到只剩地点,一个真实会话里 180 条有 51 条截完和别的行一样;评价原来是 15 个汉字,长会话测试里一条评价的后半句被截掉了)。索引里记什么,占位符里就显示什么。照常发送的图只带编号标签,不带特征行:模型看得到原图,不带也免得每轮去改前面的标签、弄断缓存。
+- **占位符里的特征行**(v0.8):模型给这张图记过特征行或评价时,第一行后面多一行,例如“特征:深蓝雨夜|近景,正脸;评价:第 4 轮“脸最好”,第 6 轮“太暗””。评价按时间累积,只显示最近 3 条,不排序,也不替用户判断褒贬;Claude 会话里只显示这张图出现那一轮及以前记下的(v0.10:之后记下的评价就在模型自己的回复里;占位符发出后不再变,否则前面的历史一变,提示缓存就从那里起整段重写);超长时在上限以内最后一个标点处截断,加“…”。上限按宽度算,和界面语言无关:特征和评价都是 30 个汉字或 100 个字母(v0.10;原来按界面语言数字符,中文界面里模型写的英文特征行被截到只剩地点,一个真实会话里 180 条有 51 条截完和别的行一样;评价原来是 15 个汉字,长会话测试里一条评价的后半句被截掉了)。除此之外,索引里记什么,占位符里就显示什么。照常发送的图只带编号标签,不带特征行:模型看得到原图,不带也免得每轮去改前面的标签、弄断缓存。
- **特征行说明**(v0.8,用户 2026-10-19 定措辞):从第一张图所在的那一轮起,插入一条说明,告诉模型怎么写特征行、怎么记评价:
- 记录行写在每一轮最后那条回复的开头(不写在中途调用工具时说的话里),一张图一行,和正文之间空一行;这一轮没有新图、也没有评价时不写;
- 用户装这个工具,是为了让模型以后(包括压缩之后)还能认出每张图、记得用户的评价;这些行只给工具读,用户在界面上看不到,正文照常回答,不提这些行,也不回应记录这件事(不说“记下了”);用户只是评价、没提要求时,正文简短回应评价本身;
@@ -81,7 +81,7 @@ v0.9(用户 2026-10-23 定):两平台使用兼容中转时,图片照样
- **为什么放在开发者消息里**:用户 2026-09-25 发现,占位符放在原图的位置,模型会以为自己从没看过那张图,于是收回之前看着原图做出的正确回答。把这些说明写在占位符里也没用:占位符属于用户内容,模型不把它当成证据。改成开发者消息后,两次自测都不再收回(见 [history/v0.1/tasks.md](history/v0.1/tasks.md))。
- **重复占位符**:包含编号、名称、来源、所在轮次和尺寸,说明它和哪一条(编号、名称、轮次)内容完全相同,那一条照常提供,请参考那一条。内容仍然看得到,不需要上面的说明。
- **“已提供”标签**:一次请求里只要有图被换掉,每张仍在发送、有编号的图前面都加一行标签,写法和占位符的第一行一样,状态是“已提供”,例如“[图片 IMG-002([Image #2]) 已提供|名称|来源|第 1 轮|尺寸]”。原因:用户 2026-09-28 发现,重新勾选的图回到原来的位置、夹在占位符中间,而 Codex 自己的“[Image #2]”在每条消息里都从 1 开始,模型对不上编号,就说看不到。没有图被换掉时不加,请求照旧原样转发。v0.8:写特征行的任务里,每张发送的图都带这个标签,这一轮的新图也带,模型才能当场对上编号;新图在它那一轮的第一个请求里就已经有编号(Codex 和 Claude 都先把新图写进本机记录,再发请求,2026-10-19 实测)。这一轮新图的标签只影响请求的末尾,不弄断缓存。
-- **压缩后放回的清单**(v0.10):压缩之后放回请求、又不发原图的图,不再一张一个占位,而是合成一份清单,一张一行,例如“IMG-101|alley_v2.png|查看|第 66 轮|雨后小巷|路面反光局部|评价:第 70 轮“太空了””(没有名字的写“-”),清单第一行说明这是压缩之前的图、这次没有附原图,以及各列是什么。同一张图又出现过的(比如用户重发了一次),后面那行不再重复特征,写“同 IMG-108”。怎么取回只在说明里讲一次,说明里也不再把这些图列一遍。原因:一个有 127 张压缩前图片的真实会话,照原来每张一个占位、说明里再列一遍的写法,每条请求多约 1.7–2.0 万 token;清单加说明约 0.7–0.9 万(按 Claude 桌面实测校准的系数估;用户 2026-10-31 定)。
+- **压缩后放回的清单**(v0.10):压缩之后放回请求、又不发原图的图,不再一张一个占位,而是合成一份清单,一张一行,例如“IMG-101|alley_v2.png|查看|第 66 轮|雨后小巷|路面反光局部|评价:第 70 轮“太空了””(没有名字的写“-”),清单第一行说明这是压缩之前的图、这次没有附原图,以及各列是什么。同一张图又出现过的(比如用户重发了一次),后面那行不再重复特征,写“同 IMG-108”。Claude 会话里清单写的是压缩那一刻的特征和评价(v0.10):压缩之后才记下的在模型那之后的回复里,到下一次压缩再进清单;这样清单在两次压缩之间不变,提示缓存接得上。怎么取回只在说明里讲一次,说明里也不再把这些图列一遍。原因:一个有 127 张压缩前图片的真实会话,照原来每张一个占位、说明里再列一遍的写法,每条请求多约 1.7–2.0 万 token;清单加说明约 0.7–0.9 万(按 Claude 桌面实测校准的系数估;用户 2026-10-31 定)。
- **“已提供,还没有特征行”标签**(v0.10):被打断那一轮里还没有特征行、这一轮再发一次的图,标签的状态写“已提供,还没有特征行”(英文 “included, no feature line yet”),特征行说明里告诉模型给它补一行。
- 占位符里不写本地路径。Codex 附在上传图片前后的路径标签,也一起换掉。
- PDF 页面和网页截图被取消时,占位符和用户上传的图一样,来源写“用户上传”;Codex 写在图前面的那句说明原样保留,模型仍然知道那是哪一页(v0.2,用户 2026-09-29 定:不改发给模型的文字)。
diff --git a/docs/v0.10/plan.md b/docs/v0.10/plan.md
index bdbf451..ffef90c 100644
--- a/docs/v0.10/plan.md
+++ b/docs/v0.10/plan.md
@@ -64,6 +64,10 @@
11. **清单里标出同一张图**:用户重发同一张图时,插件已经认得出是同一张,但清单列成两行、各写各的特征。改成后面那行写“同 IMG-108”,不再重复特征。
12. **等记录文件写完再改写**(公开评测试跑时发现):Claude Code 有时在把这一轮刚读的图写进记录文件之前就发出请求,插件认不出这几张图,原样发出、不带编号,模型这一轮没法给它们写特征行(试跑里一轮 3 张;用户本机日志 8904 次请求里有 119 次,下一次请求才认出)。改成:请求里模型最近一次回复之后有认不出的图时,引擎每 100 毫秒重读一次记录文件,最多 1.5 秒;认出了就照常改写。一张一直认不出的图只让一次请求多等这一下。
13. **压缩后照常看新图**(公开评测发现):说明里“不要用其他工具去读取图片文件”本意是被省略的图要用 `cam_view_image` 取。评测第一次跑 0.10 时(Haiku 5.5,推理强度 low),压缩后模型把它当成所有图,用户后面 5 轮让它看的图一张都没读。改成只说被省略的(Codex 的压缩说明里是清单里的)图,并写明用户新让它看的图照常去看;重跑后每轮都照常读图。这是发给模型的措辞,按 AGENTS.md 要跑 Codex 的 `v01-placeholder`、`v01-needs`、`v03-auto` 自测。
+14. **Claude 的提示缓存接得上**(公开评测发现,用户 2026-11-01 定先修再发 0.10):装插件的 Claude 会话按 API 价格折算约是不装的两倍($0.069 对 $0.036),多在写缓存上:每组 7 到 9 次请求只命中系统提示,整段对话重写。用评测留下的请求逐个对比查到两个原因:
+ - **断点位置**:Claude Code 只在最后两条消息上放断点,插件换掉上一轮的图后,这两个断点都在改动之后;Anthropic 往回找之前的缓存,评测里往回 6 个位置的也没找到。改成引擎自己放消息里的断点(`claude-cache.ts`,design.md 的“提示缓存”):在之前请求放过断点、又在这次第一处改动之前的最后一个位置放一个(读),在第一张以后会换掉的原图前面放一个(备),Claude Code 最末那个尽量留着。
+ - **占位符和清单后来又变**:用户隔几轮才评价一张图时,那张图的占位符(或压缩后的清单)里多出这条评价,从它起整段缓存重写。改成占位符只带这张图出现那一轮及以前记下的评价,清单用压缩那一刻的特征和评价;之后记下的在模型自己的回复里,下一次压缩再进清单(spec 的占位符和清单两条)。
+ - 结果(Haiku 5.5,推理强度 low,每组一次):只改第一条的第一版 $0.047、从缓存读 86%;改成记最近 4 次请求后 $0.065、78%,那一组模型每轮都晚一轮才写特征行,图在下一轮中间才换掉,之前的断点都用不上,于是加了“备”。最后这一版还没跑成:那次在 5 小时额度暂停之后上游连不上,36 步都是 502(评测脚本已改成连着两次出错就停),之后测试账号一周额度用到 95%,等 11 月 6 日重置后再跑,每组至少两次。按评测留下的请求离线模拟(断点处的缓存才算读到,往回找 20 个位置),这一版从缓存读的比例比只用 Claude Code 的断点高十几个百分点,读不到几乎任何东西的请求从 14–17 次降到 3–5 次。
## 3. 要先验证的事(关卡)
diff --git a/plugin/src/claude-cache.ts b/plugin/src/claude-cache.ts
new file mode 100644
index 0000000..d3c2b6e
--- /dev/null
+++ b/plugin/src/claude-cache.ts
@@ -0,0 +1,125 @@
+// Purpose: v0.10 — keep Claude Code's prompt cache readable after the engine changed the history. Claude Code marks
+// the end of each request for the cache: the last two messages (with two marks in the system prompt, the four
+// allowed). A read lands only where an earlier request wrote a mark; Anthropic looks back from this request's marks
+// for one, but in a long-task eval (docs/v0.10/plan.md) it missed marks 6 places back, while a mark put on the very
+// place was read every time. When the engine changes a message (an earlier turn's images become placeholders),
+// Claude Code's marks all sit after the change; 7–9 requests a run read only the system prompt and wrote the whole
+// conversation again. So the engine places the message marks itself:
+// - read: where the latest of the last few requests it sent had a mark before the first difference with that request
+// (what it covers is unchanged and was written then), when this request is more than one of them added to;
+// - prepare: just before the first image still sent as an original that a later request will leave out (automatic
+// selection), so the request that does has an unchanged place to read; with feature lines written a turn late, the
+// images go out once more and are left out in the middle of the next turn, after every mark of the requests before;
+// - Claude Code's last mark, so the request writes its own end, unless both of the others need the two places.
+// Input: a request's messages, what was sent before (newest first), how many marks sit outside the messages, the
+// first image a later request will leave out. Output: the messages with the marks placed, and what to remember once
+// they are sent.
+
+import { link } from "./claude-thinking.ts";
+
+type Json = Record<string, any>;
+export type Mark = { message: number; block: number };
+// What a sent request leaves to read: its messages' prefix hashes (hashes[i] covers messages 0..i) and its marks.
+export type SentPrefix = { hashes: string[]; marks: Mark[] };
+const MAX_MARKS = 4;
+// How many sent requests a session remembers: a turn's requests, and the turn before.
+export const REMEMBERED = 4;
+// Blocks that cannot carry a mark.
+const UNMARKABLE = new Set(["thinking", "redacted_thinking"]);
+
+const blocksOf = (message: Json): Json[] | null => (Array.isArray(message?.content) ? message.content : null);
+
+function marksOf(messages: Json[]): Mark[] {
+ const marks: Mark[] = [];
+ messages.forEach((message, m) => blocksOf(message)?.forEach((block, b) => { if (block?.cache_control) marks.push({ message: m, block: b }); }));
+ return marks;
+}
+
+function hashesOf(messages: Json[]): string[] {
+ const hashes: string[] = [];
+ let chain = "";
+ for (const message of messages) hashes.push((chain = link(chain, message)));
+ return hashes;
+}
+
+export const sentPrefixOf = (messages: Json[]): SentPrefix => ({ hashes: hashesOf(messages), marks: marksOf(messages) });
+
+// Marks a request carries outside its messages: the top-level one (automatic caching), tools, system blocks.
+export function marksOutside(body: Json): number {
+ const count = (list: unknown) => (Array.isArray(list) ? list.filter((block: Json) => block?.cache_control).length : 0);
+ return (body.cache_control ? 1 : 0) + count(body.tools) + count(body.system);
+}
+
+const later = (a: Mark, b: Mark) => a.message > b.message || (a.message === b.message && a.block > b.block);
+const same = (a: Mark, b: Mark) => a.message === b.message && a.block === b.block;
+const markable = (messages: Json[], mark: Mark) => {
+ const blocks = blocksOf(messages[mark.message]);
+ if (!blocks) return mark.block === 0 && typeof messages[mark.message]?.content === "string";
+ return !!blocks[mark.block] && !UNMARKABLE.has(blocks[mark.block]?.type);
+};
+
+// The latest remembered mark before where this request first differs from that request; null when this request only
+// adds to the newest one (Claude Code's own marks read its end).
+function readAt(hashes: string[], previous: SentPrefix[]): Mark | null {
+ let target: Mark | null = null;
+ for (const [i, sent] of previous.entries()) {
+ let kept = 0;
+ while (kept < hashes.length && kept < sent.hashes.length && hashes[kept] === sent.hashes[kept]) kept++;
+ if (i === 0 && kept >= sent.hashes.length) return null;
+ for (const mark of sent.marks) if (mark.message < kept && (!target || later(mark, target))) target = mark;
+ }
+ return target;
+}
+
+// The last block a mark can go on before `at` (a top-level block of a message).
+function blockBefore(messages: Json[], at: Mark): Mark | null {
+ for (let m = at.message, b = at.block - 1; m >= 0; m--, b = Infinity) {
+ const count = blocksOf(messages[m])?.length ?? (typeof messages[m]?.content === "string" ? 1 : 0);
+ for (let k = Math.min(b, count - 1); k >= 0; k--) if (markable(messages, { message: m, block: k })) return { message: m, block: k };
+ if (m < at.message - 2) return null;
+ }
+ return null;
+}
+
+export type Placed = { messages: Json[]; marks: { read: Mark | null; prepare: Mark | null; dropped: Mark[] } | null };
+
+export function keepCacheRead(messages: Json[], previous: SentPrefix[], outside: number, volatile: Mark | null = null): Placed {
+ const none = { messages, marks: null };
+ const current = marksOf(messages);
+ const end = current.at(-1);
+ if (!end) return none;
+ const readCandidate = previous.length ? readAt(hashesOf(messages), previous) : null;
+ const read = readCandidate && markable(messages, readCandidate) ? readCandidate : null;
+ const prepare = volatile ? blockBefore(messages, volatile) : null;
+ const wanted: Mark[] = [];
+ for (const mark of [read, prepare]) if (mark && !wanted.some((other) => same(other, mark))) wanted.push(mark);
+ if (!wanted.length) return none;
+ const slots = Math.max(0, MAX_MARKS - outside);
+ // The read first, then the prepared place, then Claude Code's last mark while there is room.
+ const chosen = [...wanted];
+ if (!chosen.some((mark) => same(mark, end))) chosen.push(end);
+ chosen.splice(slots);
+ // Room left: Claude Code's other marks stay, latest first.
+ for (const mark of [...current].reverse()) if (chosen.length < slots && !chosen.some((other) => same(other, mark))) chosen.push(mark);
+ if (!chosen.length) return none;
+ const keep = (mark: Mark) => chosen.some((other) => same(other, mark));
+ if (current.length === chosen.length && current.every(keep)) return none;
+ // A mark put earlier takes the TTL of Claude Code's next one: marks with a longer TTL must come first.
+ const controlFor = (at: Mark) => { const next = current.find((mark) => !later(at, mark)) ?? end; return messages[next.message].content[next.block].cache_control; };
+ const touched = new Set([...current, ...chosen].map((mark) => mark.message));
+ const next = messages.map((message, m) => {
+ if (!touched.has(m)) return message;
+ const content = Array.isArray(message.content) ? message.content : [{ type: "text", text: message.content }];
+ return {
+ ...message,
+ content: content.map((part: Json, b: number) => {
+ const mark = { message: m, block: b };
+ if (keep(mark)) return part.cache_control ? part : { ...part, cache_control: controlFor(mark) };
+ if (!part.cache_control) return part;
+ const { cache_control: _dropped, ...rest } = part;
+ return rest;
+ }),
+ };
+ });
+ return { messages: next, marks: { read, prepare, dropped: current.filter((mark) => !keep(mark)) } };
+}
diff --git a/plugin/src/claude-index.ts b/plugin/src/claude-index.ts
index eb81af1..2cbf2b3 100644
--- a/plugin/src/claude-index.ts
+++ b/plugin/src/claude-index.ts
@@ -23,7 +23,7 @@ import { closeSync, existsSync, openSync, readdirSync, readFileSync, readSync, s
import { homedir } from "node:os";
import { basename, dirname, join, resolve, sep } from "node:path";
import { baseName, FETCHED_STATE, imageDigest, type ImageKind, type ImageRef } from "./images.ts";
-import { addNotes, type Notes } from "./notes.ts";
+import { addNotes, copyNotes, type Notes } from "./notes.ts";
import { pixelHashOfData, type FetchedCopy, type IndexedImage, type ThreadIndex } from "./thread-index.ts";
type Json = Record<string, any>;
@@ -51,6 +51,9 @@ export type ClaudeIndex = ThreadIndex & {
summary: string | null;
// v0.10: the sessions this one continues, most recent first (for its selection, selection.ts).
previous: Array<{ sessionId: string; at: string | null }>;
+ // v0.10: the notes as they stood at the latest compaction, for the list put back after it (proxy.ts): one noted
+ // later is in the model's reply after the summary, and changing the list would rewrite the whole prompt cache.
+ compactedNotes: Map<string, Notes>;
};
const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
@@ -371,12 +374,14 @@ export function buildClaudeIndex(sessionId: string, records: ClaudeRecord[], tra
let previous: string[] = [];
// v0.8: what the model noted in record lines at the end of its replies (notes.ts), by image id.
const notes = new Map<string, Notes>();
+ let compactedNotes = notes;
const interrupted = new Set<number>();
const skipped = new Set<number>();
// v0.10: ids written under another numbering, back to this one's (through the image they named).
const numberingAt = translator(chain, options.eras);
const ownId = (numbering: Map<string, string> | null) => (id: string) => (numbering ? byKey.get(numbering.get(id) ?? "")?.id ?? null : id);
chain.forEach((record, position) => {
+ if (position === lastBoundary) compactedNotes = copyNotes(notes);
const content = record.message?.content;
if (record.type === "assistant" && Array.isArray(content)) {
const idOf = ownId(numberingAt(record.timestamp));
@@ -449,7 +454,7 @@ export function buildClaudeIndex(sessionId: string, records: ClaudeRecord[], tra
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: sessionId, images, byKey, turns: turn, turnNumbers, copies, notes, uploads, chain, title: titleOf(records, chain), replies, transcript, summary, previous: previousOf(sessionId, options.eras?.family ?? []), interrupted, skipped };
+ return { threadId: sessionId, images, byKey, turns: turn, turnNumbers, copies, notes, uploads, chain, title: titleOf(records, chain), replies, transcript, summary, previous: previousOf(sessionId, options.eras?.family ?? []), interrupted, skipped, compactedNotes };
}
// v0.10: the sessions this one continues, most recent first, each with the time this one took over: the one it was
diff --git a/plugin/src/claude-rewrite.ts b/plugin/src/claude-rewrite.ts
index 44ece91..e8f9128 100644
--- a/plugin/src/claude-rewrite.ts
+++ b/plugin/src/claude-rewrite.ts
@@ -17,6 +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 { notesBy } from "./notes.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>;
@@ -109,7 +110,8 @@ export function rewriteMessages(
const refs = findRequestImages(messages, index);
const describe = (ref: RequestImage): ClaudeImage | undefined => {
const image = ref.key ? index.byKey.get(ref.key) : undefined;
- const notes = image ? index.notes?.get(image.id) : undefined;
+ // v0.10: as noted by the image's own turn, so a placeholder stays as it first went out (notes.ts).
+ const notes = image ? notesBy(index.notes?.get(image.id), image.turn) : undefined;
if (!image) return undefined;
return notes || awaiting.has(image.key) ? { ...image, ...(notes ? { notes } : {}), ...(awaiting.has(image.key) ? { awaiting: true } : {}) } : image;
};
diff --git a/plugin/src/notes.ts b/plugin/src/notes.ts
index 0284e5d..ba4acb3 100644
--- a/plugin/src/notes.ts
+++ b/plugin/src/notes.ts
@@ -16,6 +16,18 @@ const RATING = /^(?:评价|rated)[ \t]*[::][ \t]*/i;
// v0.10: a feature line the model found wrong (e.g. the user pointed it out), written again in full.
const CORRECTION = /^(?:更正|corrected)[ \t]*[::][ \t]*/i;
+// v0.10: what a placeholder shows of an image's notes: the ratings noted by its own turn. A rating noted later would
+// change a placeholder that went out before it, and the prompt cache from there on (claude-cache.ts); the model has it
+// in its own reply. After a compaction the list shows everything noted before it (claude-index.ts, compactedNotes).
+export function notesBy(notes: Notes | undefined, turn: number | null): Notes | undefined {
+ if (!notes || turn === null) return notes;
+ const ratings = notes.ratings.filter((rating) => rating.turn === null || rating.turn <= turn);
+ if (ratings.length === notes.ratings.length) return notes;
+ return notes.line || ratings.length ? { line: notes.line, ratings } : undefined;
+}
+
+export const copyNotes = (notes: Map<string, Notes>): Map<string, Notes> => new Map([...notes].map(([id, entry]) => [id, { line: entry.line, ratings: [...entry.ratings] }]));
+
// v0.10: `idOf` turns the id a line names into the image's id now (claude-index.ts: lines written while a resumed
// transcript was numbered from its own start); null drops the line.
export function addNotes(notes: Map<string, Notes>, text: string, turn: number | null, idOf: (id: string) => string | null = (id) => id): void {
diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.ts
index 33e6b64..285a889 100644
--- a/plugin/src/proxy.ts
+++ b/plugin/src/proxy.ts
@@ -30,6 +30,7 @@ import zlib from "node:zlib";
import { childOf, recordChild } from "./children.ts";
import { claudeHome, claudeImageData, claudeStartedAt, loadClaudeIndex, type ClaudeIndex } from "./claude-index.ts";
import { addCompacted, findRequestImages, rewriteMessages, summaryAt, type RequestImage, type Resend } from "./claude-rewrite.ts";
+import { keepCacheRead, marksOutside, REMEMBERED, sentPrefixOf, type SentPrefix } from "./claude-cache.ts";
import { chainOf, fitThinking, readThinkingRecord, recordSent, writeThinkingRecord, type ThinkingRecord } from "./claude-thinking.ts";
import { codexHome } from "./codexconfig.ts";
import { buildOf, DEFAULT_PORT, ENGINE_SERVICE, engineHealth, versionOf, watchForCodex } from "./engine.ts";
@@ -428,7 +429,8 @@ export function thinkingRejected(status: number, body: string): boolean {
// without any thinking, always accepted; the original as Claude Code built it. history/sent: the chains to remember
// once the attempt goes through (null: not the session's conversation); made: the histories its thinking was made
// after; sure: the record says all its thinking fits, so a refusal means the record misses what went out.
-export type ClaudeAttempt = { body: Buffer; report: Json; history: string | null; sent: string | null; made: string[]; sure: boolean };
+// prefix: where its cache marks are, to remember once it is sent (claude-cache.ts).
+export type ClaudeAttempt = { body: Buffer; report: Json; history: string | null; sent: string | null; made: string[]; sure: boolean; prefix?: SentPrefix };
// v0.10: how long a request waits for its newest images to reach the transcript (a long-task eval caught 3 of a turn's
// images going out without ids, the transcript written a moment after the request; the user's logs had 119 such of
// 8904 requests). A request whose images never reach it waits the whole time once.
@@ -439,7 +441,7 @@ const LATE_STEP_MS = 100;
// turn is the transcript's latest prompt: Claude Code writes it before it sends the request.
// CAM_EXPERIMENT_BLOCK_BINDING (experiments only, docs/v0.4/tasks.md T04-01): asks Anthropic to check thinking with
// that prefix_mismatch_behavior, as for an account created from 2026-08-31; the report names the beta header to add.
-export function rewriteClaudeBody(original: Buffer, encoding: string | undefined, sessionId: string, dir = claudeSelectionDirOf(), home = claudeHome(), env = process.env, thinking: ThinkingRecord | null = null): { body: Buffer; report: Json; attempts: ClaudeAttempt[] } {
+export function rewriteClaudeBody(original: Buffer, encoding: string | undefined, sessionId: string, dir = claudeSelectionDirOf(), home = claudeHome(), env = process.env, thinking: ThinkingRecord | null = null, previous: SentPrefix[] = []): { body: Buffer; report: Json; attempts: ClaudeAttempt[]; prefix?: SentPrefix } {
const asIs = (report: Json) => ({ body: original, report, attempts: [] });
const decoded = decodeBody(original, encoding);
if (!decoded) return asIs({ skipped: "undecodable body" });
@@ -467,7 +469,8 @@ export function rewriteClaudeBody(original: Buffer, encoding: string | undefined
// placeholders. With any of those, the full note follows the summary, and later messages get only their short notes.
// v0.8: each with what the model noted about it, for its placeholder.
const compactedImages = index.images.filter((image) => image.compacted).map((image) => {
- const notes = index.notes.get(image.id);
+ // v0.10: as they stood at the compaction, so the list stays the same until the next one (claude-index.ts).
+ const notes = index.compactedNotes.get(image.id);
return notes ? { ...image, notes } : image;
});
const summaryIn = index.summary && compactedImages.length ? summaryAt(json.messages, index.summary) : null;
@@ -509,25 +512,34 @@ export function rewriteClaudeBody(original: Buffer, encoding: string | undefined
const changed = report.replaced.length > 0 || report.copies.length > 0 || compacted !== null || report.featureAt !== undefined;
// Once the engine has sent the session a changed history, thinking made after it may be in every later request, even
// with nothing left out now (an image checked again).
- if (!changed && !thinking?.edited) return { body: original, report: summary, attempts: [] };
- const rewritten = changed ? messages : json.messages;
- const fit = thinking ? fitThinking(json.messages, rewritten, thinking) : null;
// Side requests (no tools: the desktop's status summary, auto mode's check) are not the conversation.
const conversation = Array.isArray(json.tools) && json.tools.length > 0;
+ if (!changed && !thinking?.edited) return { body: original, report: summary, attempts: [], ...(conversation ? { prefix: sentPrefixOf(json.messages) } : {}) };
+ const rewritten = changed ? messages : json.messages;
+ const fit = thinking ? fitThinking(json.messages, rewritten, thinking) : null;
const history = fit && conversation ? fit.history : null;
const experiment = env.CAM_EXPERIMENT_BLOCK_BINDING?.trim();
+ // v0.10: the cache marks placed so this request reads what the ones before wrote, and the next one can read this
+ // one after the images still sent as originals are left out (claude-cache.ts): with automatic selection, the first
+ // such image that is not pinned.
+ const pinnedNow = selection.pinned ?? {};
+ const volatileIn = (list: Json[]) => {
+ const ref = selection.auto ? findRequestImages(list, index).find((found) => !(found.key && pinnedNow[found.key])) : undefined;
+ return ref ? { message: ref.msg, block: ref.part } : null;
+ };
const encode = (list: Json[], extra: Json) => {
- const out: Json = { ...json, messages: list };
+ const placed = conversation ? keepCacheRead(list, previous, marksOutside(json), volatileIn(list)) : { messages: list, marks: null };
+ const out: Json = { ...json, messages: placed.messages };
const asked = experiment && json.thinking && typeof json.thinking === "object";
if (asked) out.thinking = { ...json.thinking, block_binding: { prefix_mismatch_behavior: experiment } };
const next = Buffer.from(JSON.stringify(out), "utf8");
const body = encodeBody(next, encoding);
- return { body, report: { ...summary, ...extra, ...(asked ? { experiment: { blockBinding: experiment, beta: "thinking-binding-controls-2026-08-01" } } : {}), decodedBefore: decoded.length, decodedAfter: next.length, encodedBefore: original.length, encodedAfter: body.length } };
+ return { body, report: { ...summary, ...extra, ...(placed.marks ? { cacheMarks: placed.marks } : {}), ...(asked ? { experiment: { blockBinding: experiment, beta: "thinking-binding-controls-2026-08-01" } } : {}), decodedBefore: decoded.length, decodedAfter: next.length, encodedBefore: original.length, encodedAfter: body.length }, ...(conversation ? { prefix: sentPrefixOf(placed.messages) } : {}) };
};
const attempts: ClaudeAttempt[] = [];
const made = fit?.made ?? [];
const add = (list: Json[], extra: Json, sent: string, sure: boolean) => attempts.push({ ...encode(list, extra), history, sent: history ? sent : null, made, sure });
- const asBuilt = (extra: Json, sure: boolean) => attempts.push({ body: original, report: { ...summary, ...extra }, history, sent: history, made, sure });
+ const asBuilt = (extra: Json, sure: boolean) => attempts.push({ body: original, report: { ...summary, ...extra }, history, sent: history, made, sure, ...(conversation ? { prefix: sentPrefixOf(json.messages) } : {}) });
if (!thinking?.strict) {
if (changed) add(rewritten, {}, chainOf(rewritten), fit?.left === 0);
else asBuilt({}, fit!.left === 0);
@@ -641,6 +653,15 @@ async function main(): Promise<void> {
for (const key of thinkingRecords.keys()) if (thinkingRecords.size > 50) thinkingRecords.delete(key);
return record;
};
+ // v0.10: per session, where the conversation requests sent last had their cache marks, newest first
+ // (claude-cache.ts); memory only.
+ const sentPrefixes = new Map<string, SentPrefix[]>();
+ const rememberPrefix = (sessionId: string, prefix: SentPrefix) => {
+ const kept = [prefix, ...(sentPrefixes.get(sessionId) ?? [])].slice(0, REMEMBERED);
+ sentPrefixes.delete(sessionId);
+ sentPrefixes.set(sessionId, kept);
+ for (const key of sentPrefixes.keys()) if (sentPrefixes.size > 50) sentPrefixes.delete(key);
+ };
log({ at: startedAt, event: "engine-start", pid: process.pid, port, build, version });
if (!process.argv.includes("--stay")) {
// v0.1-5: a plugin removed or turned off without 停用 leaves Codex pointed at an engine nothing will start again.
@@ -841,7 +862,7 @@ async function main(): Promise<void> {
// What to send, in order: body null streams the request through unchanged. v0.4: Anthropic refusing an attempt's
// thinking after the changed history (thinkingRejected) moves on to the next one (see ClaudeAttempt), the last being
// the original as Claude Code built it; the statistics say which went out (the panel shows a fallback).
- type Attempt = { body: Buffer | null; report: Json | null; edited: boolean } & Partial<Pick<ClaudeAttempt, "history" | "sent" | "made" | "sure">>;
+ type Attempt = { body: Buffer | null; report: Json | null; edited: boolean } & Partial<Pick<ClaudeAttempt, "history" | "sent" | "made" | "sure" | "prefix">>;
const connecting = new AbortController();
res.once("close", () => {
if (!res.writableFinished) { connecting.abort(); finish("client closed before the response ended"); }
@@ -895,6 +916,7 @@ async function main(): Promise<void> {
return;
}
// The thinking the model makes now comes after what this attempt sent.
+ if (status >= 200 && status < 300 && claudeSession && attempt.prefix) rememberPrefix(claudeSession, attempt.prefix);
if (status >= 200 && status < 300 && thinking && claudeSession && attempt.history && attempt.sent && recordSent(thinking, attempt.history, attempt.sent, attempt.made ?? [])) {
try { writeThinkingRecord(claudeSession, thinking); } catch { /* kept in memory */ }
}
@@ -933,8 +955,8 @@ async function main(): Promise<void> {
req.on("end", async () => {
const original = Buffer.concat(chunks);
const encoding = req.headers["content-encoding"] as string | undefined;
- const rewriteNow = (): { body: Buffer; report: Json; attempts?: ClaudeAttempt[] } => {
- try { return claudeRewrite ? rewriteClaudeBody(original, encoding, claudeSession!, undefined, undefined, undefined, thinking) : rewriteBody(original, encoding, identity.threadId!, sessionsDir, selectionDir, identity.turnId, identity.forkedFrom); }
+ const rewriteNow = (): { body: Buffer; report: Json; attempts?: ClaudeAttempt[]; prefix?: SentPrefix } => {
+ try { return claudeRewrite ? rewriteClaudeBody(original, encoding, claudeSession!, undefined, undefined, undefined, thinking, sentPrefixes.get(claudeSession!) ?? []) : rewriteBody(original, encoding, identity.threadId!, sessionsDir, selectionDir, identity.turnId, identity.forkedFrom); }
catch (error) { return { body: original, report: { skipped: `rewrite failed: ${String(error)}` } }; }
};
let out = rewriteNow();
@@ -943,7 +965,7 @@ async function main(): Promise<void> {
let waited = 0;
for (; claudeRewrite && out.report?.late && waited < LATE_WAIT_MS; waited += LATE_STEP_MS) { await sleep(LATE_STEP_MS); out = rewriteNow(); }
const withWait = (report: Json) => (waited ? { ...report, waitedMs: waited } : report);
- const attempts: Attempt[] = out.attempts?.length ? out.attempts.map((attempt) => ({ ...attempt, report: withWait(attempt.report), edited: attempt.body !== original })) : [{ body: out.body, report: withWait(out.report), edited: out.body !== original }];
+ const attempts: Attempt[] = out.attempts?.length ? out.attempts.map((attempt) => ({ ...attempt, report: withWait(attempt.report), edited: attempt.body !== original })) : [{ body: out.body, report: withWait(out.report), edited: out.body !== original, prefix: out.prefix }];
send(attempts);
});
};
diff --git a/spike/src/claude-cache.test.ts b/spike/src/claude-cache.test.ts
new file mode 100644
index 0000000..ba6802f
--- /dev/null
+++ b/spike/src/claude-cache.test.ts
@@ -0,0 +1,104 @@
+// Purpose: v0.10 — where the engine puts the prompt-cache marks of a Claude Code request, so it still reads what the
+// ones before it wrote after the engine changed the history (claude-cache.ts). Input: requests shaped like Claude
+// Code's (two marks at the end of the messages, two in the system prompt). Output: Node test assertions only.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import { keepCacheRead, marksOutside, sentPrefixOf } from "../../plugin/src/claude-cache.ts";
+
+const mark = { type: "ephemeral", ttl: "1h" };
+const text = (value: string, marked = false) => ({ type: "text", text: value, ...(marked ? { cache_control: mark } : {}) });
+const user = (...content: any[]) => ({ role: "user", content });
+const assistant = (...content: any[]) => ({ role: "assistant", content });
+const tokens = (left: number, marked = false) => (marked ? { role: "system", content: [text(`<total_tokens>${left}</total_tokens>`, true)] } : { role: "system", content: `<total_tokens>${left}</total_tokens>` });
+const read = (id: string, marked = false) => ({ type: "tool_use", id, name: "Read", input: { file_path: `${id}.png` }, ...(marked ? { cache_control: mark } : {}) });
+const result = (id: string, body: string, marked = false) => ({ type: "tool_result", tool_use_id: id, content: [text(body)], ...(marked ? { cache_control: mark } : {}) });
+const marked = (messages: any[]) => sentPrefixOf(messages).marks.map(({ message, block }) => `${message}.${block}`);
+const plain = (messages: any[]) => messages.map((message) => JSON.stringify(message).replace(/,"cache_control":\{[^}]*\}/g, ""));
+
+// Turn 1 as sent with its image: the request after the Read (marks on the Read call and on the closing system message).
+const turnOne = (image: string, marks: boolean) => [
+ user(text("look at a.png")), tokens(100), assistant(read("t1", marks)), user(result("t1", image)), tokens(99, marks),
+];
+const before = turnOne("[IMG-001 included] <image>", true);
+// Turn 2's first request: turn 1's image is now a placeholder, Claude Code's marks are at its new end.
+const after = [
+ ...turnOne("[IMG-001 omitted] placeholder", false), assistant(text("a red dress", true)), user(text("now b.png")), tokens(98, true),
+];
+
+test("v0.10: after the engine changed the history, a mark goes where the request before had one before the change", () => {
+ const { messages, marks } = keepCacheRead(after, [sentPrefixOf(before)], 2);
+ assert.deepEqual(marks, { read: { message: 2, block: 0 }, prepare: null, dropped: [{ message: 5, block: 0 }] });
+ // The Read call carries the mark again; the closing system message keeps its own, the request still writes its end.
+ assert.deepEqual(marked(messages), ["2.0", "7.0"]);
+ assert.deepEqual(messages[2].content[0].cache_control, mark);
+ // Nothing else changed, and the input is left as it was.
+ assert.deepEqual(plain(messages), plain(after));
+ assert.deepEqual(marked(after), ["5.0", "7.0"]);
+});
+
+test("v0.10: when the last request's marks both come after the change, the one before it can still be read", () => {
+ // Eval #4 → #6: the images went out once more (no feature line yet), then became placeholders mid-turn.
+ const older = [user(text("look at a.png")), assistant(read("t1", true)), user(result("t1", "[IMG-001 included] <image>", true))];
+ const newer = [user(text("look at a.png")), assistant(read("t1")), user(result("t1", "[IMG-001 included] <image>")), assistant(text("ok", true)), user(text("now b.png", true))];
+ const now = [...newer.slice(0, 2), user(result("t1", "[IMG-001 omitted] placeholder")), assistant(text("ok")), user(text("now b.png")), assistant(read("t2", true)), user(result("t2", "[IMG-002 included] <image>", true))];
+ assert.equal(keepCacheRead(now, [sentPrefixOf(newer)], 2).marks, null);
+ assert.deepEqual(keepCacheRead(now, [sentPrefixOf(newer), sentPrefixOf(older)], 2).marks?.read, { message: 1, block: 0 });
+});
+
+test("v0.10: a mark is prepared just before the first image a later request will leave out", () => {
+ // A turn whose images went out once more: they sit after Claude Code's marks of every request so far.
+ const now = [user(text("look at a.png")), assistant(read("t1")), user(result("t1", "[IMG-001 included] <image>")), assistant(text("ok", true)), user(text("now b.png", true))];
+ const { messages, marks } = keepCacheRead(now, [], 2, { message: 2, block: 0 });
+ assert.deepEqual(marks?.prepare, { message: 1, block: 0 });
+ assert.deepEqual(marked(messages), ["1.0", "4.0"]);
+ // With a read as well, the two places go to the read and the prepared one; Claude Code's end gives way.
+ const sent = [user(text("look at a.png", true)), assistant(read("t1")), user(result("t1", "[IMG-001 included] <image>")), assistant(text("ok", true))];
+ const changed = [user(text("look at a.png")), assistant(read("t1")), user(result("t1", "[IMG-001 omitted]")), assistant(text("ok")), user(text("now b.png")), assistant(read("t2")), user(result("t2", "[IMG-002 included] <image>", true))];
+ const both = keepCacheRead(changed, [sentPrefixOf(sent)], 2, { message: 6, block: 0 });
+ assert.deepEqual([both.marks?.read, both.marks?.prepare], [{ message: 0, block: 0 }, { message: 5, block: 0 }]);
+ assert.deepEqual(marked(both.messages), ["0.0", "5.0"]);
+ // A thinking block takes no mark: the prepared place is the block before it.
+ const thought = [user(text("a")), assistant({ type: "thinking", thinking: "", signature: "s" }), user(result("t1", "<image>", true))];
+ assert.deepEqual(keepCacheRead(thought, [], 2, { message: 2, block: 0 }).marks?.prepare, { message: 0, block: 0 });
+});
+
+test("v0.10: a request that only adds to the last one keeps Claude Code's marks", () => {
+ const next = [...before.map((message, i) => (i === 4 ? tokens(99) : message)), assistant(text("ok", true)), user(text("next")), tokens(97, true)];
+ // The closing message went out as a marked block then and as a string now: the same message.
+ assert.equal(keepCacheRead(next, [sentPrefixOf(before)], 2).marks, null);
+});
+
+test("v0.10: no mark is moved when nothing before the change was marked, or nothing is known of the last request", () => {
+ const early = after.map((message, i) => (i === 0 ? user(text("look at a.png again")) : message));
+ assert.equal(keepCacheRead(early, [sentPrefixOf(before)], 2).marks, null);
+ assert.equal(keepCacheRead(after, [], 2).marks, null);
+});
+
+test("v0.10: with a place to spare, Claude Code's marks all stay", () => {
+ const added = keepCacheRead(after, [sentPrefixOf(before)], 1);
+ assert.deepEqual(marked(added.messages), ["2.0", "5.0", "7.0"]);
+});
+
+test("v0.10: a mark on a message now sent as a string goes on its text block", () => {
+ const sent = [...before.slice(0, 4).map((message, i) => (i === 2 ? assistant(read("t1")) : message)), tokens(99, true), assistant(read("t2", true)), user(result("t2", "[IMG-002 included] <image>")), tokens(98, true)];
+ const now = [...sent.slice(0, 4), tokens(99), assistant(read("t2")), user(result("t2", "[IMG-002 omitted] placeholder")), tokens(98), assistant(text("done", true)), user(text("next")), tokens(97, true)];
+ const { messages, marks } = keepCacheRead(now, [{ ...sentPrefixOf(sent), marks: [{ message: 4, block: 0 }, { message: 7, block: 0 }] }], 2);
+ assert.deepEqual(marks?.read, { message: 4, block: 0 });
+ assert.deepEqual(messages[4], { role: "system", content: [{ type: "text", text: "<total_tokens>99</total_tokens>", cache_control: mark }] });
+});
+
+test("v0.10: a mark put earlier takes the TTL of Claude Code's next mark, so longer TTLs still come first", () => {
+ const short = { type: "ephemeral" };
+ const now = after.map((message, i) => (i === 7 ? { role: "system", content: [{ type: "text", text: "<total_tokens>98</total_tokens>", cache_control: short }] } : message));
+ const { messages } = keepCacheRead(now, [sentPrefixOf(before)], 1);
+ // Before a 1-hour mark: 1 hour; the end keeps its 5 minutes.
+ assert.deepEqual([messages[2].content[0].cache_control, messages[5].content[0].cache_control, messages[7].content[0].cache_control], [mark, mark, short]);
+ const onlyShort = keepCacheRead(now.map((message, i) => (i === 5 ? assistant(text("a red dress")) : message)), [sentPrefixOf(before)], 2).messages;
+ assert.deepEqual(onlyShort[2].content[0].cache_control, short);
+});
+
+test("v0.10: marks outside the messages count against the four allowed", () => {
+ assert.equal(marksOutside({ system: [text("a"), text("b", true), text("c", true)], tools: [{ name: "x" }] }), 2);
+ assert.equal(marksOutside({ cache_control: mark, system: "plain" }), 1);
+});
diff --git a/spike/src/notes.test.ts b/spike/src/notes.test.ts
index 80bdc94..e586d94 100644
--- a/spike/src/notes.test.ts
+++ b/spike/src/notes.test.ts
@@ -10,7 +10,7 @@ import test from "node:test";
import { buildClaudeIndex } from "../../plugin/src/claude-index.ts";
import { rewriteMessages } from "../../plugin/src/claude-rewrite.ts";
import { findImages, type ImageRef } from "../../plugin/src/images.ts";
-import { addNotes, sceneOf, type Notes } from "../../plugin/src/notes.ts";
+import { addNotes, notesBy, sceneOf, type Notes } from "../../plugin/src/notes.ts";
import { autoPlaceholder, clip, featureNote, plainPlaceholder, rewriteItems, type Described } from "../../plugin/src/rewrite.ts";
import { buildIndex, writesNotes, type Parsed } from "../../plugin/src/thread-index.ts";
import { claudeTurnTexts, loadPanelState, panelStateOf } from "../../plugin/src/panel-state.ts";
@@ -161,6 +161,36 @@ test("Claude: the feature line note follows the message holding the first image,
assert.deepEqual([some.report.featureAt, some.report.noteAt], [1, 4]);
});
+// v0.10: a placeholder or the list after a compaction changing later rewrote the prompt cache from there (claude-cache.ts).
+test("v0.10: a placeholder shows the ratings of the image's own turn; the list after a compaction, the notes as they stood then", () => {
+ assert.deepEqual(notesBy({ line: "书房|红色方块", ratings: [{ turn: 1, text: "好" }, { turn: 3, text: "太暗" }] }, 2), { line: "书房|红色方块", ratings: [{ turn: 1, text: "好" }] });
+ assert.equal(notesBy({ line: null, ratings: [{ turn: 3, text: "太暗" }] }, 2), undefined);
+ const notes = { line: "x", ratings: [{ turn: null, text: "好" }] };
+ assert.equal(notesBy(notes, 1), notes);
+ const t = transcript();
+ const p1 = t.prompt([image(pngA), text("first")]);
+ t.assistant(text("[//]: # (cam IMG-001 书房|红色方块)\n\nA red square."));
+ t.prompt("too dark");
+ t.assistant(text("[//]: # (cam IMG-001 评价:太暗)\n\nNoted."));
+ const messages = [
+ { role: "user", content: [image(pngA), text("first")] },
+ { role: "assistant", content: [text("A red square.")] },
+ { role: "user", content: [text("too dark")] },
+ { role: "assistant", content: [text("Noted.")] },
+ { role: "user", content: [text("next")] },
+ ];
+ const placeholder = rewriteMessages(messages, buildClaudeIndex("s", t.records), new Set([`${p1}#0`]), () => null, { features: true, auto: { currentTurn: 3 } }).messages[0].content[0].text;
+ assert.match(placeholder, /书房|红色方块/);
+ assert.doesNotMatch(placeholder, /太暗/);
+ t.boundary();
+ t.summary();
+ t.prompt("after");
+ t.assistant(text("[//]: # (cam IMG-001 评价:又好了)\n\nOk."));
+ const index = buildClaudeIndex("s", t.records);
+ assert.deepEqual(index.compactedNotes.get("IMG-001")?.ratings.map((rating) => rating.text), ["太暗"]);
+ assert.deepEqual(index.notes.get("IMG-001")?.ratings.map((rating) => rating.text), ["太暗", "又好了"]);
+});
+
// 2026-10-19: right after a tool result, Haiku 5.5 took the note for part of what the tool returned and refused it.
test("Claude: when the first image came from a tool, the feature line note follows the user's message of that turn", () => {
const t = transcript();
diff --git a/spike/src/proxy.test.ts b/spike/src/proxy.test.ts
index f1e05d7..d211809 100644
--- a/spike/src/proxy.test.ts
+++ b/spike/src/proxy.test.ts
@@ -246,6 +246,39 @@ test("the panel's last request is the session's conversation, not Claude Desktop
assert.equal(claudeConversationRequest(describeBody("/backend-api/codex/responses", { input: [] })), false);
});
+test("v0.10: once the engine changes the history, a cache mark moves to where the request sent before had one", async () => {
+ const { usualSession, usualRequest } = await import("./claude-fixtures.ts");
+ const { rewriteClaudeBody } = await import("../../plugin/src/proxy.ts");
+ const home = mkdtempSync(join(tmpdir(), "cam-claude-home-"));
+ const dir = mkdtempSync(join(tmpdir(), "cam-claude-sel-"));
+ const session = "11111111-2222-4333-8444-555555555556";
+ const { t } = usualSession();
+ mkdirSync(join(home, "projects", "D--work"), { recursive: true });
+ writeFileSync(join(home, "projects", "D--work", `${session}.jsonl`), t.records.map((record) => JSON.stringify(record)).join("\n") + "\n");
+ const mark = { type: "ephemeral", ttl: "1h" };
+ // As Claude Code sends them: two marks in the system prompt, two at the end of the messages.
+ const request = (marked: number) => {
+ const messages = usualRequest();
+ const last = messages[marked].content.at(-1);
+ messages[marked] = { ...messages[marked], content: [...messages[marked].content.slice(0, -1), { ...last, cache_control: mark }] };
+ return Buffer.from(JSON.stringify({ model: "claude-haiku-5-5", tools: [{ name: "Read" }], system: [{ type: "text", text: "a", cache_control: mark }, { type: "text", text: "b", cache_control: mark }], messages }));
+ };
+ // The request before, when the Read call was the last assistant message: sent with nothing left out.
+ const before = rewriteClaudeBody(request(3), undefined, session, dir, home, {});
+ assert.ok(before.attempts[0].prefix);
+ writeSelection({ threadId: session, unchecked: { "tool:toolu_1#0": { id: "IMG-003", at: "2026-10-10T00:00:00Z" } } }, dir);
+ const out = rewriteClaudeBody(request(7), undefined, session, dir, home, {}, null, [before.attempts[0].prefix!]);
+ const sent = JSON.parse(out.body.toString("utf8")).messages;
+ const at = sent.findIndex((message: any) => message.content?.[0]?.type === "tool_use");
+ assert.deepEqual(out.report.cacheMarks.read, { message: at, block: 0 });
+ assert.deepEqual(sent[at].content[0].cache_control, mark);
+ // Moved from the last assistant message, which comes after the change; the end keeps its mark.
+ assert.equal(sent.filter((message: any) => message.content?.some?.((block: any) => block.cache_control)).length, 2);
+ assert.ok(sent.at(-1).content.at(-1).cache_control);
+ // Without the request before, Claude Code's marks are left as they are.
+ assert.equal(rewriteClaudeBody(request(7), undefined, session, dir, home, {}).report.cacheMarks, undefined);
+});
+
test("a Claude Code request is rewritten from the session's transcript and selection, with images also with nothing unchecked", async () => {
const { usualSession, usualRequest } = await import("./claude-fixtures.ts");
const { claudeNeedsRewrite, rewriteClaudeBody, claudeImageSizes } = await import("../../plugin/src/proxy.ts");