Skip to content

A local plugin for image-heavy chats in Codex, Claude Code and other agents: earlier images stop going out with every message, and the model fetches the one it needs by its ID, also after compaction.

refactor(rewrite): one plan in the core, put into each request format

chipfighter0257c1fdfe64
diff --git a/AGENTS.md b/AGENTS.md
index cead2ab..7ef1770 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -30,7 +30,7 @@ Context Attachment Manager(上下文素材管理器,2026-10-11 前叫 Codex
- 先在 Windows 上开发和测试。技术栈用 TypeScript/Node。
- 界面开发:Claude 自己截图检查效果;做到界面的关键节点时,截图给用户看,停下来等反馈再继续(用户 2026-09-24 确认)。
- 测试时调用模型一律用 `gpt-6-sol`,推理强度 `low`,包括脚本自测和桌面版测试,为了省 token(用户 2026-09-24 要求)。
-- 界面和提示文字分简体中文、英文两份:面板的在 `plugin/src/panel/panel.html` 的文字表里,插件服务和命令行的在 `plugin/src/messages.ts`。新增或修改文字时两份一起改,单元测试会检查条目一一对应。改发给模型的占位符和说明(`plugin/src/rewrite.ts`)时,中文、英文(`--lang en`)各跑一次 `spike/src/v01-placeholder-selftest.ts`(用户 2026-09-25 要求)和 `spike/src/v01-needs-selftest.ts`(没有名字的工具截图全部取消后,模型能不能按编号要图、面板能不能认出来;用户 2026-09-26 要求);改的是自动选图的文字(自动版的占位符和说明、`cam_view_image` 的说明和返回的文字)时,再跑 `spike/src/v03-auto-selftest.ts`(模型该取图时会不会取、不该取时会不会不取;用户 2026-10-06 要求);改的是特征行说明时,再跑 `spike/src/v08-features-selftest.ts`(模型会不会给新图写特征行、照原话记评价、正文里不提,压缩后能不能靠特征行拿对图;v0.8);改的是压缩后放回的说明和清单时,再跑 `spike/src/v10-compaction-selftest.ts`(Codex 压缩之后,模型能不能靠清单认出之前的图、要看原图时按编号取对;v0.10)。这些自测三个 GPT-6 模型都要跑:`gpt-6-sol`、`gpt-6-luna`、`gpt-6-astra`,推理强度 low,用环境变量 `CAM_TEST_MODEL` 切换(用户 2026-09-28 要求)。自测在用户的 Codex 里建的任务,测完由脚本自动归档,不留给用户手动整理(用户 2026-09-28 要求);遗留的可以用 `spike/scripts/archive-test-threads.ts` 归档。
+- 界面和提示文字分简体中文、英文两份:面板的在 `plugin/src/panel/panel.html` 的文字表里,插件服务和命令行的在 `plugin/src/messages.ts`。新增或修改文字时两份一起改,单元测试会检查条目一一对应。改发给模型的占位符和说明(`plugin/src/core/words.ts`)时,中文、英文(`--lang en`)各跑一次 `spike/src/v01-placeholder-selftest.ts`(用户 2026-09-25 要求)和 `spike/src/v01-needs-selftest.ts`(没有名字的工具截图全部取消后,模型能不能按编号要图、面板能不能认出来;用户 2026-09-26 要求);改的是自动选图的文字(自动版的占位符和说明、`cam_view_image` 的说明和返回的文字)时,再跑 `spike/src/v03-auto-selftest.ts`(模型该取图时会不会取、不该取时会不会不取;用户 2026-10-06 要求);改的是特征行说明时,再跑 `spike/src/v08-features-selftest.ts`(模型会不会给新图写特征行、照原话记评价、正文里不提,压缩后能不能靠特征行拿对图;v0.8);改的是压缩后放回的说明和清单时,再跑 `spike/src/v10-compaction-selftest.ts`(Codex 压缩之后,模型能不能靠清单认出之前的图、要看原图时按编号取对;v0.10)。这些自测三个 GPT-6 模型都要跑:`gpt-6-sol`、`gpt-6-luna`、`gpt-6-astra`,推理强度 low,用环境变量 `CAM_TEST_MODEL` 切换(用户 2026-09-28 要求)。自测在用户的 Codex 里建的任务,测完由脚本自动归档,不留给用户手动整理(用户 2026-09-28 要求);遗留的可以用 `spike/scripts/archive-test-threads.ts` 归档。
- 分工:Claude 维护 `docs/` 下的规格和方案,并负责开发和测试(阶段 0 的 T0–T2 由 Codex 完成;测试需要在 Codex 之外启动 app-server,所以从 T3 起改由 Claude 执行)。其他协作者不修改 spec.md 和 design.md。
## Git 规范
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 555825b..13c08ba 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -24,7 +24,7 @@ Bug reports, ideas and pull requests are all welcome. For a bug, an [issue](http
- Run the tests with Node 24 or later: `cd spike && node --test`. CI runs them on Windows, macOS and Linux, then installs the plugin with Codex's CLI and runs the install and uninstall scripts.
- Work on the panel without Codex: `node spike/scripts/panel-dev.ts`, then open `http://127.0.0.1:17895/?solo=1`, or `?solo=1&thread=v08` for a task with the model's notes (add `&lang=en` for English). The page uses synthetic images and a temporary Codex folder, so your real data is never read or changed.
- Text in the panel and the command line comes in English and Simplified Chinese: the panel's in the string table of `plugin/src/panel/panel.html`, the rest in `plugin/src/messages.ts`. Change both; a unit test checks that they match.
-- When you change the text the model sees (`plugin/src/rewrite.ts`), run the self-tests in `spike/src/v01-placeholder-selftest.ts` and `spike/src/v01-needs-selftest.ts`, and for Auto-select's wording `spike/src/v03-auto-selftest.ts`, in Chinese and with `--lang en`; `spike/src/v07-children-selftest.ts` covers subagents and side chats, and `spike/src/v08-features-selftest.ts` the model's notes, including after a compaction. They start their own engine and app-server, use your Codex account, and archive the test tasks they create.
+- When you change the text the model sees (`plugin/src/core/words.ts`), run the self-tests in `spike/src/v01-placeholder-selftest.ts` and `spike/src/v01-needs-selftest.ts`, and for Auto-select's wording `spike/src/v03-auto-selftest.ts`, in Chinese and with `--lang en`; `spike/src/v07-children-selftest.ts` covers subagents and side chats, and `spike/src/v08-features-selftest.ts` the model's notes, including after a compaction. They start their own engine and app-server, use your Codex account, and archive the test tasks they create.
## Pull requests
diff --git a/docs/design.md b/docs/design.md
index f8ea5c5..6b9ad2b 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -23,13 +23,13 @@ v0.11 起代码分成三层([v0.11/plan.md](v0.11/plan.md)):`core/` 是不
| 引擎 | `proxy.ts`、`engine.ts`、`core/routes.ts` | 本机代理:按绑定线路转发、改写请求、记录每个任务最近一次请求的统计;全机只有一个 |
| 插件服务 | `plugin-server.ts` | Codex 为每个会话启动的 MCP 服务:拉起并看守引擎,给面板提供数据;v0.3 起还给模型提供取图工具 |
| 面板 | `panel/panel.html`、`panel/panel-state.ts` | 侧边面板里的 MCP 应用,以及它要显示的数据 |
-| 任务索引 | `adapters/codex/thread-index.ts`、`images.ts`、`core/thumbnail.ts`、`core/png.ts`、`adapters/codex/thread-names.ts` | 从 Codex 的任务记录里只读地找出图片和它的来源、编号、生成缩略图、读任务名 |
-| 改写 | `rewrite.ts`、`selection.ts`、`core/request-stats.ts`、`core/notes.ts` | 占位符、说明和标签;勾选状态;请求统计;特征行 |
+| 任务索引 | `adapters/codex/thread-index.ts`、`adapters/protocols/openai-responses/images.ts`、`core/images.ts`、`core/thumbnail.ts`、`core/png.ts`、`adapters/codex/thread-names.ts` | 从 Codex 的任务记录里只读地找出图片和它的来源、编号、生成缩略图、读任务名 |
+| 改写 | `core/plan.ts`、`core/words.ts`、`adapters/protocols/openai-responses/rewrite.ts`、`selection.ts`、`core/request-stats.ts`、`core/notes.ts` | 每张图发不发、换成什么字(两个平台共用);发给模型的全部文字;把决定落进 Responses 请求;勾选状态;请求统计;特征行 |
| 接入和安装 | `adapters/codex/`:`codexconfig.ts`、`setup.ts`、`install.ts`、`codexcli.ts`、`plugin-cache.ts`、`binding.ts`;`cam.ts` | 管理 Codex 配置里带标记的块;用 Codex 的命令行装卸插件;保护升级中的旧运行文件;新任务绑定;`cam` 命令行 |
| 其他 | `language.ts`、`messages.ts`、`core/paths.ts`、`core/migrate-data.ts`、`core/entry.ts` | 语言、文字表、数据目录、旧数据迁移 |
| Claude 接入(v0.4) | `hooks/register.js`(Mod,不在 `plugin/src`) | 把会话的请求地址指向引擎;`/cam` 打开面板(v0.6 起有图时自动打开);取图工具免确认 |
-| Claude 会话索引和改写(v0.4) | `adapters/claude/claude-index.ts`、`claude-rewrite.ts` | 从 Claude Code 的会话记录找图、编号;改写 Anthropic Messages 请求 |
-| Claude 思考记录(v0.4) | `claude-thinking.ts` | 账号校验思考记录时,去掉和实际发出的历史对不上的思考 |
+| Claude 会话索引和改写(v0.4) | `adapters/claude/claude-index.ts`、`adapters/claude/claude-rewrite.ts`、`adapters/protocols/anthropic-messages/rewrite.ts` | 从 Claude Code 的会话记录找图、编号,把请求里的图对上记录;把决定落进 Anthropic Messages 请求 |
+| Claude 思考记录和提示缓存(v0.4、v0.10) | `adapters/protocols/anthropic-messages/thinking.ts`、`adapters/protocols/anthropic-messages/cache.ts` | 账号校验思考记录时,去掉和实际发出的历史对不上的思考;改过历史后,让提示缓存仍能读到 |
| 面板页(v0.4) | `panel/panel-web.js`、`panel/panel-language.ts` | 引擎把 `panel.html` 作为网页提供时,代替 MCP 应用的宿主 |
引擎和插件服务之间只通过数据目录里的文件共享状态,任何一方不在,另一方都照常工作。
diff --git a/plugin/src/adapters/claude/claude-index.ts b/plugin/src/adapters/claude/claude-index.ts
index 498dd93..71d394f 100644
--- a/plugin/src/adapters/claude/claude-index.ts
+++ b/plugin/src/adapters/claude/claude-index.ts
@@ -22,7 +22,8 @@
import { closeSync, existsSync, openSync, readdirSync, readFileSync, readSync, statSync } from "node:fs";
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 { baseName, FETCHED_STATE, imageDigest, type ImageKind } from "../../core/images.ts";
+import type { ImageRef } from "../protocols/openai-responses/images.ts";
import { addNotes, copyNotes, type Notes } from "../../core/notes.ts";
import { pixelHashOfData, type FetchedCopy, type IndexedImage, type ThreadIndex } from "../codex/thread-index.ts";
diff --git a/plugin/src/adapters/claude/claude-rewrite.ts b/plugin/src/adapters/claude/claude-rewrite.ts
new file mode 100644
index 0000000..4c2e2e1
--- /dev/null
+++ b/plugin/src/adapters/claude/claude-rewrite.ts
@@ -0,0 +1,81 @@
+// Purpose: v0.4 — the engine's rewrite of a Claude Code request: which index entry each image of the request is, and
+// what the session's index knows of it; the rewrite itself is the Anthropic Messages translator's
+// (adapters/protocols/anthropic-messages) and the core's.
+// Matching to the index (claude-index.ts): an image inside a tool result by its tool_use_id; pasted images by
+// content, a request message to the transcript record(s) holding the same images in the same order.
+// v0.8: placeholders carry what the model noted (as noted by the image's own turn). v0.10: images sent once more for
+// their feature line are marked in their labels.
+// v0.11: split from claude-rewrite.ts (docs/v0.11/plan.md).
+// Input: the request's messages, the session's index, the keys to leave out. Output: new messages plus a report.
+
+import { notesBy } from "../../core/notes.ts";
+import type { RewriteReport } from "../../core/plan.ts";
+import { imageBlocks, rewriteBlocks, type MessagesOptions, type RequestImage } from "../protocols/anthropic-messages/rewrite.ts";
+import type { ClaudeIndex, ClaudeImage } from "./claude-index.ts";
+
+type Json = Record<string, any>;
+
+const sameList = (a: string[], b: string[]) => a.length === b.length && a.every((value, i) => value === b[i]);
+
+// Every image of the request, with the index key it matches (null: not in the index, e.g. pasted in this turn).
+export function findRequestImages(messages: Json[], index: Pick<ClaudeIndex, "uploads">): RequestImage[] {
+ const found = imageBlocks(messages);
+ const pastedBy = new Map<number, RequestImage[]>();
+ for (const image of found) if (image.sub === null) pastedBy.set(image.msg, [...(pastedBy.get(image.msg) ?? []), image]);
+ // Pasted images: each message, in order, to the next record(s) after the last match holding the same images in the
+ // same order (Claude Code may join consecutive records into one message). Records before the latest compaction are
+ // looked at only when nothing later matches.
+ const uploads = index.uploads;
+ const used = new Set<number>();
+ let next = uploads.findIndex((upload) => !upload.compacted);
+ if (next < 0) next = uploads.length;
+ const matchAt = (start: number, ids: string[]): number[] | null => {
+ const taken: number[] = [];
+ let at = 0;
+ for (let i = start; i < uploads.length && at < ids.length; i++) {
+ if (used.has(i)) return null;
+ const part = uploads[i].contentIds;
+ if (!sameList(part, ids.slice(at, at + part.length))) return null;
+ taken.push(i);
+ at += part.length;
+ }
+ return at === ids.length ? taken : null;
+ };
+ for (const [, images] of [...pastedBy].sort((a, b) => a[0] - b[0])) {
+ const ids = images.map((image) => image.contentId);
+ let taken: number[] | null = null;
+ for (let start = next; start < uploads.length && !taken; start++) taken = matchAt(start, ids);
+ for (let start = 0; start < next && !taken; start++) taken = matchAt(start, ids);
+ if (!taken) continue;
+ let position = 0;
+ for (const i of taken) {
+ uploads[i].contentIds.forEach((_, n) => { images[position++].key = `${uploads[i].uuid}#${n}`; });
+ used.add(i);
+ }
+ next = Math.max(next, taken.at(-1)! + 1);
+ }
+ return found;
+}
+
+// v0.10: keys of the images sent once more for their feature line; their labels say so.
+export type ClaudeRewriteOptions = Omit<MessagesOptions, "fetched"> & { awaiting?: Set<string> };
+
+export function rewriteMessages(
+ messages: Json[],
+ index: Pick<ClaudeIndex, "uploads" | "byKey"> & Partial<Pick<ClaudeIndex, "notes" | "copies">>,
+ leaveOut: Set<string>,
+ pixelHash: (image: RequestImage) => string | null,
+ options: ClaudeRewriteOptions = {},
+): { messages: Json[]; report: RewriteReport } {
+ const { awaiting = new Set<string>(), ...rest } = options;
+ const refs = findRequestImages(messages, index);
+ const describe = (ref: RequestImage): ClaudeImage | undefined => {
+ const image = ref.key ? index.byKey.get(ref.key) : 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;
+ };
+ // A copy the model fetched this turn is known as one, not as an image.
+ return rewriteBlocks(messages, refs, describe, leaveOut, pixelHash, { ...rest, fetched: (ref) => !!(ref.key && index.copies?.has(ref.key)) });
+}
diff --git a/plugin/src/adapters/codex/thread-index.ts b/plugin/src/adapters/codex/thread-index.ts
index 038506c..bf043cb 100644
--- a/plugin/src/adapters/codex/thread-index.ts
+++ b/plugin/src/adapters/codex/thread-index.ts
@@ -16,13 +16,13 @@
import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, statSync, writeFileSync } from "node:fs";
import { basename, dirname, join } from "node:path";
import { zstdDecompressSync } from "node:zlib";
-import { findImages, type ImageRef } from "../../images.ts";
+import { findImages, type ImageRef } from "../protocols/openai-responses/images.ts";
import { addNotes, type Notes } from "../../core/notes.ts";
import { decodePng } from "../../core/png.ts";
type Json = Record<string, any>;
// 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.
+// engine puts it back after the compaction (openai-responses/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 };
diff --git a/plugin/src/claude-cache.ts b/plugin/src/adapters/protocols/anthropic-messages/cache.ts
similarity index 99%
rename from plugin/src/claude-cache.ts
rename to plugin/src/adapters/protocols/anthropic-messages/cache.ts
index d3c2b6e..8273968 100644
--- a/plugin/src/claude-cache.ts
+++ b/plugin/src/adapters/protocols/anthropic-messages/cache.ts
@@ -15,7 +15,7 @@
// 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";
+import { link } from "./thinking.ts";
type Json = Record<string, any>;
export type Mark = { message: number; block: number };
diff --git a/plugin/src/claude-rewrite.ts b/plugin/src/adapters/protocols/anthropic-messages/rewrite.ts
similarity index 50%
rename from plugin/src/claude-rewrite.ts
rename to plugin/src/adapters/protocols/anthropic-messages/rewrite.ts
index 9a7bf10..9231cab 100644
--- a/plugin/src/claude-rewrite.ts
+++ b/plugin/src/adapters/protocols/anthropic-messages/rewrite.ts
@@ -1,43 +1,36 @@
-// Purpose: v0.4 — the engine's rewrite of a Claude Code request (Anthropic Messages), with the same rules and words as
-// rewrite.ts for Codex: an image the user unchecked becomes a placeholder (a "duplicate" one when the same content is
-// still sent), every image still sent gets an "included" label once anything is left out, and a context management
-// note explains the placeholders. Automatic selection (v0.3) leaves out earlier turns' images that are not pinned;
-// copies the model fetched are sent in their own turn only.
-// What changes for Claude: images sit in user messages (pasted) and inside tool_result blocks; the note is a
-// mid-conversation system message, which Anthropic allows only right after a user message, so it goes right after
-// the message holding the first omitted image instead of before its turn (docs/v0.4/plan.md, D04-03). Everything else
-// — thinking blocks included — is passed on unchanged.
-// Matching to the index (claude-index.ts): an image inside a tool result by its tool_use_id; pasted images by
-// content, a request message to the transcript record(s) holding the same images in the same order.
-// v0.8: the feature line note follows the user's own message of the turn holding the first image (a system message, as
-// the other notes, but never right after a tool result), and every image sent gets its id, also the ones new in this
-// turn; placeholders carry what the model noted.
-// Input: the request's messages, the session's index, the keys to leave out. Output: new messages plus a report.
+// Purpose: v0.4 — the rewrite of an Anthropic Messages request (Claude Code): the plan of the core (core/plan.ts) put
+// into the messages, with the same rules and words as for Codex.
+// What is particular to this format: images sit in user messages and inside tool_result blocks; a placeholder keeps the
+// cache breakpoint the image carried; the notes are mid-conversation system messages, which Anthropic allows only
+// right after a user message (joined with one already there), so the note follows the message holding the omitted
+// images instead of going before their turn (docs/v0.4/plan.md, D04-03). Everything else — thinking blocks included —
+// is passed on unchanged.
+// v0.8: the feature line note follows the user's own message of the turn holding the first image (never right after a
+// tool result). v0.5: after a compaction, the images from before it go back right after the summary.
+// v0.11: split from claude-rewrite.ts (docs/v0.11/plan.md): which index key a pasted image matches is the platform's
+// business (adapters/claude/claude-rewrite.ts); an image in a tool result is keyed by its tool_use_id here.
+// Input: the request's messages, its images with their keys, a lookup into the index. Output: new messages and a report.
-import type { ClaudeIndex, ClaudeImage } from "./adapters/claude/claude-index.ts";
-import { imageDigest, type ImageDigest, type ImageKind } from "./images.ts";
-import type { Lang } from "./language.ts";
-import { notesBy } from "./core/notes.ts";
-import { autoPlaceholder, claudeNote, compactedNote, compactList, copyNote, duplicatePlaceholder, featureNote, hereNote, includedLabel, newImageWord, plainPlaceholder, type Described, type RewriteReport } from "./rewrite.ts";
+import { imageDigest, type ImageDigest, type ImageKind } from "../../../core/images.ts";
+import type { Lang } from "../../../core/lang.ts";
+import { planRewrite, type PlanOptions, type RewriteReport } from "../../../core/plan.ts";
+import { claudeNote, compactedNote, compactList, featureNote, hereNote, includedLabel, type Described } from "../../../core/words.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.
-export type RequestImage = ImageDigest & { msg: number; part: number; sub: number | null; key: string | null; kind: ImageKind; block: Json };
+export type RequestImage = ImageDigest & { msg: number; part: number; sub: number | null; key: string | null; kind: ImageKind; name: null; label: null; replaceable: true; block: Json };
-const sameList = (a: string[], b: string[]) => a.length === b.length && a.every((value, i) => value === b[i]);
-
-// Every image of the request, with the index key it matches (null: not in the index, e.g. pasted in this turn).
-export function findRequestImages(messages: Json[], index: Pick<ClaudeIndex, "uploads">): RequestImage[] {
+// Every image of the request in order: pasted ones without a key (the platform matches them to its records), the ones
+// in a tool result keyed `tool:<tool_use_id>#<n>`.
+export function imageBlocks(messages: Json[]): RequestImage[] {
const found: RequestImage[] = [];
- const pastedBy = new Map<number, RequestImage[]>();
+ const own = { name: null, label: null, replaceable: true } as const;
messages.forEach((message, msg) => {
if (message?.role !== "user" || !Array.isArray(message.content)) return;
const perTool = new Map<string, number>();
message.content.forEach((block: Json, part: number) => {
if (block?.type === "image" && typeof block.source?.data === "string") {
- const image: RequestImage = { ...imageDigest(block, block.source.data, block.source.media_type ?? null), msg, part, sub: null, key: null, kind: "upload", block };
- found.push(image);
- pastedBy.set(msg, [...(pastedBy.get(msg) ?? []), image]);
+ found.push({ ...imageDigest(block, block.source.data, block.source.media_type ?? null), msg, part, sub: null, key: null, kind: "upload", ...own, block });
}
if (block?.type === "tool_result" && Array.isArray(block.content)) {
block.content.forEach((inner: Json, sub: number) => {
@@ -45,100 +38,32 @@ export function findRequestImages(messages: Json[], index: Pick<ClaudeIndex, "up
const id = String(block.tool_use_id ?? "");
const m = perTool.get(id) ?? 0;
perTool.set(id, m + 1);
- found.push({ ...imageDigest(inner, inner.source.data, inner.source.media_type ?? null), msg, part, sub, key: `tool:${id}#${m}`, kind: "tool", block: inner });
+ found.push({ ...imageDigest(inner, inner.source.data, inner.source.media_type ?? null), msg, part, sub, key: `tool:${id}#${m}`, kind: "tool", ...own, block: inner });
});
}
});
});
- // Pasted images: each message, in order, to the next record(s) after the last match holding the same images in the
- // same order (Claude Code may join consecutive records into one message). Records before the latest compaction are
- // looked at only when nothing later matches.
- const uploads = index.uploads;
- const used = new Set<number>();
- let next = uploads.findIndex((upload) => !upload.compacted);
- if (next < 0) next = uploads.length;
- const matchAt = (start: number, ids: string[]): number[] | null => {
- const taken: number[] = [];
- let at = 0;
- for (let i = start; i < uploads.length && at < ids.length; i++) {
- if (used.has(i)) return null;
- const part = uploads[i].contentIds;
- if (!sameList(part, ids.slice(at, at + part.length))) return null;
- taken.push(i);
- at += part.length;
- }
- return at === ids.length ? taken : null;
- };
- for (const [, images] of [...pastedBy].sort((a, b) => a[0] - b[0])) {
- const ids = images.map((image) => image.contentId);
- let taken: number[] | null = null;
- for (let start = next; start < uploads.length && !taken; start++) taken = matchAt(start, ids);
- for (let start = 0; start < next && !taken; start++) taken = matchAt(start, ids);
- if (!taken) continue;
- let position = 0;
- for (const i of taken) {
- uploads[i].contentIds.forEach((_, n) => { images[position++].key = `${uploads[i].uuid}#${n}`; });
- used.add(i);
- }
- next = Math.max(next, taken.at(-1)! + 1);
- }
return found;
}
-export type ClaudeRewriteOptions = {
- lang?: Lang;
- // Copies the model fetched in an earlier turn (key → the id they copy): left out in either mode.
- copies?: Map<string, string>;
- // Automatic selection: its wording; placeholders point to, and labels mark, only earlier turns' (pinned) images.
- auto?: { currentTurn: number };
- // v0.5: the full note is given before these messages already (after a compaction summary holding placeholders).
- noted?: boolean;
- // v0.8: the feature line note and ids on this turn's new images too (rewrite.ts).
- features?: boolean;
- // v0.10: keys of the images sent once more for their feature line; their labels say so.
- awaiting?: Set<string>;
-};
+// noted (v0.5): the full note is given before these messages already (after a compaction summary holding placeholders).
+export type MessagesOptions = Omit<PlanOptions<RequestImage>, "fetched"> & { noted?: boolean; fetched?: (ref: RequestImage) => boolean };
-export function rewriteMessages(
+export function rewriteBlocks(
messages: Json[],
- index: Pick<ClaudeIndex, "uploads" | "byKey"> & Partial<Pick<ClaudeIndex, "notes" | "copies">>,
+ refs: RequestImage[],
+ describe: (ref: RequestImage) => Described | undefined,
leaveOut: Set<string>,
pixelHash: (image: RequestImage) => string | null,
- options: ClaudeRewriteOptions = {},
+ options: MessagesOptions = {},
): { messages: Json[]; report: RewriteReport } {
- const { lang = "zh", copies = new Map<string, string>(), auto, noted = false, features = false, awaiting = new Set<string>() } = options;
- const refs = findRequestImages(messages, index);
- const describe = (ref: RequestImage): ClaudeImage | undefined => {
- const image = ref.key ? index.byKey.get(ref.key) : 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;
- };
- const report: RewriteReport = { images: refs.length, replaced: [], locked: [], sentContentIds: [], copies: [] };
- const copied = refs.filter((ref) => ref.key !== null && copies.has(ref.key));
- const drop = refs.filter((ref) => ref.key !== null && !copies.has(ref.key) && leaveOut.has(ref.key) && describe(ref));
- const sent = refs.filter((ref) => !drop.includes(ref) && !copied.includes(ref));
- report.sentContentIds = sent.map((ref) => ref.contentId);
- // A copy the model fetched this turn is known as one, not as an image.
- const unknown = refs.filter((ref) => !copied.includes(ref) && !(ref.key && index.copies?.has(ref.key)) && !describe(ref));
- if (unknown.length) report.unknown = unknown.length;
+ const { lang = "zh", auto, noted = false } = options;
// v0.10: unknown images after the model's latest reply: Claude Code can send a request a moment before those records
// reach its transcript, and they would go out without ids (the engine reads the transcript again, proxy.ts).
const lastReply = messages.map((message) => message?.role).lastIndexOf("assistant");
- const late = unknown.filter((ref) => ref.msg > lastReply).length;
- if (late) report.late = late;
- // v0.8: the first image the index knows; the feature line note follows its message.
- const first = features ? refs.find((ref) => describe(ref)) : undefined;
- if (!drop.length && !copied.length && !first) return { messages, report };
- const earlier = (ref: RequestImage) => { const turn = describe(ref)?.turn; return auto !== undefined && turn !== null && turn !== undefined && turn < auto.currentTurn; };
- const lasting = auto ? sent.filter(earlier) : sent;
- const same = (a: RequestImage, b: RequestImage) => {
- if (a.contentId === b.contentId) return true;
- if (a.width !== b.width || a.height !== b.height) return false;
- const pixels = pixelHash(a);
- return pixels !== null && pixels === pixelHash(b);
- };
+ const plan = planRewrite(refs, describe, leaveOut, pixelHash, { ...options, late: (ref) => ref.msg > lastReply });
+ const { report } = plan;
+ if (!plan.changed) return { messages, report };
// Edits per content array: the message's own content ("3"), or a tool result's ("3:1"). Each puts text blocks at
// `at`, in place of `remove` blocks (none for a label).
type Edit = { at: number; remove: number; blocks: Json[] };
@@ -150,29 +75,7 @@ export function rewriteMessages(
const carried = !before && ref.block.cache_control ? { cache_control: ref.block.cache_control } : {};
edits.set(where, [...(edits.get(where) ?? []), { at, remove, blocks: [{ type: "text", text, ...carried }] }]);
};
- // The messages holding plain placeholders, each with its omitted images, for the notes that follow them.
- const plainBy = new Map<number, Described[]>();
- for (const ref of drop) {
- const image = describe(ref)!;
- const copy = lasting.find((other) => same(other, ref));
- const copyImage: Described | null = copy ? describe(copy) ?? { id: newImageWord(lang), name: null, label: null, kind: copy.kind, turn: null, width: copy.width, height: copy.height } : null;
- const text = copyImage ? duplicatePlaceholder(image, copyImage, lang) : auto ? autoPlaceholder(image, lang) : plainPlaceholder(image, lang);
- if (!copyImage) plainBy.set(ref.msg, [...(plainBy.get(ref.msg) ?? []), image]);
- report.replaced.push({ id: image.id, key: ref.key!, kind: image.kind, mode: copyImage ? "duplicate" : "plain", sameAs: copyImage?.id ?? null, base64Chars: ref.base64Chars });
- edit(ref, 1, text);
- }
- for (const ref of copied) {
- edit(ref, 1, copyNote(copies.get(ref.key!)!, lang));
- report.copies.push(copies.get(ref.key!)!);
- }
- // v0.1-25: once anything is left out, every image still sent says which id it is. v0.8: with feature lines, this
- // turn's new images too.
- for (const ref of features ? sent : lasting) {
- const image = describe(ref);
- if (!image) continue;
- edit(ref, 0, includedLabel(image, lang), true);
- report.labeled = (report.labeled ?? 0) + 1;
- }
+ for (const { slot, what, text } of plan.actions) edit(refs[slot], what === "label" ? 0 : 1, text, what === "label");
const apply = (blocks: Json[], list: Edit[]) => {
const out = [...blocks];
// Later positions first; at one position, a replacement before the label that goes in front of it.
@@ -196,6 +99,8 @@ export function rewriteMessages(
// what a tool result says about itself, and a note far from the placeholder was not enough (desktop tests,
// 2026-10-09). Later messages first, so the earlier positions stay as they are. v0.5: after a compaction summary
// holding placeholders, the full note is there already (`noted`).
+ const plainBy = new Map<number, Described[]>();
+ for (const { slot, image } of plan.plain) plainBy.set(refs[slot].msg, [...(plainBy.get(refs[slot].msg) ?? []), image]);
const holding = [...plainBy.keys()].sort((a, b) => a - b);
for (const msg of [...holding].reverse()) {
noteAfter(next, msg, `${msg === holding[0] && !noted ? `${claudeNote(lang, auto !== undefined)}\n` : ""}${hereNote(plainBy.get(msg)!, lang, auto !== undefined)}`);
@@ -203,8 +108,8 @@ export function rewriteMessages(
if (holding.length && !noted) report.noteAt = holding[0] + 1;
// v0.8: after the user's own message of the turn holding the first image, at or before the others; joined with a
// note already there.
- if (first) {
- const at = promptOf(messages, first.msg);
+ if (plan.first !== null) {
+ const at = promptOf(messages, refs[plan.first].msg);
const added = noteAfter(next, at, featureNote(lang));
report.featureAt = at + 1;
if (added && report.noteAt !== undefined && report.noteAt > at) report.noteAt += 1;
diff --git a/plugin/src/claude-thinking.ts b/plugin/src/adapters/protocols/anthropic-messages/thinking.ts
similarity index 99%
rename from plugin/src/claude-thinking.ts
rename to plugin/src/adapters/protocols/anthropic-messages/thinking.ts
index e3efeea..ef660b0 100644
--- a/plugin/src/claude-thinking.ts
+++ b/plugin/src/adapters/protocols/anthropic-messages/thinking.ts
@@ -12,7 +12,7 @@
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { join } from "node:path";
-import { claudeThinkingDirOf } from "./core/paths.ts";
+import { claudeThinkingDirOf } from "../../../core/paths.ts";
type Json = Record<string, any>;
const THINKING = new Set(["thinking", "redacted_thinking"]);
diff --git a/plugin/src/images.ts b/plugin/src/adapters/protocols/openai-responses/images.ts
similarity index 77%
rename from plugin/src/images.ts
rename to plugin/src/adapters/protocols/openai-responses/images.ts
index c08816b..5102940 100644
--- a/plugin/src/images.ts
+++ b/plugin/src/adapters/protocols/openai-responses/images.ts
@@ -1,16 +1,15 @@
-// Purpose: P2 — find every image in a list of Responses items (a request's `input`, or a rollout's response_items)
+// Purpose: P2 — find every image in a list of Responses items (a request's `input`, or a Codex rollout's response_items)
// and describe it: a key that names the same occurrence in both places, its kind and name, and a content digest.
// v0.2 — the source the panel filters by: the kind, except for the screenshots Codex desktop attaches to a comment on a
// PDF page or a web page, told apart by the caption Codex writes before them. The text for the model does not use it.
// v0.3 — an image our fetch tool returned carries, in the line before it, the id it is a copy of (thread-index.ts).
+// v0.11 — the Responses request format's reader (docs/v0.11/plan.md); the digest and kinds are the core's
+// (core/images.ts). The names and captions it reads are Codex's own; for another client they simply do not match.
// Input: items as parsed JSON. Output: ImageRef[] in item order (pure, no I/O).
-import { createHash } from "node:crypto";
+import { baseName, FETCHED_STATE, imageDigest, type ImageDigest, type ImageKind, type ImageSource } from "../../../core/images.ts";
type Json = Record<string, any>;
-export type ImageKind = "upload" | "view" | "generated" | "tool";
-export type ImageSource = ImageKind | "pdf" | "browser";
-export type ImageDigest = { contentId: string; mime: string | null; base64Chars: number; width: number | null; height: number | null };
export type ImageRef = ImageDigest & {
key: string;
@@ -35,9 +34,6 @@ export type ImageRef = ImageDigest & {
fetchedId: string | null;
};
-// v0.3 — the state our fetch tool (cam_view_image) writes in the line before each image it returns, in either
-// language, so the image is known as a copy of that id. The rest of the line is the usual heading (rewrite.ts).
-export const FETCHED_STATE = { zh: "取回的原图", en: "fetched original" } as const;
const FETCHED_LINE = new RegExp(`^\\[(?:图片|Image) (IMG-\\d{3,}) (?:${FETCHED_STATE.zh}|${FETCHED_STATE.en})(?:|| \\|)`);
const OPEN_TAG = /^<image name=(\[Image #\d+\]) path="(.*)">$/s;
@@ -47,59 +43,11 @@ const PDF_CAPTION = /^The next image shows (?:PDF page (\d+)|the PDF page) at th
const BROWSER_CAPTION = /^The next image (?:shows the browser page at the time of|is untrusted page evidence from the browser page for) Comment \d+\./;
const PDF_PATH = /^PDF path: (.+)$/gm;
-export function baseName(path: string): string {
- return path.split(/[\\/]/).filter(Boolean).pop() ?? path;
-}
-
-// Width and height from the image header only, so large images are not decoded.
-export function imageSize(bytes: Buffer): { width: number; height: number } | null {
- if (bytes.length >= 24 && bytes.readUInt32BE(0) === 0x89504e47) return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
- if (bytes.length >= 10 && bytes.toString("ascii", 0, 3) === "GIF") return { width: bytes.readUInt16LE(6), height: bytes.readUInt16LE(8) };
- if (bytes.length >= 30 && bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP") {
- const chunk = bytes.toString("ascii", 12, 16);
- if (chunk === "VP8X") return { width: bytes.readUIntLE(24, 3) + 1, height: bytes.readUIntLE(27, 3) + 1 };
- if (chunk === "VP8 ") return { width: bytes.readUInt16LE(26) & 0x3fff, height: bytes.readUInt16LE(28) & 0x3fff };
- if (chunk === "VP8L") { const bits = bytes.readUInt32LE(21); return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 }; }
- return null;
- }
- if (bytes.length >= 4 && bytes[0] === 0xff && bytes[1] === 0xd8) {
- let offset = 2;
- while (offset + 9 < bytes.length) {
- if (bytes[offset] !== 0xff) return null;
- const marker = bytes[offset + 1];
- if (marker === 0xff) { offset++; continue; }
- const length = bytes.readUInt16BE(offset + 2);
- // SOF0–SOF15 carry the frame size, except DHT (C4), JPG (C8) and DAC (CC).
- if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) return { width: bytes.readUInt16BE(offset + 7), height: bytes.readUInt16BE(offset + 5) };
- offset += 2 + length;
- }
- }
- return null;
-}
-
-const digests = new WeakMap<object, ImageDigest>();
-
-// Keyed by the part object, so re-reading the same cached rollout records does not hash the same images again.
-function digest(owner: object, value: string, mime: string | null): ImageDigest {
- const known = digests.get(owner);
- if (known) return known;
- const header = Buffer.from(value.slice(0, 96 * 1024), "base64");
- const size = imageSize(header);
- const result = { contentId: createHash("sha256").update(value).digest("hex"), mime, base64Chars: value.length, width: size?.width ?? null, height: size?.height ?? null };
- digests.set(owner, result);
- return result;
-}
-
-// v0.4: the same digest for an image block of a Claude Code transcript or request (raw base64, not a data URL).
-export function imageDigest(owner: object, value: string, mime: string | null): ImageDigest {
- return digest(owner, value, mime);
-}
-
function partDigest(part: Json): ImageDigest | null {
if (part?.type !== "input_image" && part?.type !== "output_image") return null;
if (typeof part.file_id === "string") return { contentId: `file:${part.file_id}`, mime: null, base64Chars: 0, width: null, height: null };
const inline = typeof part.image_url === "string" ? /^data:([^;,]+);base64,/.exec(part.image_url) : null;
- return inline ? digest(part, part.image_url.slice(inline[0].length), inline[1]) : null;
+ return inline ? imageDigest(part, part.image_url.slice(inline[0].length), inline[1]) : null;
}
// v0.10.1 — reading the path of a view_image call in code-mode source, without running it.
@@ -227,7 +175,7 @@ export function findImages(items: Json[]): ImageRef[] {
};
if (item.type === "image_generation_call" && typeof item.result === "string" && item.result) {
- const found = digest(item, item.result, "image/png");
+ const found = imageDigest(item, item.result, "image/png");
refs.push({ ...found, key: keyFor(0, found.contentId), item: index, part: null, openTag: null, closeTag: null, kind: "generated", replaceable: false, name: null, label: null, turnId, source: "generated", pdfPage: null, pdfName: null, fetchedId: null });
return;
}
diff --git a/plugin/src/adapters/protocols/openai-responses/rewrite.ts b/plugin/src/adapters/protocols/openai-responses/rewrite.ts
new file mode 100644
index 0000000..f6ff068
--- /dev/null
+++ b/plugin/src/adapters/protocols/openai-responses/rewrite.ts
@@ -0,0 +1,95 @@
+// Purpose: P2 — the rewrite of a Responses request's `input` (Codex): the plan of the core (core/plan.ts) put into the
+// items. A placeholder takes the place of the image, together with Codex's `<image name=…>` and `</image>` parts around
+// an upload; a copy's note takes the image's place; a label goes right before the image (or its opening tag). Nothing
+// else changes: checked images, unknown images and all other items are forwarded as they are.
+// The notes are developer messages: the one explaining omitted images before the user message that opens the turn of
+// the first plain placeholder (placeholders are user content, which the model does not take as proof; v0.1), and v0.8's
+// feature line note before the turn of the first image, at or before the other one. Neither ever splits a tool call
+// from its output.
+// v0.10: after Codex compacted the task, the images its compaction did not keep go back right after its compaction item.
+// v0.11: split from rewrite.ts; the decisions are the core's, the words core/words.ts (docs/v0.11/plan.md).
+// Input: request items, a lookup into the thread index, the keys to leave out. Output: new items plus a metadata report.
+
+import { planRewrite, type RewriteReport } from "../../../core/plan.ts";
+import type { Lang } from "../../../core/lang.ts";
+import { autoNote, codexCompactedNote, compactList, featureNote, includedLabel, omissionNote, type Described } from "../../../core/words.ts";
+import { findImages, type ImageRef } from "./images.ts";
+
+type Json = Record<string, any>;
+
+// 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 = [codexCompactedNote(listed.length, resend.length, auto, lang), ...(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 type RewriteOptions = {
+ lang?: Lang;
+ // Copies the model fetched in an earlier turn (key → the id they copy): left out in either mode.
+ copies?: Map<string, string>;
+ // Automatic selection: the turn the request belongs to (core/plan.ts).
+ auto?: { currentTurn: number };
+ // v0.8: the feature line note and an id label on every image sent.
+ features?: boolean;
+};
+
+export function rewriteItems(
+ items: Json[],
+ describe: (ref: ImageRef) => Described | undefined,
+ unchecked: Set<string>,
+ pixelHash: (ref: ImageRef) => string | null,
+ options: Lang | RewriteOptions = "zh",
+): { items: Json[]; report: RewriteReport } {
+ const { lang = "zh", copies = new Map<string, string>(), auto, features = false }: RewriteOptions = typeof options === "string" ? { lang: options } : options;
+ const refs = findImages(items);
+ // A copy the model fetched this turn is known by the line our fetch tool writes before it.
+ const plan = planRewrite(refs, describe, unchecked, pixelHash, { lang, copies, auto, features, fetched: (ref) => !!ref.fetchedId });
+ if (!plan.changed) return { items, report: plan.report };
+
+ // Each edit puts one text part at `at`, in place of `remove` parts (none for a label).
+ const edits = new Map<number, Array<{ at: number; remove: number; text: string }>>();
+ const edit = (item: number, at: number, remove: number, text: string) => edits.set(item, [...(edits.get(item) ?? []), { at, remove, text }]);
+ for (const { slot, what, text } of plan.actions) {
+ const ref = refs[slot];
+ if (what === "placeholder") {
+ const at = ref.openTag ?? ref.part!;
+ edit(ref.item, at, (ref.closeTag ?? ref.part!) - at + 1, text);
+ } else if (what === "copy") edit(ref.item, ref.part!, 1, text);
+ else edit(ref.item, ref.openTag ?? ref.part!, 0, text);
+ }
+ const next = items.map((item, index) => {
+ const list = edits.get(index);
+ if (!list) return item;
+ const field = item.type === "message" ? "content" : "output";
+ const parts: Json[] = [...item[field]];
+ for (const { at, remove, text } of list.sort((a, b) => b.at - a.at)) parts.splice(at, remove, { type: "input_text", text });
+ return { ...item, [field]: parts };
+ });
+ const turnStart = (from: number) => {
+ let at = from;
+ while (at > 0 && !(next[at].type === "message" && next[at].role === "user")) at--;
+ return at;
+ };
+ const developer = (text: string) => ({ type: "message", role: "developer", content: [{ type: "input_text", text }] });
+ const { report } = plan;
+ const noteAt = plan.plain.length ? turnStart(refs[plan.plain[0].slot].item) : null;
+ const featureAt = plan.first !== null ? turnStart(refs[plan.first].item) : null;
+ if (noteAt !== null) next.splice(noteAt, 0, developer(auto ? autoNote(lang) : omissionNote(lang)));
+ if (featureAt !== null) {
+ next.splice(featureAt, 0, developer(featureNote(lang)));
+ report.featureAt = featureAt;
+ }
+ if (noteAt !== null) report.noteAt = noteAt + (featureAt !== null ? 1 : 0);
+ return { items: next, report };
+}
diff --git a/plugin/src/core/images.ts b/plugin/src/core/images.ts
new file mode 100644
index 0000000..9b87ccd
--- /dev/null
+++ b/plugin/src/core/images.ts
@@ -0,0 +1,61 @@
+// Purpose: what the core knows of an image whatever the platform (v0.11: split from images.ts, docs/v0.11/plan.md):
+// its kind and source, a content digest (sha256 of its base64, size from the header), the state our fetch tool writes
+// before each image it returns, and a file's base name. Finding images in a request is the request format's business
+// (adapters/protocols).
+// Input: base64 image data. Output: digests and sizes (pure, no I/O).
+
+import { createHash } from "node:crypto";
+
+export type ImageKind = "upload" | "view" | "generated" | "tool";
+// v0.2 — the source the panel filters by: the kind, except for the screenshots Codex desktop attaches to a comment on a
+// PDF page or a web page.
+export type ImageSource = ImageKind | "pdf" | "browser";
+export type ImageDigest = { contentId: string; mime: string | null; base64Chars: number; width: number | null; height: number | null };
+
+// v0.3 — the state our fetch tool (cam_view_image) writes in the line before each image it returns, in either
+// language, so the image is known as a copy of that id. The rest of the line is the usual heading (words.ts).
+export const FETCHED_STATE = { zh: "取回的原图", en: "fetched original" } as const;
+
+export function baseName(path: string): string {
+ return path.split(/[\\/]/).filter(Boolean).pop() ?? path;
+}
+
+// Width and height from the image header only, so large images are not decoded.
+export function imageSize(bytes: Buffer): { width: number; height: number } | null {
+ if (bytes.length >= 24 && bytes.readUInt32BE(0) === 0x89504e47) return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
+ if (bytes.length >= 10 && bytes.toString("ascii", 0, 3) === "GIF") return { width: bytes.readUInt16LE(6), height: bytes.readUInt16LE(8) };
+ if (bytes.length >= 30 && bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP") {
+ const chunk = bytes.toString("ascii", 12, 16);
+ if (chunk === "VP8X") return { width: bytes.readUIntLE(24, 3) + 1, height: bytes.readUIntLE(27, 3) + 1 };
+ if (chunk === "VP8 ") return { width: bytes.readUInt16LE(26) & 0x3fff, height: bytes.readUInt16LE(28) & 0x3fff };
+ if (chunk === "VP8L") { const bits = bytes.readUInt32LE(21); return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 }; }
+ return null;
+ }
+ if (bytes.length >= 4 && bytes[0] === 0xff && bytes[1] === 0xd8) {
+ let offset = 2;
+ while (offset + 9 < bytes.length) {
+ if (bytes[offset] !== 0xff) return null;
+ const marker = bytes[offset + 1];
+ if (marker === 0xff) { offset++; continue; }
+ const length = bytes.readUInt16BE(offset + 2);
+ // SOF0–SOF15 carry the frame size, except DHT (C4), JPG (C8) and DAC (CC).
+ if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) return { width: bytes.readUInt16BE(offset + 7), height: bytes.readUInt16BE(offset + 5) };
+ offset += 2 + length;
+ }
+ }
+ return null;
+}
+
+const digests = new WeakMap<object, ImageDigest>();
+
+// Keyed by the object holding the image (a request part, a record's block), so re-reading the same cached records does
+// not hash the same images again. `value` is raw base64, not a data URL.
+export function imageDigest(owner: object, value: string, mime: string | null): ImageDigest {
+ const known = digests.get(owner);
+ if (known) return known;
+ const header = Buffer.from(value.slice(0, 96 * 1024), "base64");
+ const size = imageSize(header);
+ const result = { contentId: createHash("sha256").update(value).digest("hex"), mime, base64Chars: value.length, width: size?.width ?? null, height: size?.height ?? null };
+ digests.set(owner, result);
+ return result;
+}
diff --git a/plugin/src/core/lang.ts b/plugin/src/core/lang.ts
new file mode 100644
index 0000000..98a1ffb
--- /dev/null
+++ b/plugin/src/core/lang.ts
@@ -0,0 +1,3 @@
+// Purpose: v0.11 — the two languages of the text for the model and the interface. Which one a platform uses is the
+// platform's business (language.ts for Codex, panel-language.ts for Claude Desktop's panel).
+export type Lang = "zh" | "en";
diff --git a/plugin/src/core/notes.ts b/plugin/src/core/notes.ts
index ba4acb3..b82c2b7 100644
--- a/plugin/src/core/notes.ts
+++ b/plugin/src/core/notes.ts
@@ -17,7 +17,7 @@ const RATING = /^(?:评价|rated)[ \t]*[::][ \t]*/i;
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
+// change a placeholder that went out before it, and the prompt cache from there on (anthropic-messages/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;
diff --git a/plugin/src/core/paths.ts b/plugin/src/core/paths.ts
index 9bfa6d5..aac6ed6 100644
--- a/plugin/src/core/paths.ts
+++ b/plugin/src/core/paths.ts
@@ -26,7 +26,7 @@ export const selectionDirOf = (root = dataDir()) => join(root, "selection");
// v0.4: Claude Code sessions keep their own selections and request statistics, apart from Codex's.
export const claudeSelectionDirOf = (root = dataDir()) => join(root, "claude", "selection");
export const claudeRequestStatsDirOf = (root = dataDir()) => join(root, "claude", "requests");
-// What the engine sent for each history it changed, so the thinking that still fits can stay (claude-thinking.ts).
+// What the engine sent for each history it changed, so the thinking that still fits can stay (anthropic-messages/thinking.ts).
export const claudeThinkingDirOf = (root = dataDir()) => join(root, "claude", "thinking");
export const requestStatsDirOf = (root = dataDir()) => join(root, "state", "requests");
// v0.7: each task's subagents and side chats, as the engine saw their requests (children.ts).
diff --git a/plugin/src/core/plan.ts b/plugin/src/core/plan.ts
new file mode 100644
index 0000000..a04a06a
--- /dev/null
+++ b/plugin/src/core/plan.ts
@@ -0,0 +1,101 @@
+// Purpose: v0.11 — what happens to each image of a request, whatever its format (docs/v0.11/plan.md 3.4). The rules
+// were the same in the Codex and the Claude rewrite and are kept as they were (rewrite.ts, claude-rewrite.ts before
+// v0.11): an unchecked image becomes a placeholder ("duplicate" when the same content is still sent), a copy the model
+// fetched in an earlier turn becomes a short note, and once anything is left out (v0.8: once feature lines are on)
+// every image still sent gets its id. Automatic selection (v0.3) leaves out earlier turns' images that are not pinned;
+// its placeholders point to, and its labels mark, only images of earlier turns, so a copy fetched mid-turn changes
+// nothing before it. Where the text goes in the request, and where the notes go, is the translator's business.
+// Input: the request's images in order (slots), what the index knows of each, the keys to leave out. Output: a plan.
+
+import type { ImageDigest, ImageKind } from "./images.ts";
+import type { Lang } from "./lang.ts";
+import { autoPlaceholder, copyNote, duplicatePlaceholder, includedLabel, newImageWord, plainPlaceholder, type Described } from "./words.ts";
+
+export type Replacement = { id: string; key: string; kind: ImageKind; mode: "plain" | "duplicate"; sameAs: string | null; base64Chars: number };
+// noteAt: where the note explaining omitted images was inserted, if one was. copies: the ids whose copies fetched in an
+// earlier turn were left out. v0.8: featureAt, where the feature line note went; labeled, how many images sent got
+// their id; unknown, how many images of the request the index did not know (e.g. not recorded yet). v0.10, Claude:
+// late, how many of those came after the model's latest reply.
+export type RewriteReport = { images: number; replaced: Replacement[]; locked: string[]; sentContentIds: string[]; copies: string[]; noteAt?: number; featureAt?: number; labeled?: number; unknown?: number; late?: number };
+
+// An image of the request. key: the index key it matches (null: none, e.g. pasted in this turn and not recorded yet).
+// replaceable: false for one that cannot become text (Codex's hosted generation result). name and label: the request's
+// own, used only when an omitted image points to a new one.
+export type Slot = ImageDigest & { key: string | null; kind: ImageKind; name: string | null; label: string | null; replaceable: boolean };
+
+export type PlanOptions<S extends Slot> = {
+ lang?: Lang;
+ // Copies the model fetched in an earlier turn (key → the id they copy): left out in either mode.
+ copies?: Map<string, string>;
+ // Automatic selection: the turn the request belongs to.
+ auto?: { currentTurn: number };
+ // v0.8: feature lines: the note before the first image's turn, and ids on this turn's new images too.
+ features?: boolean;
+ // A copy the model fetched in this turn, known as one (not counted as unknown).
+ fetched?: (slot: S) => boolean;
+ // v0.10, Claude: an image after the model's latest reply; an unknown one there is counted as late (the records may
+ // not have it yet).
+ late?: (slot: S) => boolean;
+};
+
+// what: a placeholder in place of the image, a copy's note in its place, or a label right before it.
+export type Action = { slot: number; what: "placeholder" | "copy" | "label"; text: string };
+// changed: false when nothing is to be done (the request goes out as it is). plain: the plain placeholders, in order,
+// for the notes that explain them. first: the first image the index knows, when feature lines are on (its turn gets the
+// feature line note). unknown: the images the index does not know.
+export type Plan = { report: RewriteReport; changed: boolean; actions: Action[]; plain: Array<{ slot: number; image: Described }>; first: number | null; unknown: number[] };
+
+export function planRewrite<S extends Slot>(
+ slots: S[],
+ describe: (slot: S) => Described | undefined,
+ leaveOut: Set<string>,
+ pixelHash: (slot: S) => string | null,
+ options: PlanOptions<S> = {},
+): Plan {
+ const { lang = "zh", copies = new Map<string, string>(), auto, features = false, fetched = () => false, late = () => false } = options;
+ const report: RewriteReport = { images: slots.length, replaced: [], locked: [], sentContentIds: [], copies: [] };
+ const copied = slots.filter((slot) => slot.key !== null && copies.has(slot.key) && slot.replaceable);
+ const drop = slots.filter((slot) => slot.key !== null && !copies.has(slot.key) && leaveOut.has(slot.key) && slot.replaceable && describe(slot));
+ for (const slot of slots) if (slot.key !== null && leaveOut.has(slot.key) && !slot.replaceable) report.locked.push(describe(slot)?.id ?? slot.key);
+ const sent = slots.filter((slot) => !drop.includes(slot) && !copied.includes(slot));
+ report.sentContentIds = sent.map((slot) => slot.contentId);
+ const unknown = slots.flatMap((slot, at) => (!copied.includes(slot) && !fetched(slot) && !describe(slot) ? [at] : []));
+ if (unknown.length) report.unknown = unknown.length;
+ const lateCount = unknown.filter((at) => late(slots[at])).length;
+ if (lateCount) report.late = lateCount;
+ const firstSlot = features ? slots.find((slot) => describe(slot)) : undefined;
+ const first = firstSlot ? slots.indexOf(firstSlot) : null;
+ const plan: Plan = { report, changed: false, actions: [], plain: [], first, unknown };
+ if (!drop.length && !copied.length && first === null) return plan;
+ plan.changed = true;
+ const earlier = (slot: S) => { const turn = describe(slot)?.turn; return auto !== undefined && turn !== null && turn !== undefined && turn < auto.currentTurn; };
+ const lasting = auto ? sent.filter(earlier) : sent;
+ const same = (a: S, b: S) => {
+ if (a.contentId === b.contentId) return true;
+ if (a.width !== b.width || a.height !== b.height) return false;
+ const pixels = pixelHash(a);
+ return pixels !== null && pixels === pixelHash(b);
+ };
+ for (const slot of drop) {
+ const image = describe(slot)!;
+ const copy = lasting.find((other) => same(other, slot));
+ const copyImage: Described | null = copy ? describe(copy) ?? { id: newImageWord(lang), name: copy.name, label: copy.label, kind: copy.kind, turn: null, width: copy.width, height: copy.height } : null;
+ const text = copyImage ? duplicatePlaceholder(image, copyImage, lang) : auto ? autoPlaceholder(image, lang) : plainPlaceholder(image, lang);
+ if (!copyImage) plan.plain.push({ slot: slots.indexOf(slot), image });
+ report.replaced.push({ id: image.id, key: slot.key!, kind: image.kind, mode: copyImage ? "duplicate" : "plain", sameAs: copyImage?.id ?? null, base64Chars: slot.base64Chars });
+ plan.actions.push({ slot: slots.indexOf(slot), what: "placeholder", text });
+ }
+ for (const slot of copied) {
+ plan.actions.push({ slot: slots.indexOf(slot), what: "copy", text: copyNote(copies.get(slot.key!)!, lang) });
+ report.copies.push(copies.get(slot.key!)!);
+ }
+ // v0.1-25: a checked image sits in its old place among placeholders, so every image still sent is marked with its id.
+ // v0.8: with feature lines, this turn's new images too.
+ for (const slot of features ? sent : lasting) {
+ const image = slot.replaceable ? describe(slot) : undefined;
+ if (!image) continue;
+ plan.actions.push({ slot: slots.indexOf(slot), what: "label", text: includedLabel(image, lang) });
+ report.labeled = (report.labeled ?? 0) + 1;
+ }
+ return plan;
+}
diff --git a/plugin/src/rewrite.ts b/plugin/src/core/words.ts
similarity index 83%
rename from plugin/src/rewrite.ts
rename to plugin/src/core/words.ts
index 67c81f0..60a42a4 100644
--- a/plugin/src/rewrite.ts
+++ b/plugin/src/core/words.ts
@@ -1,5 +1,7 @@
-// Purpose: P2 — replace the images the user unchecked with placeholder text in a Responses request's `input`.
-// Nothing else changes: checked images, unknown images and all other items are forwarded as they are.
+// Purpose: the text for the model (v0.11: moved here from rewrite.ts unchanged, docs/v0.11/plan.md): placeholders,
+// notes, labels, lists, and the words of the fetch tool, in Chinese and English. Every platform and request format
+// uses the same words; where a platform needs its own (Claude's notes after a message, Codex's compaction note), the
+// function says so. The history of each wording is in the comments next to it.
// v0.1 — placeholders say the image was seen when it appeared and is left out now by the user's choice, so the model
// keeps trusting what it said about it (user report 2026-09-25).
// v0.1-14 — in the user's language (Codex's interface language, language.ts): the Chinese wording is the one tested on
@@ -15,21 +17,15 @@
// lines in its replies (notes.ts); a placeholder carries them, so the model still tells the images apart after a
// compaction. For that a feature line note goes before the turn of the first image, and every image sent says its id,
// also the ones new in this turn. The second line of a placeholder is shorter, offsetting the added text.
-// Input: request items, a lookup into the thread index, the keys to leave out. Output: new items plus a metadata report.
+// Input: what is known of an image (Described), the language. Output: strings.
-import { FETCHED_STATE, findImages, type ImageKind, type ImageRef } from "./images.ts";
-import type { Lang } from "./language.ts";
-import type { Notes, Rating } from "./core/notes.ts";
+import { FETCHED_STATE, type ImageKind } from "./images.ts";
+import type { Lang } from "./lang.ts";
+import type { Notes, Rating } from "./notes.ts";
-type Json = Record<string, any>;
// notes (v0.8): what the model noted about the image, shown in its placeholder. awaiting (v0.10): an image of an
// interrupted turn sent once more for its feature line (thread-index.ts, awaitingLine); its label says so.
export type Described = { id: string; name: string | null; label: string | null; kind: ImageKind; turn: number | null; width: number | null; height: number | null; notes?: Notes; awaiting?: boolean };
-export type Replacement = { id: string; key: string; kind: ImageKind; mode: "plain" | "duplicate"; sameAs: string | null; base64Chars: number };
-// noteAt: where the developer message explaining omitted images was inserted, if one was. copies: the ids whose copies
-// fetched in an earlier turn were left out. v0.8: featureAt, where the feature line note went; labeled, how many
-// images sent got their id; unknown, how many images of the request the index did not know (e.g. not recorded yet).
-export type RewriteReport = { images: number; replaced: Replacement[]; locked: string[]; sentContentIds: string[]; copies: string[]; noteAt?: number; featureAt?: number; labeled?: number; unknown?: number; late?: number };
type FetchWords = { title: string; description: string; ids: string; missing: (id: string) => string; unavailable: (id: string) => string; off: string };
type Words = {
@@ -42,7 +38,7 @@ type Words = {
heading: (id: string, label: string | null, state: string, fields: string[]) => string;
plain: (id: string) => string; duplicate: (id: string, where: string) => string; note: string;
autoPlain: (id: string) => string; autoNote: string; copy: (id: string) => string; fetch: FetchWords;
- // v0.4, Claude Code only (claude-rewrite.ts): what the note adds about tool results, and the short note that follows
+ // v0.4, Claude Code only (anthropic-messages/rewrite.ts): what the note adds about tool results, and the short note that follows
// 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
@@ -315,7 +311,7 @@ export function includedLabel(image: Described, lang: Lang = "zh"): string {
// v0.3: automatic selection.
export const autoNote = (lang: Lang) => WORDS[lang].autoNote;
export const fetchWords = (lang: Lang): FetchWords => WORDS[lang].fetch;
-// v0.4: the same words for a Claude Code request (claude-rewrite.ts).
+// v0.4: the same words for a Claude Code request (anthropic-messages/rewrite.ts).
export const copyNote = (id: string, lang: Lang) => WORDS[lang].copy(id);
export const newImageWord = (lang: Lang) => WORDS[lang].newImage;
@@ -330,7 +326,7 @@ 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).
+// first, as it does after the first message holding placeholders (anthropic-messages/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 {
@@ -364,22 +360,8 @@ export function compactList(images: Listed[], lang: Lang = "zh"): string {
return [WORDS[lang].compactHeader(images.length), ...images.map((image, at) => compactLine(image, lang, sameAs(image, at)))].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 };
-}
+// v0.10, Codex: the note before the images its compaction did not keep (addCodexCompacted).
+export const codexCompactedNote = (count: number, resent: number, auto: boolean, lang: Lang) => WORDS[lang].codexCompacted(count, resent, auto);
export function autoPlaceholder(image: Described, lang: Lang = "zh"): string {
const words = WORDS[lang];
@@ -394,99 +376,3 @@ export const featureNote = (lang: Lang) => WORDS[lang].featureNote;
export function fetchedLabel(image: Described, lang: Lang = "zh"): string {
return heading(WORDS[lang], { ...image, label: null }, FETCHED_STATE[lang]);
}
-
-export type RewriteOptions = {
- lang?: Lang;
- // Copies the model fetched in an earlier turn (key → the id they copy): left out in either mode.
- copies?: Map<string, string>;
- // Automatic selection: its wording; and a placeholder points to, and a label marks, only images of earlier turns
- // (the pinned ones), which stay sent through the turn, so a copy fetched mid-turn changes nothing before it.
- auto?: { currentTurn: number };
- // v0.8: the feature line note before the turn of the first image, and an id label on every image sent, also the ones
- // new in this turn (the model notes them by id). A duplicate placeholder still points only to earlier turns' images.
- features?: boolean;
-};
-
-export function rewriteItems(
- items: Json[],
- describe: (ref: ImageRef) => Described | undefined,
- unchecked: Set<string>,
- pixelHash: (ref: ImageRef) => string | null,
- options: Lang | RewriteOptions = "zh",
-): { items: Json[]; report: RewriteReport } {
- const { lang = "zh", copies = new Map<string, string>(), auto, features = false }: RewriteOptions = typeof options === "string" ? { lang: options } : options;
- const refs = findImages(items);
- const report: RewriteReport = { images: refs.length, replaced: [], locked: [], sentContentIds: [], copies: [] };
- const copied = refs.filter((ref) => copies.has(ref.key) && ref.part !== null);
- const drop = refs.filter((ref) => !copies.has(ref.key) && unchecked.has(ref.key) && ref.replaceable && describe(ref));
- for (const ref of refs) if (unchecked.has(ref.key) && !ref.replaceable) report.locked.push(describe(ref)?.id ?? ref.key);
- const sent = refs.filter((ref) => !drop.includes(ref) && !copied.includes(ref));
- report.sentContentIds = sent.map((ref) => ref.contentId);
- // A copy the model fetched this turn is known as one (the line our fetch tool writes before it), not as an image.
- const unknown = refs.filter((ref) => !copied.includes(ref) && !ref.fetchedId && !describe(ref)).length;
- if (unknown) report.unknown = unknown;
- // v0.8: the first image the index knows; the feature line note goes before its turn.
- const first = features ? refs.find((ref) => describe(ref)) : undefined;
- if (!drop.length && !copied.length && !first) return { items, report };
- const earlier = (ref: ImageRef) => { const turn = describe(ref)?.turn; return auto !== undefined && turn !== null && turn !== undefined && turn < auto.currentTurn; };
- const lasting = auto ? sent.filter(earlier) : sent;
-
- const same = (a: ImageRef, b: ImageRef) => {
- if (a.contentId === b.contentId) return true;
- if (a.width !== b.width || a.height !== b.height) return false;
- const pixels = pixelHash(a);
- return pixels !== null && pixels === pixelHash(b);
- };
- // Each edit puts one text part at `at`, in place of `remove` parts (none for a label).
- const edits = new Map<number, Array<{ at: number; remove: number; text: string }>>();
- const edit = (item: number, at: number, remove: number, text: string) => edits.set(item, [...(edits.get(item) ?? []), { at, remove, text }]);
- let firstPlain: number | null = null;
- for (const ref of drop) {
- const image = describe(ref)!;
- const copy = lasting.find((other) => same(other, ref));
- const copyImage = copy ? describe(copy) ?? { id: WORDS[lang].newImage, name: copy.name, label: copy.label, kind: copy.kind, turn: null, width: copy.width, height: copy.height } : null;
- const text = copyImage ? duplicatePlaceholder(image, copyImage, lang) : auto ? autoPlaceholder(image, lang) : plainPlaceholder(image, lang);
- if (!copyImage && firstPlain === null) firstPlain = ref.item;
- report.replaced.push({ id: image.id, key: ref.key, kind: ref.kind, mode: copyImage ? "duplicate" : "plain", sameAs: copyImage?.id ?? null, base64Chars: ref.base64Chars });
- const at = ref.openTag ?? ref.part!;
- edit(ref.item, at, (ref.closeTag ?? ref.part!) - at + 1, text);
- }
- for (const ref of copied) {
- edit(ref.item, ref.part!, 1, WORDS[lang].copy(copies.get(ref.key)!));
- report.copies.push(copies.get(ref.key)!);
- }
- // v0.1-25: a checked image sits in its old place among placeholders, so every image still sent is marked with its id.
- // v0.8: with feature lines, this turn's new images too.
- for (const ref of features ? sent : lasting) {
- const image = ref.replaceable && ref.part !== null ? describe(ref) : undefined;
- if (!image) continue;
- edit(ref.item, ref.openTag ?? ref.part!, 0, includedLabel(image, lang));
- report.labeled = (report.labeled ?? 0) + 1;
- }
- const next = items.map((item, index) => {
- const list = edits.get(index);
- if (!list) return item;
- const field = item.type === "message" ? "content" : "output";
- const parts: Json[] = [...item[field]];
- for (const { at, remove, text } of list.sort((a, b) => b.at - a.at)) parts.splice(at, remove, { type: "input_text", text });
- return { ...item, [field]: parts };
- });
- // Only plain placeholders need the note (a duplicate's content is still in view). It goes before the user message
- // that opens that turn, so it never splits a tool call from its output. v0.8: the feature line note likewise, before
- // the turn of the first image: at or before the other one (the first image comes no later than the first omitted).
- const turnStart = (from: number) => {
- let at = from;
- while (at > 0 && !(next[at].type === "message" && next[at].role === "user")) at--;
- return at;
- };
- const developer = (text: string) => ({ type: "message", role: "developer", content: [{ type: "input_text", text }] });
- const noteAt = firstPlain !== null ? turnStart(firstPlain) : null;
- const featureAt = first ? turnStart(first.item) : null;
- if (noteAt !== null) next.splice(noteAt, 0, developer(auto ? WORDS[lang].autoNote : WORDS[lang].note));
- if (featureAt !== null) {
- next.splice(featureAt, 0, developer(WORDS[lang].featureNote));
- report.featureAt = featureAt;
- }
- if (noteAt !== null) report.noteAt = noteAt + (featureAt !== null ? 1 : 0);
- return { items: next, report };
-}
diff --git a/plugin/src/language.ts b/plugin/src/language.ts
index 731a764..df3136d 100644
--- a/plugin/src/language.ts
+++ b/plugin/src/language.ts
@@ -16,7 +16,8 @@ import { dirname, join } from "node:path";
import { codexHome } from "./adapters/codex/codexconfig.ts";
import { dataDir } from "./core/paths.ts";
-export type Lang = "zh" | "en";
+import type { Lang } from "./core/lang.ts";
+export type { Lang };
// codex: the panel got Codex's interface language; system: it only had the system's.
export type LangSource = "codex" | "system";
// codexLocale: Codex's language setting when the panel reported (absent in records from before v0.1-20).
diff --git a/plugin/src/messages.ts b/plugin/src/messages.ts
index 3afe4ad..a0746f4 100644
--- a/plugin/src/messages.ts
+++ b/plugin/src/messages.ts
@@ -1,6 +1,6 @@
// Purpose: v0.1-14 — the plugin's own words in Simplified Chinese and English: Codex's tool list and the panel's tab
// title, results and refusals of the panel's calls, conflicts with the user's settings, and the command line. The
-// panel page keeps its texts in panel.html, and the text for the model is in rewrite.ts. Every key exists in both
+// panel page keeps its texts in panel.html, and the text for the model is in core/words.ts. Every key exists in both
// languages (a unit test checks it), so changing a text means changing both.
// Input: a language and a key, with {name} values filled in. Output: strings.
diff --git a/plugin/src/panel/panel-state.ts b/plugin/src/panel/panel-state.ts
index a8b1bd4..b89a195 100644
--- a/plugin/src/panel/panel-state.ts
+++ b/plugin/src/panel/panel-state.ts
@@ -15,7 +15,7 @@
import { readChildren } from "../children.ts";
import { claudeHome, claudeImageData, claudeStartedAt, isPrompt, loadClaudeIndex, type ClaudeIndex, type ClaudeRecord } from "../adapters/claude/claude-index.ts";
-import type { ImageSource } from "../images.ts";
+import type { ImageSource } from "../core/images.ts";
import { sceneOf, withoutRecords } from "../core/notes.ts";
import { childrenDirOf, claudeRequestStatsDirOf, claudeSelectionDirOf, dataDir, requestStatsDirOf, selectionDirOf } from "../core/paths.ts";
import { readRequestStats, type RequestStats } from "../core/request-stats.ts";
@@ -49,8 +49,8 @@ export type SendInfo = {
// What the engine sent for that request; resent: images from before a compaction it sent again (v0.5).
last: { at: string; bytesBefore: number; bytesAfter: number; replaced: number; resent: number; skipped: boolean } | null;
// v0.4: "fallback": Anthropic refused the rewritten history under its thinking, so the engine sent the original
- // (claude-rewrite.ts): what the user unchecked went out that time. "thinking": the account checks thinking, and the
- // engine left out `count` thinking records that no longer fit the history as sent (claude-thinking.ts); the model may
+ // (anthropic-messages/rewrite.ts): what the user unchecked went out that time. "thinking": the account checks thinking, and the
+ // engine left out `count` thinking records that no longer fit the history as sent (anthropic-messages/thinking.ts); the model may
// think again.
notice: { kind: "skipped"; at: string; reason: SkipReason } | { kind: "websocket"; at: string } | { kind: "fallback"; at: string } | { kind: "thinking"; at: string; count: number } | null;
};
diff --git a/plugin/src/plugin-server.ts b/plugin/src/plugin-server.ts
index 4d1a52c..a3eb200 100644
--- a/plugin/src/plugin-server.ts
+++ b/plugin/src/plugin-server.ts
@@ -12,7 +12,7 @@
// v0.1-14 — the panel reports Codex's interface language with its calls; it is remembered (language.ts), and the tool
// list (the tab's title), results and refusals speak it (messages.ts). v0.1-20 — Codex's language setting counts too.
// v0.3 — cam_view_image, the one tool for the model: in a thread with automatic selection on, it returns the originals
-// of images by id, each after a line naming it (rewrite.ts), so the index knows them as copies. Codex's code mode does
+// of images by id, each after a line naming it (core/words.ts), so the index knows them as copies. Codex's code mode does
// not list plugin tools to the model; the model learns its name from the context note and looks it up.
// v0.4 — the same service under Claude Code (CAM_HOST=claude, set by the Claude plugin's manifest): it keeps the same
// engine running, and serves the Claude plugin's mod (its panel and its routing, hooks/register.js) and the model's
@@ -37,7 +37,7 @@ import { say } from "./messages.ts";
import { migrateDataOnce } from "./core/migrate-data.ts";
import { applySelection, claudeImageFor, imageFor, loadPanelState, type ClaudePanelOptions, type PanelState } from "./panel/panel-state.ts";
import { claudeSelectionDirOf, dataDir, pixelCacheDirOf, selectionDirOf } from "./core/paths.ts";
-import { fetchedLabel, fetchWords } from "./rewrite.ts";
+import { fetchedLabel, fetchWords } from "./core/words.ts";
import { claudeSelection, effectiveSelection, ensureAutoDefault, ensureStableIds, stableIdsSince } from "./selection.ts";
import { connectDirectly, useEngine, usesEngine } from "./adapters/codex/setup.ts";
import { hasRollout, loadThreadIndex, readThreadHistory, sessionMetaOf, setPixelCache, sideChatOrigin } from "./adapters/codex/thread-index.ts";
@@ -92,7 +92,7 @@ export function toolsFor(lang: Lang) {
inputSchema: { type: "object", properties: { ...shared, target: { type: "string" } }, required: ["target"] },
_meta: APP_ONLY,
},
- // For the model (no app-only visibility); its words are text for the model, so they live in rewrite.ts.
+ // For the model (no app-only visibility); its words are text for the model, so they live in core/words.ts.
{
name: "cam_view_image",
title: fetchWords(lang).title,
diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.ts
index 1dfc1b2..69b821c 100644
--- a/plugin/src/proxy.ts
+++ b/plugin/src/proxy.ts
@@ -29,12 +29,13 @@ import { fileURLToPath } from "node:url";
import zlib from "node:zlib";
import { childOf, recordChild } from "./children.ts";
import { claudeHome, claudeImageData, claudeStartedAt, loadClaudeIndex, type ClaudeIndex } from "./adapters/claude/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 { addCompacted, summaryAt, type RequestImage, type Resend } from "./adapters/protocols/anthropic-messages/rewrite.ts";
+import { findRequestImages, rewriteMessages } from "./adapters/claude/claude-rewrite.ts";
+import { keepCacheRead, marksOutside, REMEMBERED, sentPrefixOf, type SentPrefix } from "./adapters/protocols/anthropic-messages/cache.ts";
+import { chainOf, fitThinking, readThinkingRecord, recordSent, writeThinkingRecord, type ThinkingRecord } from "./adapters/protocols/anthropic-messages/thinking.ts";
import { codexHome } from "./adapters/codex/codexconfig.ts";
import { buildOf, DEFAULT_PORT, ENGINE_SERVICE, engineHealth, versionOf, watchForCodex } from "./engine.ts";
-import { findImages, type ImageRef } from "./images.ts";
+import { findImages, type ImageRef } from "./adapters/protocols/openai-responses/images.ts";
import { isEntryPoint } from "./core/entry.ts";
import { currentLang } from "./language.ts";
import { migrateDataOnce } from "./core/migrate-data.ts";
@@ -44,7 +45,8 @@ import { applyClaudeSelection, claudeImageFor, loadClaudePanelState, type Claude
import { claudeRequestStatsDirOf, claudeSelectionDirOf, dataDir, pixelCacheDirOf, proxyLogDirOf, selectionDirOf } from "./core/paths.ts";
import { recordRequest } from "./core/request-stats.ts";
import { readRoute, registerRoute, routeBaseUrl, routingPort, validateBaseUrl, type Platform } from "./core/routes.ts";
-import { addCodexCompacted, rewriteItems, type Described } from "./rewrite.ts";
+import { addCodexCompacted, rewriteItems } from "./adapters/protocols/openai-responses/rewrite.ts";
+import type { Described } from "./core/words.ts";
import { connectDirectly, pluginGone, usesEngine } from "./adapters/codex/setup.ts";
import { claudeSelection, effectiveSelection, ensureAutoDefault, ensureStableIds, selectionDir, sideChatSelection, stableIdsSince } from "./selection.ts";
import { awaitingLine, imageData, loadThreadIndex, pixelHashOf, pixelHashOfData, setPixelCache, sideChatOrigin, writesNotes, type ThreadIndex } from "./adapters/codex/thread-index.ts";
@@ -420,11 +422,11 @@ export function thinkingRejected(status: number, body: string): boolean {
// v0.4: what to send for a Claude Code request, each next one when Anthropic refuses the thinking after the changed
// history (thinkingRejected): the rewrite with all its thinking (an account that lets it through); the rewrite without
-// the thinking that no longer fits (claude-thinking.ts), first once the account is known to refuse it; the rewrite
+// the thinking that no longer fits (anthropic-messages/thinking.ts), first once the account is known to refuse it; the rewrite
// 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.
-// prefix: where its cache marks are, to remember once it is sent (claude-cache.ts).
+// prefix: where its cache marks are, to remember once it is sent (anthropic-messages/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
@@ -432,7 +434,7 @@ export type ClaudeAttempt = { body: Buffer; report: Json; history: string | null
const LATE_WAIT_MS = 1500;
const LATE_STEP_MS = 100;
-// v0.4: the same rules as rewriteBody, for a Claude Code request (Anthropic Messages, claude-rewrite.ts). The current
+// v0.4: the same rules as rewriteBody, for a Claude Code request (Anthropic Messages, anthropic-messages/rewrite.ts). The current
// 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.
@@ -459,7 +461,7 @@ export function rewriteClaudeBody(original: Buffer, encoding: string | undefined
}
const pixels = (ref: RequestImage) => (ref.key ? index.byKey.get(ref.key)?.pixelSha256 : undefined) ?? pixelHashOfData(ref, ref.block.source.data);
const lang = currentLang();
- // v0.5: after a compaction, the images from before it go back right after the summary (claude-rewrite.ts): the ones
+ // v0.5: after a compaction, the images from before it go back right after the summary (anthropic-messages/rewrite.ts): the ones
// the user keeps sending (checked, or pinned with automatic selection) read from the transcript, the others as
// 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.
@@ -515,7 +517,7 @@ export function rewriteClaudeBody(original: Buffer, encoding: string | undefined
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
+ // one after the images still sent as originals are left out (anthropic-messages/cache.ts): with automatic selection, the first
// such image that is not pinned.
const pinnedNow = selection.pinned ?? {};
const volatileIn = (list: Json[]) => {
@@ -639,7 +641,7 @@ async function main(): Promise<void> {
} catch { /* only the panel's list misses it */ }
};
// v0.4: per Claude Code session, whether its account refuses thinking after a changed history and what was sent
- // (claude-thinking.ts); the latest sessions stay in memory.
+ // (anthropic-messages/thinking.ts); the latest sessions stay in memory.
const thinkingRecords = new Map<string, ThinkingRecord>();
const thinkingOf = (sessionId: string): ThinkingRecord => {
const record = thinkingRecords.get(sessionId) ?? readThinkingRecord(sessionId);
@@ -649,7 +651,7 @@ async function main(): Promise<void> {
return record;
};
// v0.10: per session, where the conversation requests sent last had their cache marks, newest first
- // (claude-cache.ts); memory only.
+ // (anthropic-messages/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);
@@ -955,7 +957,7 @@ async function main(): Promise<void> {
catch (error) { return { body: original, report: { skipped: `rewrite failed: ${String(error)}` } }; }
};
let out = rewriteNow();
- // v0.10: the newest images not in the transcript yet (claude-rewrite.ts, late): read it again for a moment, so
+ // v0.10: the newest images not in the transcript yet (core/plan.ts, late): read it again for a moment, so
// they go out with their ids now and the model can note them in this reply.
let waited = 0;
for (; claudeRewrite && out.report?.late && waited < LATE_WAIT_MS; waited += LATE_STEP_MS) { await sleep(LATE_STEP_MS); out = rewriteNow(); }
diff --git a/spike/src/claude-cache.test.ts b/spike/src/claude-cache.test.ts
index ba6802f..d272423 100644
--- a/spike/src/claude-cache.test.ts
+++ b/spike/src/claude-cache.test.ts
@@ -1,10 +1,10 @@
// 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
+// ones before it wrote after the engine changed the history (anthropic-messages/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";
+import { keepCacheRead, marksOutside, sentPrefixOf } from "../../plugin/src/adapters/protocols/anthropic-messages/cache.ts";
const mark = { type: "ephemeral", ttl: "1h" };
const text = (value: string, marked = false) => ({ type: "text", text: value, ...(marked ? { cache_control: mark } : {}) });
diff --git a/spike/src/claude-rewrite.test.ts b/spike/src/claude-rewrite.test.ts
index defa124..fa7c4a8 100644
--- a/spike/src/claude-rewrite.test.ts
+++ b/spike/src/claude-rewrite.test.ts
@@ -8,8 +8,9 @@
import assert from "node:assert/strict";
import test from "node:test";
import { buildClaudeIndex } from "../../plugin/src/adapters/claude/claude-index.ts";
-import { addCompacted, findRequestImages, rewriteMessages, summaryAt } from "../../plugin/src/claude-rewrite.ts";
-import { autoPlaceholder, claudeNote, compactedNote, compactLine, compactList, hereNote, includedLabel, plainPlaceholder } from "../../plugin/src/rewrite.ts";
+import { addCompacted, summaryAt } from "../../plugin/src/adapters/protocols/anthropic-messages/rewrite.ts";
+import { findRequestImages, rewriteMessages } from "../../plugin/src/adapters/claude/claude-rewrite.ts";
+import { autoPlaceholder, claudeNote, compactedNote, compactLine, compactList, hereNote, includedLabel, plainPlaceholder } from "../../plugin/src/core/words.ts";
import { image, pngA, pngB, pngC, text, transcript, usualRequest, usualSession } from "./claude-fixtures.ts";
const noPixels = () => null;
diff --git a/spike/src/claude-thinking.test.ts b/spike/src/claude-thinking.test.ts
index 4e89ee1..78e39a2 100644
--- a/spike/src/claude-thinking.test.ts
+++ b/spike/src/claude-thinking.test.ts
@@ -1,4 +1,4 @@
-// Purpose: v0.4 — claude-thinking.ts: which thinking still fits after the engine changed the history before it, and
+// Purpose: v0.4 — anthropic-messages/thinking.ts: which thinking still fits after the engine changed the history before it, and
// the per-session record of what the engine sent. Input: synthetic message lists and a temporary folder; output: Node
// test assertions only.
@@ -7,7 +7,7 @@ import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
-import { chainOf, fitThinking, newThinkingRecord, readThinkingRecord, recordSent, rememberSent, writeThinkingRecord } from "../../plugin/src/claude-thinking.ts";
+import { chainOf, fitThinking, newThinkingRecord, readThinkingRecord, recordSent, rememberSent, writeThinkingRecord } from "../../plugin/src/adapters/protocols/anthropic-messages/thinking.ts";
type Json = Record<string, any>;
const think = (signature: string) => ({ type: "thinking", thinking: "", signature });
diff --git a/spike/src/codex-compaction.test.ts b/spike/src/codex-compaction.test.ts
index 9d220ed..29bf6fc 100644
--- a/spike/src/codex-compaction.test.ts
+++ b/spike/src/codex-compaction.test.ts
@@ -11,7 +11,8 @@ 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 { addCodexCompacted } from "../../plugin/src/adapters/protocols/openai-responses/rewrite.ts";
+import { compactList } from "../../plugin/src/core/words.ts";
import { writeSelection } from "../../plugin/src/selection.ts";
import { loadThreadIndex } from "../../plugin/src/adapters/codex/thread-index.ts";
import { png } from "./testkit.ts";
diff --git a/spike/src/feature-backfill.test.ts b/spike/src/feature-backfill.test.ts
index 7e024dc..580836a 100644
--- a/spike/src/feature-backfill.test.ts
+++ b/spike/src/feature-backfill.test.ts
@@ -11,7 +11,7 @@ import test from "node:test";
import zlib from "node:zlib";
import { buildClaudeIndex } from "../../plugin/src/adapters/claude/claude-index.ts";
import { rewriteBody, rewriteClaudeBody } from "../../plugin/src/proxy.ts";
-import { featureNote } from "../../plugin/src/rewrite.ts";
+import { featureNote } from "../../plugin/src/core/words.ts";
import { writeSelection } from "../../plugin/src/selection.ts";
import { awaitingLine, loadThreadIndex } from "../../plugin/src/adapters/codex/thread-index.ts";
import { image, pngA, pngB, text, transcript } from "./claude-fixtures.ts";
diff --git a/spike/src/images.test.ts b/spike/src/images.test.ts
index f5523cc..100e9ee 100644
--- a/spike/src/images.test.ts
+++ b/spike/src/images.test.ts
@@ -3,7 +3,8 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { findImages, imageSize } from "../../plugin/src/images.ts";
+import { findImages } from "../../plugin/src/adapters/protocols/openai-responses/images.ts";
+import { imageSize } from "../../plugin/src/core/images.ts";
import { png } from "./testkit.ts";
const url = (bytes: Buffer) => `data:image/png;base64,${bytes.toString("base64")}`;
diff --git a/spike/src/language.test.ts b/spike/src/language.test.ts
index a85cc80..f4e8540 100644
--- a/spike/src/language.test.ts
+++ b/spike/src/language.test.ts
@@ -12,7 +12,8 @@ import { fileURLToPath } from "node:url";
import { codexUiLocale, currentLang, langOf, rememberLang, storedLang, systemLang } from "../../plugin/src/language.ts";
import { MESSAGES, say } from "../../plugin/src/messages.ts";
import { callTool, toolsFor } from "../../plugin/src/plugin-server.ts";
-import { OMISSION_NOTE, omissionNote, rewriteItems, type Described } from "../../plugin/src/rewrite.ts";
+import { OMISSION_NOTE, omissionNote, type Described } from "../../plugin/src/core/words.ts";
+import { rewriteItems } from "../../plugin/src/adapters/protocols/openai-responses/rewrite.ts";
import { sampleSessions } from "./testfixtures.ts";
const here = dirname(fileURLToPath(import.meta.url));
diff --git a/spike/src/layers.test.ts b/spike/src/layers.test.ts
index 39ebc92..a929d04 100644
--- a/spike/src/layers.test.ts
+++ b/spike/src/layers.test.ts
@@ -15,15 +15,12 @@ const src = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "plugin",
const PENDING = new Set<string>([
"adapters/claude/claude-index.ts -> adapters/codex/thread-index.ts",
- "adapters/claude/claude-index.ts -> images.ts",
"adapters/codex/install.ts -> language.ts",
"adapters/codex/install.ts -> messages.ts",
- "adapters/codex/thread-index.ts -> images.ts",
"panel/panel-state.ts -> adapters/claude/claude-index.ts",
"panel/panel-state.ts -> adapters/codex/thread-index.ts",
"panel/panel-state.ts -> adapters/codex/thread-names.ts",
"panel/panel-state.ts -> children.ts",
- "panel/panel-state.ts -> images.ts",
"panel/panel-state.ts -> selection.ts",
]);
diff --git a/spike/src/notes.test.ts b/spike/src/notes.test.ts
index bc81a16..dd64287 100644
--- a/spike/src/notes.test.ts
+++ b/spike/src/notes.test.ts
@@ -8,10 +8,11 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import { buildClaudeIndex } from "../../plugin/src/adapters/claude/claude-index.ts";
-import { rewriteMessages } from "../../plugin/src/claude-rewrite.ts";
-import { findImages, type ImageRef } from "../../plugin/src/images.ts";
+import { rewriteMessages } from "../../plugin/src/adapters/claude/claude-rewrite.ts";
+import { findImages, type ImageRef } from "../../plugin/src/adapters/protocols/openai-responses/images.ts";
import { addNotes, notesBy, sceneOf, type Notes } from "../../plugin/src/core/notes.ts";
-import { autoPlaceholder, clip, featureNote, plainPlaceholder, rewriteItems, type Described } from "../../plugin/src/rewrite.ts";
+import { autoPlaceholder, clip, featureNote, plainPlaceholder, type Described } from "../../plugin/src/core/words.ts";
+import { rewriteItems } from "../../plugin/src/adapters/protocols/openai-responses/rewrite.ts";
import { buildIndex, writesNotes, type Parsed } from "../../plugin/src/adapters/codex/thread-index.ts";
import { claudeTurnTexts, loadPanelState, panelStateOf } from "../../plugin/src/panel/panel-state.ts";
import { image, pngA, pngB, text, transcript } from "./claude-fixtures.ts";
@@ -161,7 +162,7 @@ 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).
+// v0.10: a placeholder or the list after a compaction changing later rewrote the prompt cache from there (anthropic-messages/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);
diff --git a/spike/src/proxy.test.ts b/spike/src/proxy.test.ts
index 5a67a5a..28a8c48 100644
--- a/spike/src/proxy.test.ts
+++ b/spike/src/proxy.test.ts
@@ -318,7 +318,7 @@ test("a Claude Code request is rewritten from the session's transcript and selec
test("an account that refuses thinking after an edited history gets the rewrite without the thinking that no longer fits", async () => {
const { usualSession, usualRequest, text } = await import("./claude-fixtures.ts");
const { rewriteClaudeBody } = await import("../../plugin/src/proxy.ts");
- const { newThinkingRecord, recordSent } = await import("../../plugin/src/claude-thinking.ts");
+ const { newThinkingRecord, recordSent } = await import("../../plugin/src/adapters/protocols/anthropic-messages/thinking.ts");
const home = mkdtempSync(join(tmpdir(), "cam-claude-home-"));
const dir = mkdtempSync(join(tmpdir(), "cam-claude-sel-"));
const session = "11111111-2222-4333-8444-555555555555";
diff --git a/spike/src/rewrite-golden.test.ts b/spike/src/rewrite-golden.test.ts
index f124eed..75528d0 100644
--- a/spike/src/rewrite-golden.test.ts
+++ b/spike/src/rewrite-golden.test.ts
@@ -9,9 +9,11 @@ import { createHash } from "node:crypto";
import { readFileSync, writeFileSync } from "node:fs";
import test from "node:test";
import { buildClaudeIndex } from "../../plugin/src/adapters/claude/claude-index.ts";
-import { addCompacted, rewriteMessages } from "../../plugin/src/claude-rewrite.ts";
-import { findImages, type ImageRef } from "../../plugin/src/images.ts";
-import { addCodexCompacted, rewriteItems, type Described } from "../../plugin/src/rewrite.ts";
+import { addCompacted } from "../../plugin/src/adapters/protocols/anthropic-messages/rewrite.ts";
+import { rewriteMessages } from "../../plugin/src/adapters/claude/claude-rewrite.ts";
+import { findImages, type ImageRef } from "../../plugin/src/adapters/protocols/openai-responses/images.ts";
+import { addCodexCompacted, rewriteItems } from "../../plugin/src/adapters/protocols/openai-responses/rewrite.ts";
+import type { Described } from "../../plugin/src/core/words.ts";
import { image, pngA, pngB, pngC, text, transcript, usualRequest } from "./claude-fixtures.ts";
import { png } from "./testkit.ts";
diff --git a/spike/src/rewrite.test.ts b/spike/src/rewrite.test.ts
index 6438dd2..28ce8b6 100644
--- a/spike/src/rewrite.test.ts
+++ b/spike/src/rewrite.test.ts
@@ -6,8 +6,9 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { findImages, type ImageRef } from "../../plugin/src/images.ts";
-import { autoNote, autoPlaceholder, fetchedLabel, OMISSION_NOTE, omissionNote, rewriteItems, type Described } from "../../plugin/src/rewrite.ts";
+import { findImages, type ImageRef } from "../../plugin/src/adapters/protocols/openai-responses/images.ts";
+import { autoNote, autoPlaceholder, fetchedLabel, OMISSION_NOTE, omissionNote, type Described } from "../../plugin/src/core/words.ts";
+import { rewriteItems } from "../../plugin/src/adapters/protocols/openai-responses/rewrite.ts";
import { png } from "./testkit.ts";
const url = (bytes: Buffer) => `data:image/png;base64,${bytes.toString("base64")}`;