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.

eval: scripts for a long task in Claude Code, compacted twice and forked

chipfighter4f39d076f6f9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index df28573..3e425b4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -29,7 +29,7 @@ Earlier images come back after compaction and resume, with the same IDs, in Code
- After updating, reopen Claude sessions that were open: their image tool still runs the earlier code and numbering until then.
- Earlier transcripts are read only up to the compaction, and their image data stays on disk until needed: for the longest real session tested (9 transcripts, 210 images), the engine uses about 60 MB more memory and the first index takes under 2 seconds.
-- Verified so far with 285 unit tests, read-only replays of real Codex and Claude sessions, a live test in Claude Desktop (a compaction, a restart of the session, and an edited earlier message that moved the session to a new transcript), and a long real session replayed turn by turn into a test session with two compactions, where the model picked the right image for all 12 questions asked after them. The model self-tests are still to run.
+- Verified so far with 289 unit tests, read-only replays of real Codex and Claude sessions, a live test in Claude Desktop (a compaction, a restart of the session, and an edited earlier message that moved the session to a new transcript), and a long real session replayed turn by turn into a test session with two compactions, where the model picked the right image for all 12 questions asked after them. The model self-tests are still to run.
## [0.9.1] - 2026-10-29
diff --git a/docs/v0.10/plan.md b/docs/v0.10/plan.md
index a596ee4..bdbf451 100644
--- a/docs/v0.10/plan.md
+++ b/docs/v0.10/plan.md
@@ -1,6 +1,6 @@
# v0.10 方案:压缩和续接之后,照样拿回之前的图
-> 状态:用户 2026-10-31 确认方案,让 Claude 按自己的安排做完(第 8 节)。代码和单元测试已完成,spec 和 design 已改;关卡 1–4 用本机回放验证通过,关卡 6 的大会话只有估算(系数按桌面实测校准过),关卡 5、7 的模型自测因为 Codex 用量到了上限没跑成;Claude 桌面实测(压缩、重启、改消息分叉)和长会话回放(关卡 8)已通过,回放发现的三处(第 2 节第 9 到 11 条)已修。这几项通过之前不发布。起因是用 5 个真实会话评估图片检索(会话内容只在本机,不进仓库)。规格以 [spec.md](../spec.md) 为准,实现见 [design.md](../design.md)。
+> 状态:用户 2026-10-31 确认方案,让 Claude 按自己的安排做完(第 8 节)。代码和单元测试已完成,spec 和 design 已改;关卡 1–4 用本机回放验证通过,关卡 6 的大会话只有估算(系数按桌面实测校准过),关卡 5、7 的模型自测因为 Codex 用量到了上限没跑成;Claude 桌面实测(压缩、重启、改消息分叉)和长会话回放(关卡 8)已通过,回放发现的三处(第 2 节第 9 到 11 条)已修。公开评测(第 6 节)2026-11-01 跑过一次,评测里又发现并修了两处(第 2 节第 12、13 条);报告先留在本机,等 Claude 会话的提示缓存命中问题改好、重跑之后再发布(第 8 节第 7 条)。这几项通过之前不发布。起因是用 5 个真实会话评估图片检索(会话内容只在本机,不进仓库)。规格以 [spec.md](../spec.md) 为准,实现见 [design.md](../design.md)。
## 1. 背景与目标
@@ -62,6 +62,8 @@
9. **并行读图乱序时照样编号**(插件 bug,v0.4 起就有):模型同时读几张图、结果回来的顺序乱了时,对话会从前面某个调用的结果接着走,后面的调用记录不在对话链上,插件认不出它们的图。这些图没有编号,每轮照发原图,压缩后丢失,也取不回。改成:同一次回复的几次调用带同一个消息 id,不在链上的也接回来,图按调用顺序编号。补上编号后,排在它后面的图编号后移,修复之前写下的记录行按当时的编号换算(第 3 条的做法,旧编号跳过这些图);编号规则的版本记在 `stable-ids.json` 里,规则变了,第一次运行的时间重新记。
10. **评价和特征行一样长**:评价原来截到 15 个汉字,长会话测试里一条 18 个字的评价在清单里只剩前半句,压缩后模型看不到后半句说的问题。评价是用户的原话,一个会话没几条,上限改成和特征行一样,30 个汉字或 100 个字母。
11. **清单里标出同一张图**:用户重发同一张图时,插件已经认得出是同一张,但清单列成两行、各写各的特征。改成后面那行写“同 IMG-108”,不再重复特征。
+12. **等记录文件写完再改写**(公开评测试跑时发现):Claude Code 有时在把这一轮刚读的图写进记录文件之前就发出请求,插件认不出这几张图,原样发出、不带编号,模型这一轮没法给它们写特征行(试跑里一轮 3 张;用户本机日志 8904 次请求里有 119 次,下一次请求才认出)。改成:请求里模型最近一次回复之后有认不出的图时,引擎每 100 毫秒重读一次记录文件,最多 1.5 秒;认出了就照常改写。一张一直认不出的图只让一次请求多等这一下。
+13. **压缩后照常看新图**(公开评测发现):说明里“不要用其他工具去读取图片文件”本意是被省略的图要用 `cam_view_image` 取。评测第一次跑 0.10 时(Haiku 5.5,推理强度 low),压缩后模型把它当成所有图,用户后面 5 轮让它看的图一张都没读。改成只说被省略的(Codex 的压缩说明里是清单里的)图,并写明用户新让它看的图照常去看;重跑后每轮都照常读图。这是发给模型的措辞,按 AGENTS.md 要跑 Codex 的 `v01-placeholder`、`v01-needs`、`v03-auto` 自测。
## 3. 要先验证的事(关卡)
@@ -119,12 +121,16 @@
## 6. 公开评测(用户 2026-10-31 提议)
-修完以后,在 `eval/` 加一个长任务的评测。现有的关键帧评测只有 9 张图、Codex 一个平台,它的“局限”一节里写着长任务没测,这次补上。用合成的会话和图片,谁都能复现,不用用户的真实会话。
+修完以后,在 `eval/` 加一个长任务的评测。现有的关键帧评测只有 9 张图、Codex 一个平台,它的“局限”一节里写着长任务没测,这次补上。用合成的会话和图片,谁都能复现,不用用户的真实会话。这一轮只测 Claude Code(用户 2026-11-01 定);Codex 由用户自己上手体验,评测里只写测了什么。
-- **场景**:在关键帧评测的基础上加长。几十张合成图,有用户上传的,也有工具查看的(代替生成的,省掉生图费用);有同一张图的几个版本、一批里的好几张、三视图拼图;中间评价几张,有说好的、说差的、改主意的。Codex 压缩两次,Claude 压缩后再续接一次。
-- **题目**照真实会话里用户的说法设计:一批里的第几张、按版本(“v2”)、按内容(“穿红衣、站在窗边的那张”)、按评价(“脸最好的那张”)、按文件名;另有只看原图才答得出的细节题(角落里的数字)。
-- **记录**:答对几题、取了哪几张、每条请求的 token 和耗时;对照 0.9.1(修复前)和 0.10。
-- 脚本放在 `spike/src/eval-*.ts`,报告放在 `eval/`,英文和中文各一份,README 底部的评测一节加一句链接。
+- **怎么跑**:命令行版 Claude Code,脚本驱动,一个会话一个进程,像桌面版那样一条条发消息。用评测自己的配置文件夹(`CLAUDE_CONFIG_DIR`),用户的技能、设置、记录都不混进来;插件用 `--plugin-dir` 加载,各组各用自己的引擎端口和数据文件夹。自动压缩关掉,脚本在两个固定位置发 `/compact`(和用户手打一样),三组都在同一处压缩;每次压缩后接着问题。
+- **三组**:不装插件、0.9.1、0.10。0.9.1 的 mod 在 Claude Code 2.1.309 起不加载,对照组用只换上修好的 `register.js` 的 0.9.1(两个版本的 mod 只差这一处),比出来的才是压缩修复本身的效果。
+- **模型**:Haiku 5.5,推理强度 low,每组跑一次。原来打算再加 Sonnet,以及 300 张、600 张两档看全量清单从多大规模开始不准;试跑算下来要用掉测试账号一周额度的大半,用户定先做简单的一版(2026-11-01),规模的问题以后需要时再测。
+- **场景**:在关键帧评测的基础上加长。51 张合成图、16 轮,有用户直接发的(简笔画、重发的同一张),也有工具查看的(代替生成的,省掉生图费用);有同一镜头的几个版本、几乎一样的抽帧、三视图、一批设置页截图、一次并行读的一批;中间评价几张,有说好的、说差的、改主意的、只说局部的。
+- **题目**照真实会话里用户的说法设计:一批里的哪一张、按版本、按内容、按评价(含改了主意的)、按文件名;另有只看原图才答得出的细节题(角落里的数字)、不需要看图的题。压缩后在原会话里接着问,最后再分叉一次问几题。
+- **记录**:答对几题、取了哪几张、取错几次、每条请求的 token、放回的清单占多少。脚本看着账号的用量,一周额度到 90% 就停。
+- **真实会话**:关卡 8 的长会话回放只写数字(图数、压缩次数、题数和对错、发现并修好的问题),注明素材不公开、不能复现;题目不写,题目本身带着用户项目的内容。
+- 脚本放在 `spike/src/eval-*.ts`,报告放在 `eval/`,英文和中文各一份,写明测试日期、插件版本、Claude Code 版本、模型和推理强度、系统;README 底部的评测一节加一句链接。
## 7. 验收
@@ -148,3 +154,7 @@
随后用户补充(同一天):两边放回的一段占请求约 7% 以内都能接受,更要紧的是准确度和信息别丢太多。关卡 6 的上限照此定为约 7%。
6. 按桌面实测校准系数以后,Claude 那个 127 张的会话在压缩后的头几条请求里约占 7%–9%,超过 7%;对话变长后降到 7% 以下。要一直压在 7% 以下,就得截短特征行或去掉文件名。用户选择保持现状。
+
+2026-11-01:
+
+7. 公开评测按简单的一版跑(Haiku,一个场景,第 6 节)。跑完后发现装插件的 Claude 会话提示缓存命中有问题,用户定:报告先存在本机的 `local/`,不进 git;等缓存的问题改好、重跑以后再发布。评测脚本留在仓库里,改完用它重跑。
diff --git a/spike/src/eval-long-scene.test.ts b/spike/src/eval-long-scene.test.ts
new file mode 100644
index 0000000..18835ff
--- /dev/null
+++ b/spike/src/eval-long-scene.test.ts
@@ -0,0 +1,47 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { draw, scene, score } from "./eval-long-scene.ts";
+
+test("eval-long: each question fits exactly one image, its answer", () => {
+ const { images, steps, questions } = scene();
+ const keys = images.map((image) => image.key);
+ assert.equal(new Set(keys).size, keys.length);
+ for (const question of questions) {
+ if (question.target) assert.ok(keys.includes(question.target), `${question.key} target ${question.target}`);
+ if (question.fits) assert.deepEqual(images.filter(question.fits).map((image) => image.key), [question.target], `${question.key}: ${question.say}`);
+ if (question.expect === "number") assert.match(question.answer, /^\d+$/);
+ }
+ // Every file a turn names is an image of the scene, and every image is named or sent once.
+ const files = new Set(images.flatMap((image) => ("file" in image ? [image.file] : [])));
+ const named = steps.flatMap((step) => (step.type === "turn" ? [...step.say.matchAll(/[\w-]+\.png/g)].map((m) => m[0]) : []));
+ for (const file of named) assert.ok(files.has(file), file);
+ const ranges = [...steps.flatMap((step) => (step.type === "turn" ? [...step.say.matchAll(/(clip\d+|set_\d+)_(\d+)\.png 到 \1_(\d+)\.png/g)] : []))];
+ const shown = new Set([...named, ...ranges.flatMap((m) => Array.from({ length: Number(m[3]) - Number(m[2]) + 1 }, (_, i) => `${m[1]}_${m[1].startsWith("clip") ? String(Number(m[2]) + i).padStart(2, "0") : Number(m[2]) + i}.png`))]);
+ assert.deepEqual([...files].filter((file) => !shown.has(file)), []);
+ const uploads = steps.flatMap((step) => (step.type === "turn" ? step.upload : []));
+ assert.deepEqual(uploads.sort(), images.filter((image) => !("file" in image)).map((image) => image.key).sort());
+ assert.equal(images.length, 51);
+ assert.equal(steps.filter((step) => step.type === "turn").length, 16);
+});
+
+test("eval-long: images are PNGs, a resent image is the same bytes", () => {
+ const { images } = scene();
+ const of = (key: string) => images.find((image) => image.key === key)!;
+ for (const key of ["s03_v2", "sheet_03", "clip1_06", "set_1105_4", "sketch2"]) assert.equal(draw(of(key), images).subarray(1, 4).toString("ascii"), "PNG");
+ assert.deepEqual(draw(of("resend1"), images), draw(of("s05_v2"), images));
+});
+
+test("eval-long: scoring", () => {
+ const { questions } = scene();
+ const q = (key: string) => questions.find((question) => question.key === key)!;
+ const file = q("Q2"), digit = q("Q7"), sit = q("Q11"), count = q("Q14");
+ assert.equal(file.answer, "s03_v1.png");
+ assert.deepEqual(score(file, "[//]: # (cam IMG-007 雨夜|近景)\n是 s03_v1.png。"), { verdict: "right", said: "s03_v1.png" });
+ assert.equal(score(file, "s03_v2.png").verdict, "wrong");
+ assert.equal(score(file, "看不到这张图了").verdict, "none");
+ assert.equal(digit.target, "s01_v1");
+ assert.equal(score(digit, `第 1 镜 v1(s01_v1.png,IMG-001)角落里的数字是 ${digit.answer}。`).said, digit.answer);
+ assert.equal(score(sit, "坐着,坐在椅子上").verdict, "right");
+ assert.equal(score(sit, "站着").verdict, "wrong");
+ assert.equal(score(count, "一共 3 版").said, "3");
+});
diff --git a/spike/src/eval-long-scene.ts b/spike/src/eval-long-scene.ts
new file mode 100644
index 0000000..29da763
--- /dev/null
+++ b/spike/src/eval-long-scene.ts
@@ -0,0 +1,456 @@
+// Purpose: eval — the scene of the long keyframe task in Claude Code (eval-long.ts): synthetic
+// images, the user's turns, the questions with their answers, and how a reply is scored. Nothing here runs a model;
+// eval-long-scene.test.ts checks that every question has exactly one right answer.
+// The task (51 images, 16 turns): keyframes of a short film, ten shots of two or three versions, which the user asks the
+// model to look at (Read, standing in for generated images); two clips of extracted video frames, four settings-page
+// screenshots, four character turnaround sheets; two sketches the user sends, and once an earlier image sent again. The
+// user says where each shot takes place and who is in it, never how the versions differ (dark, position, a hat or an
+// umbrella): that is only in what the model saw. Ratings come in later turns, one changed afterwards, one about part of
+// an image. Each keyframe and sheet carries a faint two-digit number in a corner that only the original shows.
+// Input: none. Output: images (with a draw function), steps, questions, score().
+
+import { png } from "./testkit.ts";
+
+type Rgb = [number, number, number];
+export type Who = "her" | "him" | "side";
+export type Place = "study" | "rain" | "beach" | "bamboo" | "rooftop" | "cafe";
+export type ShotSize = "wide" | "medium" | "close";
+export type Pos = "left" | "center" | "right";
+export type Variant = { dark?: boolean; tint?: "warm" | "cool"; pos?: Pos; prop?: "umbrella" | "hat" };
+export type Pose = "raise" | "sit" | "point" | "jump";
+
+export type Image =
+ | { key: string; kind: "keyframe"; file: string; shot: number; version: number; place: Place; who: Who | null; size: ShotSize; variant: Variant; number: number }
+ | { key: string; kind: "sheet"; file: string; who: Who; belt: boolean; number: number }
+ | { key: string; kind: "frame"; file: string; clip: number; frame: number; frames: number; scene: "car" | "walk"; mark: number }
+ | { key: string; kind: "screen"; file: string; batch: string; index: number; values: [number, number, number] }
+ | { key: string; kind: "sketch"; pose: Pose; index: number }
+ | { key: string; kind: "resend"; of: string };
+
+export type Question = {
+ key: string; block: "mid" | "end" | "fork"; say: string;
+ expect: "file" | "number" | "word" | "text"; answer: string;
+ // The image the question is about (null: none); needsOriginal: only the original answers it.
+ target: string | null; needsOriginal: boolean;
+ // For the unit test: the images the user's words fit. Exactly one, the target.
+ fits?: (image: Image) => boolean;
+};
+export type Step =
+ | { type: "turn"; say: string; upload: string[] }
+ | { type: "compact"; label: "mid" | "end" }
+ | { type: "ask"; block: "mid" | "end" | "fork" };
+
+export const PLACE_ZH: Record<Place, string> = { study: "书房", rain: "雨夜街道", beach: "黄昏海边", bamboo: "竹林", rooftop: "夜晚屋顶", cafe: "咖啡馆" };
+const WHO_ZH: Record<Who, string> = { her: "女主", him: "男主", side: "配角" };
+const SIZE_ZH: Record<ShotSize, string> = { wide: "全景", medium: "中景", close: "近景" };
+
+// ---- Drawing ----
+
+const FONT: Record<string, string[]> = {
+ "0": ["01110", "10001", "10011", "10101", "11001", "10001", "01110"],
+ "1": ["00100", "01100", "00100", "00100", "00100", "00100", "01110"],
+ "2": ["01110", "10001", "00001", "00010", "00100", "01000", "11111"],
+ "3": ["11111", "00010", "00100", "00010", "00001", "10001", "01110"],
+ "4": ["00010", "00110", "01010", "10010", "11111", "00010", "00010"],
+ "5": ["11111", "10000", "11110", "00001", "00001", "10001", "01110"],
+ "6": ["00110", "01000", "10000", "11110", "10001", "10001", "01110"],
+ "7": ["11111", "00001", "00010", "00100", "01000", "01000", "01000"],
+ "8": ["01110", "10001", "10001", "01110", "10001", "10001", "01110"],
+ "9": ["01110", "10001", "10001", "01111", "00001", "00010", "01100"],
+};
+// Is (x, y) on a digit of text drawn from (left, top) at this scale?
+function glyphs(text: string, left: number, top: number, scale: number): (x: number, y: number) => boolean {
+ const step = 7 * scale;
+ return (x, y) => {
+ const row = Math.floor((y - top) / scale);
+ if (x < left || y < top || row >= 7) return false;
+ const at = Math.floor((x - left) / step);
+ const col = Math.floor((x - left - at * step) / scale);
+ return at < text.length && col < 5 && FONT[text[at]][row][col] === "1";
+ };
+}
+// The corner number: small faint digits like a watermark, lighter or darker than what is under them. A first try had
+// white digits on a dark plate: the model wrote them into its feature lines, and the questions about them no longer
+// needed the original.
+function cornerMark(number: number, corner: number, width: number, height: number): (x: number, y: number, rgb: Rgb) => Rgb {
+ const scale = 3, margin = 14, w = 2 * 7 * scale - 2 * scale, h = 7 * scale;
+ const left = corner % 2 === 0 ? margin : width - margin - w;
+ const top = corner < 2 ? margin : height - margin - h;
+ const digit = glyphs(String(number).padStart(2, "0"), left, top, scale);
+ return (x, y, rgb) => {
+ if (!digit(x, y)) return rgb;
+ const light = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11 > 110;
+ return mix(rgb, light ? [0, 0, 0] : [255, 255, 255], 0.55);
+ };
+}
+
+const mix = (a: Rgb, b: Rgb, t: number): Rgb => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];
+const inCircle = (x: number, y: number, cx: number, cy: number, r: number) => (x - cx) ** 2 + (y - cy) ** 2 < r * r;
+const hashOf = (text: string) => text.split("").reduce((sum, ch) => (sum * 31 + ch.charCodeAt(0)) >>> 0, 7);
+
+function backdrop(place: Place, x: number, y: number, W: number, H: number): Rgb {
+ const u = x / W, v = y / H;
+ switch (place) {
+ case "study": {
+ if (v < 0.12) return [150, 105, 70];
+ if (v > 0.8) return [110, 75, 50];
+ const row = (y - 0.12 * H) % 130;
+ if (row < 12) return [90, 55, 30];
+ const spines: Rgb[] = [[170, 40, 40], [200, 170, 60], [140, 70, 40], [190, 110, 50], [120, 50, 60]];
+ return x % 26 < 3 ? [90, 55, 30] : spines[(Math.floor(x / 26) + Math.floor((y - 0.12 * H) / 130) * 2) % spines.length];
+ }
+ case "rain": {
+ const base: Rgb = v > 0.82 ? ((x + y) % 40 < 3 ? [70, 75, 95] : [30, 32, 42]) : mix([15, 20, 45], [40, 45, 75], v);
+ const glow = Math.max(0, 1 - Math.hypot(x - 0.78 * W, y - 0.22 * H) / (0.34 * Math.min(W, H) + 60));
+ const lit = mix(base, [235, 205, 120], glow * glow);
+ return (x + Math.floor(y * 0.3)) % 31 < 2 && y % 70 < 46 ? mix(lit, [170, 180, 210], 0.55) : lit;
+ }
+ case "beach": {
+ if (v >= 0.62) return (y - 0.62 * H) % 40 < 4 ? [90, 130, 170] : [40, 80, 130];
+ return mix([240, 120, 80], [252, 196, 150], v / 0.62);
+ }
+ case "bamboo": {
+ if (x % 110 >= 26) return [80, 140, 80];
+ return y % 150 < 8 ? [25, 70, 30] : [40, 100, 45];
+ }
+ case "rooftop": {
+ if (v > 0.66 && v < 0.68) return [130, 130, 140];
+ if (v >= 0.68 && x % 40 < 5) return [120, 120, 130];
+ if (v > 0.74) return x % 24 < 9 && y % 28 < 11 && hashOf(`${Math.floor(x / 24)},${Math.floor(y / 28)}`) % 3 === 0 ? [230, 200, 90] : [22, 22, 30];
+ return mix([10, 12, 30], [32, 30, 62], v / 0.74);
+ }
+ case "cafe": {
+ if (v > 0.9) return [150, 110, 80];
+ if (u > 0.08 && u < 0.5 && v > 0.1 && v < 0.42) return u < 0.1 || u > 0.48 || v < 0.12 || v > 0.4 || Math.abs(u - 0.29) < 0.01 ? [240, 240, 235] : [170, 200, 230];
+ if (inCircle(x / W, (y / H) * 2.4, 0.78, 0.86 * 2.4, 0.13)) return [120, 80, 50];
+ return [230, 215, 185];
+ }
+ }
+}
+
+const SKIN: Rgb = [235, 195, 165], EYE: Rgb = [30, 25, 25], WHITE: Rgb = [248, 248, 248], LIPS: Rgb = [170, 70, 70];
+const LOOK: Record<Who, { hair: Rgb; outfit: Rgb; long: boolean; glasses: boolean }> = {
+ her: { hair: [25, 20, 20], outfit: [190, 30, 40], long: true, glasses: false },
+ him: { hair: [75, 48, 25], outfit: [40, 70, 150], long: false, glasses: false },
+ side: { hair: [150, 150, 150], outfit: [40, 120, 70], long: false, glasses: true },
+};
+
+// A person facing the camera: red dress and long black hair, blue with short brown hair, or green with grey hair and
+// glasses; a hat or an umbrella when the variant has one.
+function person(who: Who, size: ShotSize, variant: Variant, x: number, y: number): Rgb | null {
+ const look = LOOK[who];
+ const pos = variant.pos ?? "center";
+ const [r, cy] = size === "close" ? [170, 400] : size === "medium" ? [62, 330] : [22, 560];
+ const cx = (size === "close" ? { left: 200, center: 256, right: 312 } : size === "medium" ? { left: 150, center: 256, right: 362 } : { left: 130, center: 256, right: 382 })[pos];
+ if (variant.prop === "umbrella") {
+ // A purple canopy with darker ribs, and its handle beside the face.
+ const top = cy - 1.25 * r;
+ if (y < top && inCircle(x, y, cx, top, 1.9 * r)) return Math.abs(((Math.atan2(top - y, x - cx) * 180) / Math.PI) % 30) < 1.2 ? [70, 25, 80] : [125, 55, 140];
+ if (Math.abs(x - (cx + r)) < Math.max(2, 0.03 * r) && y >= top && y < cy + 0.9 * r) return [60, 60, 60];
+ }
+ if (variant.prop === "hat") {
+ if (Math.abs(x - cx) < 1.25 * r && y > cy - 0.98 * r && y < cy - 0.82 * r) return [25, 25, 30];
+ if (Math.abs(x - cx) < 0.7 * r && y > cy - 1.6 * r && y <= cy - 0.98 * r) return [25, 25, 30];
+ }
+ const close = size === "close";
+ if (inCircle(x, y, cx, cy, r)) {
+ const eyeY = cy + r * 0.05, eyeX = r * 0.38;
+ for (const ex of [cx - eyeX, cx + eyeX]) {
+ if (inCircle(x, y, ex, eyeY, r * 0.07)) return EYE;
+ if (look.glasses && inCircle(x, y, ex, eyeY, r * 0.17) && !inCircle(x, y, ex, eyeY, r * 0.13)) return [35, 35, 35];
+ if (close && inCircle(x, y, ex, eyeY, r * 0.13)) return WHITE;
+ }
+ if (look.glasses && Math.abs(y - eyeY) < r * 0.02 && Math.abs(x - cx) < r * 0.22) return [35, 35, 35];
+ if (Math.abs(x - cx) < r * 0.28 && y > cy + r * 0.45 && y < cy + r * 0.53) return LIPS;
+ if (y < cy - r * (look.long ? 0.35 : 0.45)) return look.hair;
+ return SKIN;
+ }
+ const neckTop = cy + r * 0.85, shoulders = cy + r * (close ? 1.25 : 1.35);
+ const off = Math.abs(x - cx);
+ if (look.long && off < r * 1.3 && y > cy - r * 0.9 && (y < cy + r * 0.5 || (off > r * 0.6 && y < cy + r * (close ? 1.6 : 2.6)))) return look.hair;
+ if (!look.long && inCircle(x, y, cx, cy - r * 0.1, r * 1.08) && y < cy - r * 0.2) return look.hair;
+ if (off < r * 0.3 && y >= neckTop && y < shoulders) return SKIN;
+ const bottom = size === "close" ? Infinity : cy + r * 5.2;
+ if (y >= shoulders && y < bottom && off < r * 1.4 + (y - shoulders) * (close ? 0.8 : 0.3)) return look.outfit;
+ return null;
+}
+
+function grainOf(key: string): () => number {
+ let state = (0x9e3779b9 ^ hashOf(key)) >>> 0 || 1;
+ return () => { state ^= state << 13; state ^= state >>> 17; state ^= state << 5; return ((state >>> 0) % 13) - 6; };
+}
+const finish = (rgb: Rgb, grain: () => number): Rgb => [rgb[0], rgb[1], rgb[2]].map((value) => Math.max(0, Math.min(255, Math.round(value + grain())))) as Rgb;
+const cornerOf = (key: string) => hashOf(`${key}#corner`) % 4;
+
+function drawKeyframe(image: Extract<Image, { kind: "keyframe" }>): Buffer {
+ const W = 512, H = 768;
+ const grain = grainOf(image.key);
+ const mark = cornerMark(image.number, cornerOf(image.key), W, H);
+ return png(W, H, (x, y) => {
+ let rgb = (image.who ? person(image.who, image.size, image.variant, x, y) : null) ?? backdrop(image.place, x, y, W, H);
+ if (image.variant.tint === "warm") rgb = [rgb[0] + 38, rgb[1] + 12, rgb[2] - 28];
+ if (image.variant.tint === "cool") rgb = [rgb[0] - 28, rgb[1] + 2, rgb[2] + 38];
+ if (image.variant.dark) rgb = [rgb[0] * 0.35, rgb[1] * 0.35, rgb[2] * 0.35];
+ return finish(mark(x, y, rgb), grain);
+ });
+}
+
+// Front, side and back of one character on a grey sheet; the second version of a sheet adds a yellow belt.
+function drawSheet(image: Extract<Image, { kind: "sheet" }>): Buffer {
+ const W = 768, H = 512;
+ const grain = grainOf(image.key);
+ const mark = cornerMark(image.number, cornerOf(image.key), W, H);
+ const look = LOOK[image.who];
+ return png(W, H, (x, y) => finish(mark(x, y, sheetAt(x, y)), grain));
+ function sheetAt(x: number, y: number): Rgb {
+ for (const [view, cx] of [["front", 128], ["side", 384], ["back", 640]] as const) {
+ const cy = 120, r = 38;
+ if (inCircle(x, y, cx, cy, r)) {
+ if (view === "back") return look.hair;
+ if (y < cy - r * (look.long ? 0.35 : 0.45)) return look.hair;
+ if (view === "front" && (inCircle(x, y, cx - 14, cy + 2, 3.5) || inCircle(x, y, cx + 14, cy + 2, 3.5))) return EYE;
+ if (view === "side" && inCircle(x, y, cx + 16, cy + 2, 3.5)) return EYE;
+ if (look.glasses && view !== "back" && Math.abs(y - (cy + 2)) < 1.5 && Math.abs(x - cx) < 26) return [35, 35, 35];
+ return SKIN;
+ }
+ if (view === "side" && inCircle(x, y, cx + r - 2, cy + 8, 7)) return SKIN;
+ if (look.long && Math.abs(x - cx) < r + 6 && y > cy && y < (view === "back" ? 240 : 190) && (view === "back" || Math.abs(x - cx) > r * 0.6)) return look.hair;
+ const half = 40 + (y - 165) * 0.1;
+ if (y >= 165 && y < 360 && Math.abs(x - cx) < half) return image.belt && y >= 255 && y < 268 ? [225, 190, 40] : look.outfit;
+ if (y >= 360 && y < 465 && Math.abs(Math.abs(x - cx) - 18) < 8) return [60, 60, 70];
+ if (y >= 175 && y < 330 && Math.abs(Math.abs(x - cx) - (half + 8)) < 6) return SKIN;
+ }
+ if (Math.abs(y - 470) < 2) return [150, 150, 150];
+ return [228, 228, 228];
+ }
+}
+
+// Frame `frame` of a clip: a car driving left to right past a street lamp at night, or the lead walking right to left
+// along the beach past the setting sun. `mark` is the frame the car is right under the lamp, or she covers the sun.
+export const carX = (frame: number, frames: number) => 100 + ((frame - 1) * (768 - 200)) / (frames - 1);
+export const walkerX = (frame: number, frames: number) => 700 - ((frame - 1) * 640) / (frames - 1);
+function drawFrame(image: Extract<Image, { kind: "frame" }>): Buffer {
+ const W = 768, H = 512;
+ const grain = grainOf(image.key);
+ if (image.scene === "car") {
+ const lamp = carX(image.mark, image.frames), cx = carX(image.frame, image.frames);
+ // The car is narrower than one frame's step, so only one frame has it under the lamp.
+ return png(W, H, (x, y) => {
+ if (inCircle(x, y, cx + 38, 395, 6) && x > cx + 32) return finish([250, 230, 120], grain);
+ if (inCircle(x, y, cx - 24, 422, 10) || inCircle(x, y, cx + 24, 422, 10)) return finish([15, 15, 15], grain);
+ if (Math.abs(x - cx) < 40 && y > 380 && y < 420) return finish([70, 72, 80], grain);
+ if (Math.abs(x - cx) < 24 && y > 356 && y <= 380) return finish(Math.abs(x - cx) < 20 && y > 360 ? [120, 140, 170] : [70, 72, 80], grain);
+ if (Math.abs(x - lamp) < 4 && y > 110 && y < 470) return finish([90, 90, 95], grain);
+ const glow = Math.max(0, 1 - Math.hypot(x - lamp, y - 110) / 150);
+ const base: Rgb = y > 430 ? ((x + y) % 40 < 3 ? [70, 75, 95] : [30, 32, 42]) : mix([15, 20, 45], [40, 45, 75], y / H);
+ const lit = mix(base, [235, 205, 120], glow * glow);
+ return finish((x + Math.floor(y * 0.3)) % 31 < 2 && y % 70 < 46 ? mix(lit, [170, 180, 210], 0.55) : lit, grain);
+ });
+ }
+ const sun = walkerX(image.mark, image.frames), cx = walkerX(image.frame, image.frames);
+ return png(W, H, (x, y) => {
+ // Her head at y 250, in front of the sun; the sun is narrower than one frame's step.
+ const her = person("her", "wide", { pos: "center" }, x - cx + 256, y + 310);
+ if (her) return finish(her, grain);
+ if (y < 0.6 * H && inCircle(x, y, sun, 0.6 * H - 40, 50)) return finish([255, 222, 130], grain);
+ if (y >= 0.6 * H) return finish((y - 0.6 * H) % 30 < 3 ? [90, 130, 170] : [40, 80, 130], grain);
+ return finish(mix([240, 120, 80], [252, 196, 150], y / (0.6 * H)), grain);
+ });
+}
+
+// A settings page: a top bar, a sidebar, and three rows (green, blue, orange dots) with a number each.
+function drawScreen(image: Extract<Image, { kind: "screen" }>): Buffer {
+ const W = 768, H = 512;
+ const grain = grainOf(image.key);
+ const dots: Rgb[] = [[40, 170, 80], [50, 110, 220], [240, 140, 30]];
+ const values = image.values.map((value, row) => glyphs(String(value), 470, 120 + row * 100 - 17, 5));
+ return png(W, H, (x, y) => {
+ if (y < 44) return finish(x > 20 && x < 120 && y > 16 && y < 28 ? [200, 200, 205] : [45, 48, 55], grain);
+ if (x < 150) return finish(x > 20 && x < 130 && (y - 70) % 60 < 22 && y < 380 ? [205, 207, 214] : [235, 236, 240], grain);
+ if (x < 190 || x > 720 || y < 80 || y > 440) return finish([250, 250, 252], grain);
+ if (x === 190 || x === 720 || y === 80 || y === 440) return finish([200, 200, 205], grain);
+ for (let row = 0; row < 3; row++) {
+ const cy = 120 + row * 100;
+ if (inCircle(x, y, 225, cy, 14)) return finish(dots[row], grain);
+ if (x > 255 && x < 420 && Math.abs(y - cy) < 7) return finish([190, 192, 198], grain);
+ if (x > 455 && x < 600 && Math.abs(y - cy) < 28) {
+ if (values[row](x, y)) return finish([30, 30, 35], grain);
+ return finish(x < 458 || x > 597 || Math.abs(y - cy) > 25 ? [170, 172, 180] : [255, 255, 255], grain);
+ }
+ }
+ return finish([255, 255, 255], grain);
+ });
+}
+
+// A stick figure in black pen on white: one arm up (on the left of the picture), sitting on a chair, pointing to the
+// right, or jumping with both arms up.
+function drawSketch(image: Extract<Image, { kind: "sketch" }>): Buffer {
+ const W = 512, H = 512;
+ const grain = grainOf(image.key);
+ type Seg = [number, number, number, number];
+ const body: Seg[] = { raise: [[256, 180, 256, 330], [256, 330, 210, 450], [256, 330, 302, 450], [256, 215, 150, 120], [256, 215, 320, 290]],
+ sit: [[256, 180, 256, 330], [256, 330, 340, 330], [340, 330, 340, 440], [256, 215, 200, 290], [256, 215, 312, 290], [180, 340, 360, 340], [190, 340, 190, 450], [350, 340, 350, 450]],
+ point: [[256, 180, 256, 330], [256, 330, 210, 450], [256, 330, 302, 450], [256, 215, 420, 215], [256, 215, 200, 290]],
+ jump: [[256, 180, 256, 320], [256, 320, 180, 420], [256, 320, 332, 420], [256, 215, 180, 110], [256, 215, 332, 110]] }[image.pose] as Seg[];
+ const near = (x: number, y: number, [x1, y1, x2, y2]: Seg) => {
+ const dx = x2 - x1, dy = y2 - y1;
+ const t = Math.max(0, Math.min(1, ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy)));
+ return Math.hypot(x - (x1 + t * dx), y - (y1 + t * dy)) < 3.5;
+ };
+ return png(W, H, (x, y) => {
+ const ring = Math.hypot(x - 256, y - 135);
+ if ((ring > 38 && ring < 45) || body.some((seg) => near(x, y, seg))) return finish([25, 25, 25], grain);
+ return finish([250, 250, 246], grain);
+ });
+}
+
+export function draw(image: Image, images: Image[]): Buffer {
+ switch (image.kind) {
+ case "keyframe": return drawKeyframe(image);
+ case "sheet": return drawSheet(image);
+ case "frame": return drawFrame(image);
+ case "screen": return drawScreen(image);
+ case "sketch": return drawSketch(image);
+ case "resend": return draw(images.find((other) => other.key === image.of)!, images);
+ }
+}
+
+// ---- The task ----
+
+type Shot = { shot: number; place: Place; who: Who | null; size: ShotSize; variants: Variant[] };
+const SHOTS_A: Shot[] = [
+ { shot: 1, place: "study", who: "her", size: "medium", variants: [{ pos: "left" }, { pos: "center" }] },
+ { shot: 2, place: "study", who: "him", size: "medium", variants: [{ dark: true }, {}, { prop: "hat" }] },
+ { shot: 3, place: "rain", who: "her", size: "close", variants: [{}, { prop: "umbrella" }, { prop: "umbrella", tint: "warm" }] },
+ { shot: 4, place: "rain", who: null, size: "wide", variants: [{}, { dark: true }] },
+ { shot: 5, place: "beach", who: "him", size: "medium", variants: [{ pos: "left" }, { pos: "center" }, { pos: "right" }] },
+ { shot: 6, place: "beach", who: "her", size: "close", variants: [{ prop: "hat" }, {}, { tint: "warm" }] },
+];
+const SHOTS_B: Shot[] = [
+ { shot: 7, place: "bamboo", who: "side", size: "medium", variants: [{ prop: "hat" }, {}] },
+ { shot: 8, place: "bamboo", who: "her", size: "close", variants: [{}, { prop: "hat" }, { tint: "cool" }] },
+ { shot: 9, place: "rooftop", who: "him", size: "medium", variants: [{ dark: true }, {}, { pos: "right" }] },
+ { shot: 10, place: "cafe", who: "her", size: "medium", variants: [{ pos: "left" }, { pos: "right" }] },
+];
+const SCREENS: Array<[number, number, number]> = [[5, 41, 30], [8, 73, 30], [12, 28, 30], [10, 65, 50]];
+
+const numberOf = (key: string) => 10 + (hashOf(`${key}#n`) % 90);
+const range = (from: number, to: number) => Array.from({ length: to - from + 1 }, (_, i) => from + i);
+const two = (n: number) => String(n).padStart(2, "0");
+
+export type Scene = { images: Image[]; steps: Step[]; questions: Question[] };
+
+export function scene(): Scene {
+ const images: Image[] = [];
+ const steps: Step[] = [];
+ const turn = (say: string, upload: string[] = []) => steps.push({ type: "turn", say, upload });
+ const keyframes = (shot: Shot) => shot.variants.map((variant, i) => {
+ const key = `s${two(shot.shot)}_v${i + 1}`;
+ const image: Image = { key, kind: "keyframe", file: `${key}.png`, shot: shot.shot, version: i + 1, place: shot.place, who: shot.who, size: shot.size, variant, number: numberOf(key) };
+ images.push(image);
+ return image.file as string;
+ });
+ const shotLine = (shot: Shot) => {
+ const files = keyframes(shot);
+ const who = shot.who ? `${WHO_ZH[shot.who]}${SIZE_ZH[shot.size]}` : "空镜";
+ return `第 ${shot.shot} 镜,${PLACE_ZH[shot.place]},${who},${files.length} 版:${files.join("、")}`;
+ };
+ const shots = (list: Shot[], tail = "看一下。") => turn(`${list.map(shotLine).join(";")}。${tail}`);
+ const clip = (clipNo: number, frames: number, scene: "car" | "walk", mark: number) => {
+ for (const frame of range(1, frames)) images.push({ key: `clip${clipNo}_${two(frame)}`, kind: "frame", file: `clip${clipNo}_${two(frame)}.png`, clip: clipNo, frame, frames, scene, mark });
+ return `clip${clipNo}_01.png 到 clip${clipNo}_${two(frames)}.png`;
+ };
+ const screens = (batch: string, values: Array<[number, number, number]>) => {
+ values.forEach((value, i) => images.push({ key: `set_${batch}_${i + 1}`, kind: "screen", file: `set_${batch}_${i + 1}.png`, batch, index: i + 1, values: value }));
+ return `set_${batch}_1.png 到 set_${batch}_${values.length}.png`;
+ };
+ const sheet = (n: number, who: Who, belt: boolean) => {
+ const key = `sheet_${two(n)}`;
+ images.push({ key, kind: "sheet", file: `${key}.png`, who, belt, number: numberOf(key) });
+ return `${key}.png`;
+ };
+ const sketch = (index: number, pose: Pose) => { images.push({ key: `sketch${index}`, kind: "sketch", pose, index }); return `sketch${index}`; };
+
+ // Part A: shots 1–6, two sketches, the first sheets, a clip, screenshots, an image sent again; then a compaction.
+ turn("我们在做一部短片的关键帧和分镜,图都在当前文件夹里。接下来每轮我会说看哪些图,你用 Read 看完简单说一两句就行,别展开分析;我直接发给你的图也一样。不用改文件,也不用跑命令。人物:女主穿红裙、黑色长发;男主穿蓝外套、棕色短发;配角穿绿大衣、灰头发、戴眼镜。\n\n" +
+ `${shotLine(SHOTS_A[0])}。看一下。`);
+ shots([SHOTS_A[1]]);
+ shots([SHOTS_A[2]]);
+ turn("这是我画的两张简笔画,后面按这个姿势出图。", [sketch(1, "raise"), sketch(2, "sit")]);
+ shots([SHOTS_A[3]], "第 3 镜 v2 女主的脸最好,先定它。看一下。");
+ shots([SHOTS_A[4]]);
+ turn(`两张三视图:${sheet(1, "her", false)} 是女主,${sheet(2, "him", false)} 是男主。看一下。`);
+ shots([SHOTS_A[5]]);
+ turn(`第 1 段视频(雨夜街道)抽了 8 帧:${clip(1, 8, "car", 6)},都看一下,看车的动作连不连贯。`);
+ turn(`我截了 4 张生成工具的设置页:${screens("1105", SCREENS)}。绿色那一行是时长,蓝色是种子,橙色是步数,帮我看看有没有填错的。第 6 镜 v3 衣服和光都对了,但表情不对,表情还是参考 v1。`);
+ images.push({ key: "resend1", kind: "resend", of: "s05_v2" });
+ turn("这张你看一下,我想在它基础上把表情改得自然一点。", ["resend1"]);
+ steps.push({ type: "compact", label: "mid" }, { type: "ask", block: "mid" });
+
+ // Part B: shots 7–10, a change of mind, a second clip, a better sheet; then a compaction and a fork.
+ shots([SHOTS_B[0]]);
+ shots([SHOTS_B[1]], "第 3 镜我改主意了:v2 光太硬,最后用 v3。看一下。");
+ turn(`海边那段视频也抽了 6 帧:${clip(2, 6, "walk", 4)},看看女主走路的节奏。`);
+ shots([SHOTS_B[2], SHOTS_B[3]]);
+ turn(`男主三视图第二版:${sheet(3, "him", true)},这版比例更好。还有配角的 ${sheet(4, "side", false)}。第 9 镜 v1 太暗,不要了。看一下。`);
+ steps.push({ type: "compact", label: "end" }, { type: "ask", block: "end" }, { type: "ask", block: "fork" });
+
+ const kf = (image: Image) => (image.kind === "keyframe" ? image : null);
+ const of = (key: string) => images.find((image) => image.key === key)!;
+ const numberAt = (key: string) => { const image = of(key); return String(image.kind === "keyframe" || image.kind === "sheet" ? image.number : -1); };
+ const screen = (batch: string, index: number, row: number) => { const image = of(`set_${batch}_${index}`); return String(image.kind === "screen" ? image.values[row] : -1); };
+ const file = (key: string, block: Question["block"], say: string, fits: Question["fits"], needsOriginal = false): Question => ({ key: "", block, say: `${say}只回答文件名。`, expect: "file", answer: `${key}.png`, target: key, needsOriginal, fits });
+ const number = (key: string, block: Question["block"], say: string, answer: string, needsOriginal = true): Question => ({ key: "", block, say: `${say}只回答数字。`, expect: "number", answer, target: key, needsOriginal });
+ const questions: Question[] = [
+ file("s02_v1", "mid", "第 2 镜里偏暗的那一版是哪个文件?", (i) => kf(i)?.shot === 2 && !!kf(i)?.variant.dark),
+ file("s06_v1", "mid", "第 6 镜女主戴着帽子的那一版是哪个文件?", (i) => kf(i)?.shot === 6 && kf(i)?.variant.prop === "hat"),
+ number("s02_v3", "mid", "第 2 镜男主戴帽子的那一版,角落里的数字是多少?", numberAt("s02_v3")),
+ number("set_1105_3", "mid", "设置页截图里,第 3 张的种子(蓝色那一行)是多少?", screen("1105", 3, 1)),
+ file("s04_v2", "end", "雨夜街道的空镜(不是抽帧)里,整体更暗的那一版是哪个文件?", (i) => kf(i)?.place === "rain" && kf(i)?.who === null && !!kf(i)?.variant.dark),
+ file("s03_v1", "end", "第 3 镜里女主没打伞的那一版是哪个文件?", (i) => kf(i)?.shot === 3 && kf(i)?.variant.prop !== "umbrella"),
+ file("s03_v3", "end", "第 3 镜最后定的是哪一版?", (i) => i.key === "s03_v3"),
+ file("s06_v3", "end", "我说衣服和光都对了、但表情不对的那张是哪个文件?", (i) => i.key === "s06_v3"),
+ file("s09_v1", "end", "我说太暗、不要了的那张是哪个文件?", (i) => i.key === "s09_v1"),
+ file("s05_v3", "end", "第 5 镜里男主站在画面右边的那一版是哪个文件?", (i) => kf(i)?.shot === 5 && kf(i)?.variant.pos === "right"),
+ number("s01_v1", "end", "第 1 镜女主站在画面左边的那一版,角落里的数字是多少?", numberAt("s01_v1")),
+ file("clip1_06", "end", "第 1 段抽帧里,车正好开到路灯底下的那一帧是哪个文件?", (i) => i.kind === "frame" && i.clip === 1 && i.frame === i.mark),
+ file("clip2_04", "end", "海边那段抽帧里,女主走到正好挡住太阳的那一帧是哪个文件?", (i) => i.kind === "frame" && i.scene === "walk" && i.frame === i.mark),
+ file("set_1105_4", "end", "设置页截图里,步数(橙色那一行)填成 50 的是哪个文件?", (i) => i.kind === "screen" && i.values[2] === 50),
+ { key: "", block: "end", say: "我直接发给你的第二张简笔画,画的是什么姿势?一两个字回答。", expect: "word", answer: "坐", target: "sketch2", needsOriginal: false },
+ file("s05_v2", "end", "我后来直接发给你、说想在它基础上改表情的那张图,其实是之前哪个文件?", (i) => i.key === "s05_v2"),
+ file("sheet_03", "end", "男主的三视图里,我说比例更好的那一版是哪个文件?", (i) => i.key === "sheet_03"),
+ { key: "", block: "end", say: "第 2 镜一共出了几版?只回答数字。", expect: "number", answer: "3", target: null, needsOriginal: false },
+ file("s08_v2", "fork", "第 8 镜女主戴帽子的那一版是哪个文件?", (i) => kf(i)?.shot === 8 && kf(i)?.variant.prop === "hat"),
+ number("s05_v2", "fork", "第 5 镜男主站在画面中间的那一版,角落里的数字是多少?", numberAt("s05_v2")),
+ ];
+ const counts = { mid: 0, end: 0, fork: 0 };
+ for (const question of questions) question.key = `${{ mid: "M", end: "Q", fork: "K" }[question.block]}${++counts[question.block]}`;
+ return { images, steps, questions };
+}
+
+// ---- Scoring ----
+
+// The model's record lines ([//]: # (cam …)) are not part of what the user sees.
+export const visible = (reply: string) => reply.replace(/\[\/\/\]:[ \t]*#[ \t]*\(cam[^)\n]*\)/g, "").trim();
+const CN: Record<string, string> = { 零: "0", 一: "1", 二: "2", 两: "2", 三: "3", 四: "4", 五: "5", 六: "6", 七: "7", 八: "8", 九: "9", 十: "10" };
+
+// right, wrong (another file, number or word), or none (no answer of the asked kind: "I can't tell" and the like).
+export function score(question: Question, reply: string): { verdict: "right" | "wrong" | "none"; said: string | null } {
+ const shown = visible(reply);
+ const judge = (said: string | null) => ({ verdict: said === null ? "none" as const : said === question.answer ? "right" as const : "wrong" as const, said });
+ switch (question.expect) {
+ case "file": return judge(/[\w-]+\.png\b/i.exec(shown)?.[0].toLowerCase() ?? null);
+ case "number": {
+ const clean = shown.replace(/[\w-]+\.png\b/gi, "").replace(/IMG-\d+/g, "").replace(/set_\d+/g, "").replace(/第\s*\d+\s*[镜版张段批轮行帧]/g, "").replace(/\bv\d+\b/gi, "");
+ // Digits first: a Chinese numeral is often just a word ("一共", "一张").
+ const match = /(?<![0-9])[0-9]{1,3}(?![0-9])/.exec(clean)?.[0] ?? /[零一二两三四五六七八九十]/.exec(clean)?.[0] ?? null;
+ return judge(match === null ? null : CN[match] ?? match);
+ }
+ case "word": {
+ const options = question.answer === "坐" ? ["坐", "站", "举", "指", "跳"] : ["左", "右"];
+ const hit = options.map((word) => ({ word, at: shown.indexOf(word) })).filter((item) => item.at >= 0).sort((a, b) => a.at - b.at)[0];
+ return judge(hit?.word ?? null);
+ }
+ case "text": return { verdict: /weather/i.test(shown) ? "right" : "wrong", said: shown.slice(0, 80) };
+ }
+}
diff --git a/spike/src/eval-long-setup.ts b/spike/src/eval-long-setup.ts
new file mode 100644
index 0000000..f14a110
--- /dev/null
+++ b/spike/src/eval-long-setup.ts
@@ -0,0 +1,70 @@
+// Purpose: eval — what the long-task eval (eval-long.ts) runs Claude Code with, kept apart from the user's own setup:
+// a Claude Code configuration folder of its own (signed in once for the eval; no skills, settings, memory or history of
+// the user's), and for each arm a copy of the Claude plugin whose engine port and data folder are the eval's, so the
+// plugin the user has installed and its engine (port 17891) are never touched.
+// Arms: "v0.10" — this checkout. "v0.9.1" — the v0.9.1 release (`git archive v0.9.1`) with this checkout's hooks/register.js:
+// Claude Code 2.1.309 refuses 0.9.1's mod for `$.env.get(name)` with a non-literal name, and the two mods differ only in
+// that (CHANGELOG 0.10.0), so the arm measures the compaction fixes and nothing else.
+// Input: the arm, a port, folders. Output: plugin copies under local/eval-long/plugins/, an engine process.
+
+import { spawn, spawnSync, type ChildProcess } from "node:child_process";
+import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
+import { setTimeout as sleep } from "node:timers/promises";
+import { fileURLToPath } from "node:url";
+import { engineHealth } from "../../plugin/src/engine.ts";
+
+export type Arm = "off" | "v0.9.1" | "v0.10";
+const here = dirname(fileURLToPath(import.meta.url));
+export const repo = resolve(here, "../..");
+export const evalRoot = join(repo, "local", "eval-long");
+// The eval's own Claude Code configuration folder: sign in once with
+// CLAUDE_CONFIG_DIR=<repo>/local/eval-long/claude claude auth login
+export const claudeConfigDir = join(evalRoot, "claude");
+
+// The plugin files an arm runs: this checkout, or the v0.9.1 release extracted once.
+function sourceOf(arm: Exclude<Arm, "off">): string {
+ if (arm === "v0.10") return repo;
+ const dir = join(evalRoot, "v0.9.1");
+ if (!existsSync(join(dir, ".claude-plugin", "plugin.json"))) {
+ mkdirSync(dir, { recursive: true });
+ const archive = spawnSync("git", ["-C", repo, "archive", "--format=tar", "v0.9.1", "plugin", "hooks", ".claude-plugin"], { maxBuffer: 1 << 28 });
+ if (archive.status !== 0) throw new Error(`git archive v0.9.1 failed: ${archive.stderr}`);
+ // Unpacked in its own folder: a tar from Git for Windows takes "D:\…" after -C for a remote host.
+ const untar = spawnSync("tar", ["-x"], { cwd: dir, input: archive.stdout });
+ if (untar.status !== 0) throw new Error(`tar failed: ${untar.stderr}`);
+ }
+ return dir;
+}
+
+// A copy of an arm's plugin pointed at its own engine port and data folder; the model's text in Chinese, as the
+// conversation is.
+export function preparePlugin(arm: Exclude<Arm, "off">, port: number, data: string): string {
+ const source = sourceOf(arm);
+ const root = join(evalRoot, "plugins", `${arm}-${port}`);
+ rmSync(root, { recursive: true, force: true });
+ for (const part of ["hooks", "plugin/src", "plugin/scripts"]) cpSync(join(source, part), join(root, part), { recursive: true });
+ // v0.9.1 runs with the mod that loads in current Claude Code (see above).
+ if (arm === "v0.9.1") cpSync(join(repo, "hooks", "register.js"), join(root, "hooks", "register.js"));
+ const manifest = JSON.parse(readFileSync(join(source, ".claude-plugin", "plugin.json"), "utf8"));
+ const server = manifest.mcpServers.codex_attachment_manager;
+ server.env = { ...server.env, CAM_ENGINE_PORT: String(port), CAM_DATA_DIR: data, CAM_LANG: "zh" };
+ mkdirSync(join(root, ".claude-plugin"), { recursive: true });
+ writeFileSync(join(root, ".claude-plugin", "plugin.json"), JSON.stringify(manifest, null, 2));
+ const register = join(root, "hooks", "register.js");
+ const mod = readFileSync(register, "utf8").replace(/\r\n/g, "\n");
+ if (!mod.includes("const ENGINE_PORT = 17891")) throw new Error("the mod's engine port was not found");
+ writeFileSync(register, mod.replace("const ENGINE_PORT = 17891", `const ENGINE_PORT = ${port}`));
+ return root;
+}
+
+// The arm's engine, started from its plugin copy (the plugin's own service then finds it running and keeps it), with
+// every request written to <data>/p2/requests for the counts in the report.
+export async function startEngine(root: string, port: number, data: string): Promise<ChildProcess> {
+ if (await engineHealth(port)) throw new Error(`port ${port} is in use`);
+ const env = { ...process.env, CAM_DATA_DIR: data, CAM_LANG: "zh", CLAUDE_CONFIG_DIR: claudeConfigDir };
+ const engine = spawn(process.execPath, [join(root, "plugin", "src", "proxy.ts"), "--port", String(port), "--stay", "--dump-requests"], { env, stdio: "ignore", windowsHide: true });
+ for (let i = 0; i < 50 && !(await engineHealth(port)); i++) await sleep(200);
+ if (!(await engineHealth(port))) throw new Error(`the engine on ${port} did not start`);
+ return engine;
+}
diff --git a/spike/src/eval-long-summary.ts b/spike/src/eval-long-summary.ts
new file mode 100644
index 0000000..06c4bdb
--- /dev/null
+++ b/spike/src/eval-long-summary.ts
@@ -0,0 +1,81 @@
+// Purpose: eval — sums up the runs of eval-long.ts for the report (kept in local/eval-long/report until it goes into
+// eval/): per run, how many questions were answered right before and after the compactions and in the fork, how many
+// images the model fetched or read again, the feature lines it wrote, and what the requests cost. The summary keeps
+// the replies (synthetic content) without session ids or local paths.
+// Input: --label name [--out <dir>]. Output: a console summary; with --out, <dir>/summary.json.
+
+import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { evalRoot } from "./eval-long-setup.ts";
+
+type Json = Record<string, any>;
+const option = (name: string, fallback: string | null) => (process.argv.includes(name) ? process.argv[process.argv.indexOf(name) + 1] : fallback);
+const label = option("--label", "run1")!;
+const out = option("--out", null);
+const dir = join(evalRoot, label);
+// A run is its file: a run done again keeps the earlier one under another name (v0.10-haiku.before-wording.json).
+const runs: Json[] = readdirSync(dir).filter((name) => name.endsWith(".json")).map((name) => ({ ...JSON.parse(readFileSync(join(dir, name), "utf8")), file: name.replace(/\.json$/, "") }));
+// What Claude Code reports a session cost at API prices (total_cost_usd, a running total that a fork carries on).
+function costOf(run: Json): number | null {
+ const last = (file: string) => {
+ if (!existsSync(file)) return null;
+ const totals = readFileSync(file, "utf8").split("\n").flatMap((line) => { try { const event = JSON.parse(line); return event.type === "result" && typeof event.total_cost_usd === "number" ? [event.total_cost_usd] : []; } catch { return []; } });
+ return totals.at(-1) ?? null;
+ };
+ const total = last(join(dir, run.file, "events-fork.jsonl")) ?? last(join(dir, run.file, "events-main.jsonl"));
+ return total === null ? null : Math.round(total * 10000) / 10000;
+}
+
+// Tokens a request carried: new input, read from the cache, written to the cache.
+const context = (request: Json | undefined) => (request ? request.input + request.cacheRead + request.cacheWrite : null);
+// Calibrated on Claude's own output (docs/v0.10/plan.md, gate 6): a Han character ~1.3 tokens, any other ~0.45.
+const listTokens = (list: Json | null) => (list ? Math.round(list.han * 1.3 + (list.chars - list.han) * 0.45) : null);
+const strip = (text: string) => text.replace(/[A-Za-z]:\\[^\s"'))]*|\/(?:Users|home|tmp)\/[^\s"'))]*/g, "<path>");
+
+function summarize(run: Json): Json {
+ const steps: Json[] = run.steps;
+ const questions = steps.filter((step) => step.kind === "question");
+ const block = (prefix: string) => {
+ const mine = questions.filter((step) => step.step.startsWith(prefix));
+ return { asked: mine.length, right: mine.filter((step) => step.verdict === "right").length, wrong: mine.filter((step) => step.verdict === "wrong").length, none: mine.filter((step) => step.verdict === "none").length };
+ };
+ const turns = steps.filter((step) => step.kind === "turn");
+ const requests = steps.flatMap((step) => step.requests as Json[]);
+ // The first request after each compaction: the next step's first.
+ const afterCompaction = steps.flatMap((step, at) => (step.kind === "compact" ? [{ compaction: step.step, tokens: context(steps[at + 1]?.requests?.[0]) }] : []));
+ // Lists the engine put back, in order: the first after each compaction.
+ const lists = ((run.engine as Json[] | undefined) ?? []).filter((entry) => entry.list);
+ const firstLists: Json[] = [];
+ for (const entry of lists) if (!firstLists.some((seen) => seen.compacted.listed === entry.compacted.listed && seen.session === entry.session)) firstLists.push(entry);
+ const featureLines = new Set(turns.flatMap((step) => [...String(step.reply).matchAll(/\[\/\/\]:\s*#\s*\(cam (IMG-\d+)/g)].map((match) => match[1])));
+ return {
+ run: run.file, arm: run.arm, model: run.model, effort: run.effort, images: run.images, startedAt: run.startedAt, finishedAt: run.finishedAt,
+ turnsDone: turns.length, turnsFailed: turns.filter((step) => step.timedOut || step.error).length,
+ questions: { mid: block("M"), end: block("Q"), fork: block("K"), all: block("") },
+ fetches: { calls: questions.reduce((sum, step) => sum + step.fetchCalls.length, 0), images: questions.reduce((sum, step) => sum + step.fetched.length, 0), reads: questions.reduce((sum, step) => sum + step.reads.length, 0) },
+ featureLines: featureLines.size, costUsd: costOf(run),
+ // Images the model read in each turn (a turn that names files and reads none did not look at them).
+ turnReads: turns.map((step) => step.reads.length),
+ tokens: { requests: requests.length, input: requests.reduce((sum, r) => sum + r.input, 0), cacheRead: requests.reduce((sum, r) => sum + r.cacheRead, 0), cacheWrite: requests.reduce((sum, r) => sum + r.cacheWrite, 0), output: requests.reduce((sum, r) => sum + r.output, 0), largest: Math.max(0, ...requests.map((r) => context(r) ?? 0)) },
+ afterCompaction: afterCompaction.map((item, at) => {
+ const list = firstLists[at] ?? null;
+ const tokens = listTokens(list?.list ?? null);
+ return { ...item, listed: list?.compacted?.listed ?? null, listTokens: tokens, listShare: tokens && item.tokens ? Math.round((tokens / item.tokens) * 1000) / 10 : null };
+ }),
+ answers: questions.map((step) => ({ q: step.step, verdict: step.verdict, said: step.said, expected: step.expected, needsOriginal: step.needsOriginal, fetched: step.fetched, reads: step.reads.length, seconds: Math.round(step.ms / 1000), reply: strip(String(step.reply)).slice(0, 600) })),
+ };
+}
+
+const summary = runs.map(summarize).sort((a, b) => a.run.localeCompare(b.run));
+for (const run of summary) {
+ console.log(`\n== ${run.run}: ${run.images} images, ${run.turnsDone} turns (${run.turnsFailed} failed), ${run.featureLines} feature lines`);
+ console.table({ mid: run.questions.mid, end: run.questions.end, fork: run.questions.fork, all: run.questions.all });
+ console.log("fetches", run.fetches, "tokens", run.tokens);
+ console.table(run.afterCompaction);
+ console.table(run.answers.map(({ reply, ...rest }: Json) => ({ ...rest, fetched: rest.fetched.join(",") })));
+}
+if (out) {
+ mkdirSync(out, { recursive: true });
+ writeFileSync(join(out, "summary.json"), JSON.stringify(summary, null, 2));
+ console.log(`\nwrote ${join(out, "summary.json")}`);
+}
diff --git a/spike/src/eval-long.ts b/spike/src/eval-long.ts
new file mode 100644
index 0000000..0af4313
--- /dev/null
+++ b/spike/src/eval-long.ts
@@ -0,0 +1,313 @@
+// Purpose: eval — a long keyframe task in Claude Code, with and without the plugin. The scene, the
+// questions and the scoring are in eval-long-scene.ts; the plugin copies, the engine and the eval's own Claude Code
+// configuration in eval-long-setup.ts.
+// One run: one arm (no plugin, v0.9.1, v0.10) with one model. Claude Code's command line runs as Claude Desktop
+// runs it: one process per session, messages in and events out as JSON lines. Each turn says which images to look at
+// (the model reads them with Read, as it looks at what a tool made) or sends sketches with the message. At two points
+// the session is compacted (/compact, as a user types it; automatic compaction is off so every arm compacts at the same
+// place) and questions follow; at the end the session is forked (--resume … --fork-session, a new session that carries
+// the old one's history, as Claude Desktop does when an earlier message is edited) and a few more are asked there.
+// Only Read and cam_view_image are allowed; the folder the model works in is outside this repository, so no CLAUDE.md
+// of ours reaches it.
+// Input: [--label name] [--runs arm/model,…] [--parallel 3] [--port 17931] [--effort low] [--stop-at 0.9]
+// [--draw] [--quick];
+// CAM_CLAUDE_BIN (default: claude on PATH). Output: local/eval-long/<label>/<run>.json and a console summary.
+// Needs the eval's configuration signed in once (eval-long-setup.ts).
+
+import { spawn, type ChildProcess } from "node:child_process";
+import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, appendFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { setTimeout as sleep } from "node:timers/promises";
+import { draw, scene, score, type Image, type Question, type Step } from "./eval-long-scene.ts";
+import { claudeConfigDir, evalRoot, preparePlugin, startEngine, type Arm } from "./eval-long-setup.ts";
+
+type Json = Record<string, any>;
+const MODELS: Record<string, string> = { sonnet: "claude-sonnet-5-5", haiku: "claude-haiku-5-5" };
+const FETCH_TOOL = "mcp__plugin_codex-attachment-manager_codex_attachment_manager__cam_view_image";
+const TURN_TIMEOUT = 15 * 60_000;
+const QUESTION_TIMEOUT = 6 * 60_000;
+type Run = { arm: Arm; model: string; name: string };
+// The account's usage as Claude Code last reported it (rate_limit_event): a run stops before its next step once the
+// weekly share reaches --stop-at, so the eval never uses up the account it runs on.
+// Near the end of the five-hour window it waits for the window to start again instead.
+const quota = { fiveHour: null as number | null, weekly: null as number | null, fiveHourResets: null as number | null };
+let stopAt = 0.9;
+const overQuota = () => quota.weekly !== null && quota.weekly >= stopAt;
+async function waitForWindow(note: (step: Json) => void, refused = false): Promise<void> {
+ if (!refused && (quota.fiveHour === null || quota.fiveHour < 0.95)) return;
+ const until = (quota.fiveHourResets ?? Date.now() / 1000 + 15 * 60) * 1000 + 60_000;
+ note({ step: "paused", kind: "paused", reason: `five-hour usage ${quota.fiveHour}${refused ? ", a request refused" : ""}`, until: new Date(until).toISOString() });
+ await sleep(Math.max(0, until - Date.now()));
+ quota.fiveHour = 0;
+}
+
+// ---- Images ----
+
+// Drawn once into a folder of their own, then copied into each run's working folder.
+const imageDir = join(tmpdir(), "cam-eval-long", "images");
+function drawImages(): Image[] {
+ const { images } = scene();
+ mkdirSync(imageDir, { recursive: true });
+ for (const image of images) {
+ const file = join(imageDir, "file" in image ? image.file : `${image.key}.png`);
+ if (!existsSync(file)) writeFileSync(file, draw(image, images));
+ }
+ return images;
+}
+
+// ---- A Claude Code session ----
+
+class Session {
+ readonly child: ChildProcess;
+ private buffer = "";
+ readonly events: Json[] = [];
+ sessionId: string | null = null;
+ private waiting: ((event: Json) => void) | null = null;
+ exited: number | null = null;
+ private log: string;
+
+ constructor(args: string[], env: NodeJS.ProcessEnv, cwd: string, log: string) {
+ this.log = log;
+ this.child = spawn(process.env.CAM_CLAUDE_BIN || "claude", args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
+ this.child.stdout!.setEncoding("utf8");
+ this.child.stdout!.on("data", (chunk: string) => {
+ this.buffer += chunk;
+ for (let at = this.buffer.indexOf("\n"); at >= 0; at = this.buffer.indexOf("\n")) {
+ const line = this.buffer.slice(0, at).trim();
+ this.buffer = this.buffer.slice(at + 1);
+ if (!line) continue;
+ let event: Json;
+ try { event = JSON.parse(line); } catch { appendFileSync(this.log, `?? ${line.slice(0, 500)}\n`); continue; }
+ // Image data stays out of the log.
+ appendFileSync(this.log, `${JSON.stringify(event, (key, value) => (key === "data" && typeof value === "string" && value.length > 200 ? `<${value.length} chars>` : value))}\n`);
+ if (event.session_id) this.sessionId = event.session_id;
+ const windows = event.type === "rate_limit_event" ? event.rate_limit_info?.unifiedWindows : null;
+ if (windows) {
+ quota.fiveHour = windows.five_hour?.utilization ?? quota.fiveHour;
+ quota.fiveHourResets = windows.five_hour?.resetsAt ?? quota.fiveHourResets;
+ quota.weekly = windows.seven_day?.utilization ?? quota.weekly;
+ }
+ this.events.push(event);
+ if (event.type === "result" && this.waiting) { const done = this.waiting; this.waiting = null; done(event); }
+ }
+ });
+ this.child.stderr!.setEncoding("utf8");
+ this.child.stderr!.on("data", (chunk: string) => appendFileSync(this.log, `stderr ${chunk}`));
+ this.child.on("exit", (code) => {
+ this.exited = code ?? -1;
+ if (this.waiting) { const done = this.waiting; this.waiting = null; done({ type: "exit", code }); }
+ });
+ }
+
+ // One user message; resolves with the turn's events once Claude Code reports the turn's result.
+ async send(content: Json[], timeoutMs: number): Promise<{ events: Json[]; result: Json | null; ms: number; timedOut: boolean }> {
+ const from = this.events.length;
+ const started = Date.now();
+ if (this.exited !== null) return { events: [], result: null, ms: 0, timedOut: false };
+ const done = new Promise<Json>((resolve) => { this.waiting = resolve; });
+ this.child.stdin!.write(`${JSON.stringify({ type: "user", message: { role: "user", content } })}\n`);
+ let timer: NodeJS.Timeout | undefined;
+ const timeout = new Promise<null>((resolve) => { timer = setTimeout(() => resolve(null), timeoutMs); });
+ const result = await Promise.race([done, timeout]);
+ clearTimeout(timer);
+ if (result === null) this.waiting = null;
+ return { events: this.events.slice(from), result: result?.type === "result" ? result : null, ms: Date.now() - started, timedOut: result === null };
+ }
+
+ async close(): Promise<void> {
+ if (this.exited !== null) return;
+ this.child.stdin!.end();
+ await new Promise<void>((resolve) => {
+ const timer = setTimeout(() => { this.child.kill(); resolve(); }, 30_000);
+ this.child.on("exit", () => { clearTimeout(timer); resolve(); });
+ });
+ }
+}
+
+// ---- What a turn cost and did ----
+
+const blocksOf = (event: Json): Json[] => (Array.isArray(event.message?.content) ? event.message.content : []);
+
+function turnOf(events: Json[]): Json {
+ // One API response can come as several assistant events (one per content block): count it once.
+ const requests = new Map<string, Json>();
+ const reads: string[] = [];
+ const fetchCalls: string[][] = [];
+ const fetchCallIds = new Set<string>();
+ const fetched: string[] = [];
+ let compacted = false;
+ for (const event of events) {
+ if (event.type === "system" && event.subtype === "compact_boundary") compacted = true;
+ if (event.type === "assistant") {
+ const usage = event.message?.usage;
+ if (usage && event.message?.id) requests.set(event.message.id, { input: usage.input_tokens ?? 0, cacheRead: usage.cache_read_input_tokens ?? 0, cacheWrite: usage.cache_creation_input_tokens ?? 0, output: usage.output_tokens ?? 0 });
+ for (const block of blocksOf(event)) {
+ if (block.type !== "tool_use") continue;
+ if (block.name === "Read") reads.push(String(block.input?.file_path ?? "").split(/[\\/]/).pop() ?? "");
+ else if (String(block.name).endsWith("__cam_view_image")) { fetchCalls.push(([] as unknown[]).concat(block.input?.ids ?? block.input?.id ?? []).map(String)); fetchCallIds.add(block.id); }
+ }
+ }
+ if (event.type === "user") {
+ for (const block of blocksOf(event)) {
+ if (block.type !== "tool_result" || !fetchCallIds.has(block.tool_use_id)) continue;
+ const texts = (Array.isArray(block.content) ? block.content : [{ type: "text", text: String(block.content ?? "") }]).filter((part: Json) => part.type === "text").map((part: Json) => part.text);
+ for (const text of texts) for (const match of text.matchAll(/[\w-]+\.png/g)) fetched.push(match[0]);
+ }
+ }
+ }
+ return { requests: [...requests.values()], reads, fetchCalls, fetched: [...new Set(fetched)], compacted };
+}
+
+// ---- One run ----
+
+// quick (to check the harness): the first three turns, the first compaction, four questions about those turns' images,
+// then the fork and one of them again.
+const QUICK = ["M1", "M3", "Q2", "Q7"];
+async function runOne(run: Run, label: string, port: number, effort: string, quick = false): Promise<Json> {
+ const { arm, model } = run;
+ const root = join(evalRoot, label);
+ const runDir = join(root, run.name);
+ mkdirSync(runDir, { recursive: true });
+ const images = drawImages();
+ const full = scene();
+ const steps: Step[] = quick ? [...full.steps.filter((step) => step.type === "turn").slice(0, 3), { type: "compact", label: "mid" }, { type: "ask", block: "mid" }, { type: "ask", block: "fork" }] : full.steps;
+ const picked = full.questions.filter((question) => QUICK.includes(question.key));
+ const questions: Question[] = quick ? [...picked.map((question) => ({ ...question, block: "mid" as const })), { ...picked.at(-1)!, key: `K-${picked.at(-1)!.key}`, block: "fork" }] : full.questions;
+ const work = join(tmpdir(), "cam-eval-long", label, run.name);
+ mkdirSync(work, { recursive: true });
+ for (const image of images) if ("file" in image) cpSync(join(imageDir, image.file), join(work, image.file));
+ const upload = (key: string) => {
+ const image = images.find((candidate) => candidate.key === key)!;
+ return { type: "image", source: { type: "base64", media_type: "image/png", data: readFileSync(join(imageDir, "file" in image ? image.file : `${image.key}.png`)).toString("base64") } };
+ };
+
+ let engine: ChildProcess | null = null;
+ let plugin: string | null = null;
+ const data = join(runDir, "data");
+ if (arm !== "off") {
+ plugin = preparePlugin(arm, port, data);
+ engine = await startEngine(plugin, port, data);
+ }
+ // This process may itself run inside Claude Code: none of its session's variables (its engine's URL included) go on.
+ const env: NodeJS.ProcessEnv = Object.fromEntries(Object.entries(process.env).filter(([name]) => !/^(CLAUDE|ANTHROPIC)/i.test(name)));
+ Object.assign(env, { CLAUDE_CONFIG_DIR: claudeConfigDir, DISABLE_AUTO_COMPACT: "1" });
+ const args = (resume: string[] = []) => [
+ "-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose",
+ "--model", MODELS[model], "--effort", effort, "--tools", "Read", "--allowedTools", "Read", FETCH_TOOL,
+ ...(plugin ? ["--plugin-dir", plugin] : []), ...resume,
+ ];
+ const result: Json = { run: run.name, arm, model: MODELS[model], effort, images: images.length, startedAt: new Date().toISOString(), steps: [] };
+ let session = new Session(args(), env, work, join(runDir, "events-main.jsonl"));
+ const record = (step: Json) => { result.steps.push(step); writeFileSync(join(root, `${run.name}.json`), JSON.stringify(result, null, 2)); };
+ const ask = async (question: Question) => {
+ const sent = await session.send([{ type: "text", text: question.say }], QUESTION_TIMEOUT);
+ const reply = sent.result?.result ?? "";
+ record({ step: question.key, kind: "question", ms: sent.ms, timedOut: sent.timedOut, error: sent.result?.is_error ?? null, reply, ...score(question, reply), expected: question.answer, target: question.target, needsOriginal: question.needsOriginal, ...turnOf(sent.events) });
+ return sent.result !== null;
+ };
+
+ result.quotaAtStart = { ...quota };
+ try {
+ let turnNo = 0;
+ for (const step of steps) {
+ if (overQuota()) { record({ step: "stopped", kind: "stopped", reason: `weekly usage ${quota.weekly} ≥ ${stopAt}` }); break; }
+ await waitForWindow(record);
+ if (step.type === "turn") {
+ turnNo++;
+ const content = [{ type: "text", text: step.say }, ...step.upload.map(upload)];
+ let sent = await session.send(content, TURN_TIMEOUT);
+ // Refused for the account's limit: the same turn again once the window has started again.
+ if (sent.result?.is_error && /limit/i.test(String(sent.result.result))) { await waitForWindow(record, true); sent = await session.send(content, TURN_TIMEOUT); }
+ record({ step: `T${turnNo}`, kind: "turn", ms: sent.ms, timedOut: sent.timedOut, error: sent.result?.is_error ?? null, reply: sent.result?.result ?? "", ...turnOf(sent.events) });
+ if (!sent.result) break;
+ } else if (step.type === "compact") {
+ const sent = await session.send([{ type: "text", text: "/compact" }], TURN_TIMEOUT);
+ record({ step: `compact-${step.label}`, kind: "compact", ms: sent.ms, timedOut: sent.timedOut, error: sent.result?.is_error ?? null, ...turnOf(sent.events) });
+ if (!sent.result) break;
+ } else if (step.block === "fork") {
+ const from = session.sessionId;
+ await session.close();
+ if (!from) break;
+ session = new Session(args(["--resume", from, "--fork-session"]), env, work, join(runDir, "events-fork.jsonl"));
+ result.forkedFrom = from;
+ for (const question of questions.filter((candidate) => candidate.block === "fork")) if (!(await ask(question))) break;
+ result.forkSession = session.sessionId;
+ } else {
+ let alive = true;
+ for (const question of questions.filter((candidate) => candidate.block === step.block)) if (!(alive = await ask(question))) break;
+ if (!alive) break;
+ }
+ if (!result.session) result.session = session.sessionId;
+ }
+ } finally {
+ await session.close();
+ engine?.kill();
+ }
+ result.finishedAt = new Date().toISOString();
+ result.quotaAtEnd = { ...quota };
+ if (arm !== "off") result.engine = engineRequests(data, [result.session, result.forkSession].filter(Boolean));
+ writeFileSync(join(root, `${run.name}.json`), JSON.stringify(result, null, 2));
+ return result;
+}
+
+// The main-loop requests as the engine logged them, and for those after a compaction, how long the list it put back
+// was (from the request as sent, which stays in the local data folder).
+function engineRequests(data: string, sessions: string[]): Json[] {
+ const dir = join(data, "proxy");
+ if (!existsSync(dir)) return [];
+ const entries = readdirSync(dir).filter((name) => name.endsWith(".jsonl")).flatMap((name) => readFileSync(join(dir, name), "utf8").split("\n"))
+ .flatMap((line) => { try { return [JSON.parse(line)]; } catch { return []; } })
+ .filter((entry) => entry.kind === "messages" && sessions.includes(entry.claudeSessionId) && entry.tools > 0);
+ const dumps = join(data, "p2", "requests");
+ return entries.map((entry) => {
+ let list: Json | null = null;
+ if (entry.rewrite?.compacted) {
+ const sent = join(dumps, readdirSync(dumps).find((name) => name.endsWith(`-${entry.id}.sent.json`)) ?? "-");
+ if (existsSync(sent)) {
+ const dump = JSON.parse(readFileSync(sent, "utf8"));
+ const body = typeof dump.body === "string" ? JSON.parse(dump.body) : dump.body ?? dump;
+ const texts = (body.messages ?? []).flatMap((message: Json) => (Array.isArray(message.content) ? message.content : [])).filter((block: Json) => block.type === "text").map((block: Json) => String(block.text));
+ const text = texts.find((candidate: string) => candidate.includes("压缩之前的图片")) ?? null;
+ if (text) list = { chars: text.length, han: (text.match(/[一-鿿]/g) ?? []).length, lines: text.split("\n").length };
+ }
+ }
+ return { at: entry.at, session: entry.claudeSessionId, status: entry.status, bytes: entry.decodedBytes, images: entry.images, sent: entry.rewrite ? entry.images - (entry.rewrite.replaced?.length ?? 0) : entry.images, compacted: entry.rewrite?.compacted ?? null, list };
+ });
+}
+
+function summarize(result: Json): void {
+ const questions = (result.steps as Json[]).filter((step) => step.kind === "question");
+ const right = questions.filter((step) => step.verdict === "right").length;
+ console.log(`\n== ${result.run} (${result.model}, ${result.effort}, ${result.images} images): ${right}/${questions.length} right`);
+ console.table(questions.map((step) => ({ q: step.step, verdict: step.verdict, said: step.said, expected: step.expected, fetched: step.fetched.join(","), reads: step.reads.length, s: Math.round(step.ms / 1000) })));
+}
+
+async function main(): Promise<void> {
+ const option = (name: string, fallback: string) => (process.argv.includes(name) ? process.argv[process.argv.indexOf(name) + 1] : fallback);
+ const label = option("--label", "run1");
+ const effort = option("--effort", "low");
+ const port = Number(option("--port", "17931"));
+ const parallel = Number(option("--parallel", "3"));
+ stopAt = Number(option("--stop-at", "0.9"));
+ const defaults = ["off/haiku", "v0.9.1/haiku", "v0.10/haiku"];
+ const runs: Run[] = option("--runs", defaults.join(",")).split(",").map((spec) => {
+ const [arm, model] = spec.split("/");
+ if (!["off", "v0.9.1", "v0.10"].includes(arm) || !MODELS[model]) throw new Error(`bad run ${spec}`);
+ return { arm: arm as Arm, model, name: `${arm}-${model}` };
+ });
+ console.log(`${drawImages().length} images in ${imageDir}`);
+ if (process.argv.includes("--draw")) return;
+ // Each run its own engine; ports two apart (an engine also takes the next port for its routes).
+ let next = 0;
+ const worker = async () => {
+ for (let at = next++; at < runs.length && !overQuota(); at = next++) {
+ // A run that fails is reported; the others go on.
+ try { summarize(await runOne(runs[at], label, port + at * 2, effort, process.argv.includes("--quick"))); }
+ catch (error) { console.error(`\n== ${runs[at].name} failed: ${(error as Error).stack ?? error}`); }
+ }
+ };
+ await Promise.all(Array.from({ length: Math.min(parallel, runs.length) }, worker));
+}
+
+await main();