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.
TypeScript ai-agentsclaude-codeclaude-code-plugincodexcodex-plugincontext-managementdeveloper-toolsimage-generationmcpmultimodal
feat(claude): 账号拒绝改过历史后的思考时,去掉对不上的思考记录再发(实验中)
chipfighterf0552ae2165e
diff --git a/plugin/src/claude-thinking.ts b/plugin/src/claude-thinking.tsnew file mode 100644index 0000000..6bfcdc4--- /dev/null+++ b/plugin/src/claude-thinking.ts@@ -0,0 +1,100 @@+// Purpose: v0.4 — keep the thinking in a Claude Code request valid when the engine has changed the history before it.+// Anthropic binds each thinking block to everything before it in the conversation (Fable 5.1, Opus 5.5, Sonnet 5.5,+// Haiku 5.5); accounts created from 2026-08-31 refuse a request whose thinking no longer matches, older ones let it+// through (docs/v0.4/plan.md §2). Thinking may be left out, as long as each block kept comes after exactly what it was+// made after. So the engine remembers, per session, what it sent for each history it saw (as hash chains), and keeps a+// thinking block only when what comes before it now is what was sent when the block was made.+// Input: a request's messages as Claude Code built them and as the engine will send them; the session's record.+// Output: the messages without the thinking that no longer fits, counts, and the chains to remember;+// <data dir>/claude/thinking/<session>.json (whether the account refuses such thinking, and hashes; never content).++import { createHash } from "node:crypto";+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { claudeThinkingDirOf } from "./paths.ts";++type Json = Record<string, any>;+const THINKING = new Set(["thinking", "redacted_thinking"]);+const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;+// Hashes of the latest histories only: a block is made after the history of the request just before it.+const KEEP = 2000;++// Cache breakpoints move from request to request; thinking is not bound to them.+const withoutBreakpoints = (key: string, value: unknown) => (key === "cache_control" ? undefined : value);+export const link = (previous: string, message: Json): string =>+ createHash("sha256").update(previous).update("\n").update(JSON.stringify(message, withoutBreakpoints) ?? "").digest("hex");+export const chainOf = (messages: Json[]): string => messages.reduce((chain: string, message) => link(chain, message), "");++const thinkingIn = (message: Json): number =>+ message?.role === "assistant" && Array.isArray(message.content) ? message.content.filter((block: Json) => THINKING.has(block?.type)).length : 0;++export type ThinkingFit = { messages: Json[]; kept: number; left: number; history: string; sent: string };++// sent: for each history the engine changed, the chain of what it sent instead. A history it never changed went out as+// it was. The rewrite never adds, drops or edits an assistant message, so the n-th one of each list is the same.+export function fitThinking(original: Json[], outgoing: Json[], sent: ReadonlyMap<string, string>): ThinkingFit {+ const madeAfter: string[] = [];+ let history = "";+ for (const message of original) {+ if (message?.role === "assistant") madeAfter.push(history);+ history = link(history, message);+ }+ let chain = "";+ let assistant = 0;+ let kept = 0;+ let left = 0;+ const messages = outgoing.map((message) => {+ let next = message;+ if (message?.role === "assistant") {+ const made = madeAfter[assistant++];+ const count = thinkingIn(message);+ if (count) {+ const rest = message.content.filter((block: Json) => !THINKING.has(block?.type));+ // A message of thinking alone stays: Anthropic takes no empty message (the request may then be refused).+ if (made === undefined || (sent.get(made) ?? made) === chain || !rest.length) kept += count;+ else {+ left += count;+ next = { ...message, content: rest };+ }+ }+ }+ chain = link(chain, next);+ return next;+ });+ return { messages, kept, left, history, sent: chain };+}++// strict: Anthropic refused this session's thinking after an edited history once (the account checks it).+export type ThinkingRecord = { strict: boolean; sent: Map<string, string> };++export function readThinkingRecord(sessionId: string, dir = claudeThinkingDirOf()): ThinkingRecord {+ const empty: ThinkingRecord = { strict: false, sent: new Map() };+ if (!SESSION_ID.test(sessionId)) return empty;+ const file = join(dir, `${sessionId}.json`);+ if (!existsSync(file)) return empty;+ try {+ const json = JSON.parse(readFileSync(file, "utf8"));+ const pairs = Array.isArray(json.sent) ? json.sent.filter((pair: unknown) => Array.isArray(pair) && pair.length === 2 && pair.every((hash) => typeof hash === "string")) : [];+ return { strict: json.strict === true, sent: new Map(pairs) };+ } catch {+ return empty;+ }+}++export function writeThinkingRecord(sessionId: string, record: ThinkingRecord, dir = claudeThinkingDirOf()): void {+ if (!SESSION_ID.test(sessionId)) return;+ mkdirSync(dir, { recursive: true });+ const file = join(dir, `${sessionId}.json`);+ writeFileSync(`${file}.tmp`, JSON.stringify({ strict: record.strict, sent: [...record.sent] }));+ renameSync(`${file}.tmp`, file);+}++// What went out for a history: a changed one is remembered (latest last), one sent as it was needs no entry.+export function rememberSent(record: ThinkingRecord, history: string, sent: string): void {+ record.sent.delete(history);+ if (sent !== history) record.sent.set(history, sent);+ for (const key of record.sent.keys()) {+ if (record.sent.size <= KEEP) break;+ record.sent.delete(key);+ }+}diff --git a/plugin/src/paths.ts b/plugin/src/paths.tsindex 4233137..a86cb90 100644--- a/plugin/src/paths.ts+++ b/plugin/src/paths.ts@@ -26,6 +26,8 @@ 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).+export const claudeThinkingDirOf = (root = dataDir()) => join(root, "claude", "thinking");export const requestStatsDirOf = (root = dataDir()) => join(root, "state", "requests");export const proxyLogDirOf = (root = dataDir()) => join(root, "proxy");export const bindingsDirOf = (root = dataDir()) => join(root, "bindings");diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.tsindex 3bb4621..aa51206 100644--- a/plugin/src/proxy.ts+++ b/plugin/src/proxy.ts@@ -27,6 +27,7 @@ import { fileURLToPath } from "node:url";import zlib from "node:zlib";import { claudeHome, loadClaudeIndex, type ClaudeIndex } from "./claude-index.ts";import { findRequestImages, rewriteMessages, type RequestImage } from "./claude-rewrite.ts";+import { chainOf, fitThinking, readThinkingRecord, rememberSent, writeThinkingRecord, type ThinkingRecord } from "./claude-thinking.ts";import { codexHome } from "./codexconfig.ts";import { buildOf, DEFAULT_PORT, ENGINE_SERVICE, engineHealth, versionOf, watchForCodex } from "./engine.ts";import { findImages, type ImageRef } from "./images.ts";@@ -322,20 +323,27 @@ export function thinkingRejected(status: number, body: string): boolean {return status === 400 && /thinking/i.test(body) && /signature|bound to a different conversation|prefix/i.test(body);}+// v0.4: what to send for a Claude Code request, in order: the rewrite; if Anthropic refuses the thinking after the+// changed history (thinkingRejected), the rewrite without the thinking that no longer fits (claude-thinking.ts); then+// the original. Once a session's account refused such thinking (thinking.strict), the rewrite goes without it from the+// start. history/sent: the chains to remember once an attempt goes through.+export type ClaudeAttempt = { body: Buffer; report: Json; history: string | null; sent: string | null };+// v0.4: the same rules as rewriteBody, for a Claude Code request (Anthropic Messages, claude-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.-export function rewriteClaudeBody(original: Buffer, encoding: string | undefined, sessionId: string, dir = claudeSelectionDirOf(), home = claudeHome(), env = process.env): { body: Buffer; report: Json } {+export function rewriteClaudeBody(original: Buffer, encoding: string | undefined, sessionId: string, dir = claudeSelectionDirOf(), home = claudeHome(), env = process.env, thinking: ThinkingRecord | null = null): { body: Buffer; report: Json; attempts: ClaudeAttempt[] } {+ const asIs = (report: Json) => ({ body: original, report, attempts: [] });const decoded = decodeBody(original, encoding);- if (!decoded) return { body: original, report: { skipped: "undecodable body" } };+ if (!decoded) return asIs({ skipped: "undecodable body" });const text = decoded.toString("utf8");let json: Json;- try { json = JSON.parse(text); } catch { return { body: original, report: { skipped: "unparsable body" } }; }- if (!Array.isArray(json.messages)) return { body: original, report: { skipped: "no messages array" } };- if (hasUnsafeInteger(text)) return { body: original, report: { skipped: "integer beyond 2^53 would change when re-serialized" } };+ try { json = JSON.parse(text); } catch { return asIs({ skipped: "unparsable body" }); }+ if (!Array.isArray(json.messages)) return asIs({ skipped: "no messages array" });+ if (hasUnsafeInteger(text)) return asIs({ skipped: "integer beyond 2^53 would change when re-serialized" });let index: ClaudeIndex;- try { index = loadClaudeIndex(sessionId, home); } catch (error) { return { body: original, report: { skipped: `thread index: ${String(error)}` } }; }+ try { index = loadClaudeIndex(sessionId, home); } catch (error) { return asIs({ skipped: `thread index: ${String(error)}` }); }const selection = readSelection(sessionId, dir);const current = index.turns;const copies = new Map([...index.copies.values()].filter((copy) => copy.turn === null || copy.turn < current).map((copy) => [copy.key, copy.of]));@@ -356,16 +364,25 @@ export function rewriteClaudeBody(original: Buffer, encoding: string | undefined...(selection.auto ? { auto: true } : {}),...(report.copies.length ? { copies: report.copies } : {}),};- if (!report.replaced.length && !report.copies.length) return { body: original, report: summary };- json.messages = messages;+ const changed = report.replaced.length > 0 || report.copies.length > 0;+ const rewritten = changed ? messages : json.messages;+ // Thinking made after an earlier edit may not fit even when nothing is left out now (an image checked again).+ const fit = thinking ? fitThinking(json.messages, rewritten, thinking.sent) : null;+ if (!changed && !(thinking?.strict && fit?.left)) return { body: original, report: summary, attempts: [] };const experiment = env.CAM_EXPERIMENT_BLOCK_BINDING?.trim();- if (experiment && json.thinking && typeof json.thinking === "object") {- json.thinking = { ...json.thinking, block_binding: { prefix_mismatch_behavior: experiment } };- summary.experiment = { blockBinding: experiment, beta: "thinking-binding-controls-2026-08-01" };- }- const next = Buffer.from(JSON.stringify(json), "utf8");- const body = encodeBody(next, encoding);- return { body, report: { ...summary, decodedBefore: decoded.length, decodedAfter: next.length, encodedBefore: original.length, encodedAfter: body.length } };+ const encode = (list: Json[], extra: Json) => {+ const out: Json = { ...json, messages: list };+ const asked = experiment && json.thinking && typeof json.thinking === "object";+ if (asked) out.thinking = { ...json.thinking, block_binding: { prefix_mismatch_behavior: experiment } };+ const next = Buffer.from(JSON.stringify(out), "utf8");+ const body = encodeBody(next, encoding);+ return { body, report: { ...summary, ...extra, ...(asked ? { experiment: { blockBinding: experiment, beta: "thinking-binding-controls-2026-08-01" } } : {}), decodedBefore: decoded.length, decodedAfter: next.length, encodedBefore: original.length, encodedAfter: body.length } };+ };+ const attempts: ClaudeAttempt[] = [];+ if (!thinking?.strict) attempts.push({ ...encode(rewritten, {}), history: fit?.history ?? null, sent: fit ? (fit.left ? chainOf(rewritten) : fit.sent) : null });+ if (fit && (thinking?.strict || fit.left)) attempts.push({ ...encode(fit.messages, { thinking: { kept: fit.kept, left: fit.left }, ...(thinking?.strict ? {} : { retry: "thinking-signature" }) }), history: fit.history, sent: fit.sent });+ attempts.push({ body: original, report: { ...summary, fallback: "thinking-signature" }, history: fit?.history ?? null, sent: fit?.history ?? null });+ return { body: attempts[0].body, report: attempts[0].report, attempts };}// v0.4: a Claude Code session's panel reads and changes its images here: the panel page the engine serves@@ -442,6 +459,16 @@ async function main(): Promise<void> {const build = buildOf();const version = versionOf();let sequence = 0;+ // 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.+ const thinkingRecords = new Map<string, ThinkingRecord>();+ const thinkingOf = (sessionId: string): ThinkingRecord => {+ const record = thinkingRecords.get(sessionId) ?? readThinkingRecord(sessionId);+ thinkingRecords.delete(sessionId);+ thinkingRecords.set(sessionId, record);+ for (const key of thinkingRecords.keys()) if (thinkingRecords.size > 50) thinkingRecords.delete(key);+ return record;+ };log({ at: startedAt, event: "engine-start", pid: process.pid, port, build, version });if (!process.argv.includes("--stay")) {// v0.1-5: a plugin removed or turned off without 停用 leaves Codex pointed at an engine nothing will start again.@@ -566,7 +593,10 @@ async function main(): Promise<void> {// Codex thread's once something is unchecked there.const claude = upstream === CLAUDE_HOST ? claudeIdentity(req.headers) : null;const claudeSession = claude?.sessionId && !claude.agentId && req.method === "POST" && path === "/v1/messages" ? claude.sessionId : null;- const claudeRewrite = claudeNeedsRewrite(claudeSession);+ // Once the session's account refused thinking after a changed history, every request of it is looked at, even with+ // nothing left out now: thinking made after an edited history no longer fits the history as it was.+ const thinking = claudeSession ? thinkingOf(claudeSession) : null;+ const claudeRewrite = claudeNeedsRewrite(claudeSession) || !!(thinking?.strict && thinking.sent.size);const claudeFields = claude ? { claudeSessionId: claude.sessionId, claudeAgentId: claude.agentId } : {};const chunks: Buffer[] = [];let requestBytes = 0;@@ -576,6 +606,7 @@ async function main(): Promise<void> {let extra: Json = {};// Synthetic test threads only (--dump-requests): the body as the engine sent it, after a rewrite.let sentBody: Buffer | null = null;+ const dumpName = (suffix: string) => join(dumpDir!, `${new Date(started).toISOString().replaceAll(":", "-")}-${id}${suffix}`);const collect = () => req.on("data", (chunk: Buffer) => { chunks.push(chunk); requestBytes += chunk.length; });const finish = (error?: string) => {if (finished) return;@@ -605,16 +636,24 @@ async function main(): Promise<void> {if (/\/responses$/.test(path)) recordRequest(identity.threadId, imageSizes ? { ...entry, imageSizes } : entry);if (claudeSession && claudeConversationRequest(details)) recordRequest(claudeSession, imageSizes ? { ...entry, imageSizes } : entry, claudeRequestStatsDirOf());};- // body === null streams the request through unchanged. v0.4: with `fallback` (the original body of a rewritten- // Claude Code request), Anthropic refusing the rewritten history under its thinking (thinkingRejected) sends the- // original instead: the request goes out as Claude Code built it, and the statistics say why (the panel shows it).- const send = (headers: Record<string, string | string[]>, body: Buffer | null, fallback: Buffer | null = null) => connectUpstream(viaOf(upstream), upstream).then((socket) => {+ // What to send, in order: body null streams the request through unchanged. v0.4: Anthropic refusing an attempt's+ // thinking after the changed history (thinkingRejected) moves on to the next one (see ClaudeAttempt), the last being+ // the original as Claude Code built it; the statistics say which went out (the panel shows a fallback).+ type Attempt = { body: Buffer | null; report: Json | null; edited: boolean; history?: string | null; sent?: string | null };+ const send = (attempts: Attempt[], at = 0): void => { connectUpstream(viaOf(upstream), upstream).then((socket) => {+ const attempt = attempts[at];+ const outgoing = forwardHeaders(req.headers, upstream);+ if (attempt.body) outgoing["content-length"] = String(attempt.body.length);+ const beta = attempt.report?.experiment?.beta;+ if (beta) outgoing["anthropic-beta"] = [String(outgoing["anthropic-beta"] ?? ""), beta].filter(Boolean).join(",");+ if (attempt.report) extra = { ...extra, rewrite: attempt.report };+ if (dumpDir) sentBody = attempt.edited ? attempt.body : null;// No `agent` option: with agent:false Node ignores createConnection and dials the host directly.- const outbound = http.request({ host: upstream, method: req.method, path: req.url, headers, createConnection: () => socket }, (answer) => {+ const outbound = http.request({ host: upstream, method: req.method, path: req.url, headers: outgoing, createConnection: () => socket }, (answer) => {status = answer.statusCode ?? 0;const headers: Record<string, string | string[]> = {};for (const [name, value] of Object.entries(answer.headers)) if (value !== undefined && !HOP_BY_HOP.has(name)) headers[name] = value;- if (fallback && status === 400) {+ if (at < attempts.length - 1 && status === 400) {const parts: Buffer[] = [];answer.on("data", (chunk: Buffer) => parts.push(chunk));answer.on("error", (error) => finish(String(error)));@@ -622,10 +661,15 @@ async function main(): Promise<void> {const raw = Buffer.concat(parts);const text = decodeBody(raw, answer.headers["content-encoding"] as string | undefined)?.toString("utf8") ?? "";if (thinkingRejected(status, text)) {- extra = { ...extra, rewrite: { ...extra.rewrite, fallback: "thinking-signature", rejectedStatus: status } };- const again = { ...forwardHeaders(req.headers, upstream), "content-length": String(fallback.length) };+ extra = { ...extra, rejected: [...(extra.rejected ?? []), status] };+ if (dumpDir) { try { writeFileSync(dumpName(`.rejected-${at}.json`), text); } catch { /* experiments only */ } }+ // The account checks thinking: from now on the session's rewrites leave out what no longer fits.+ if (thinking && claudeSession && attempt.history && !thinking.strict) {+ thinking.strict = true;+ try { writeThinkingRecord(claudeSession, thinking); } catch { /* kept in memory */ }+ }socket.destroy();- send(again, fallback);+ send(attempts, at + 1);return;}res.writeHead(status, headers);@@ -635,36 +679,45 @@ async function main(): Promise<void> {});return;}+ // The thinking the model makes now comes after what this attempt sent.+ if (status >= 200 && status < 300 && thinking && claudeSession && attempt.history && attempt.sent) {+ rememberSent(thinking, attempt.history, attempt.sent);+ try { writeThinkingRecord(claudeSession, thinking); } catch { /* kept in memory */ }+ }res.writeHead(status, headers);- answer.on("data", (chunk: Buffer) => { responseBytes += chunk.length; });+ // Experiments only (--dump-requests): the response too, for its usage and what Anthropic changed.+ const captured: Buffer[] = [];+ answer.on("data", (chunk: Buffer) => { responseBytes += chunk.length; if (dumpDir && claudeSession && responseBytes <= 8 * 1024 * 1024) captured.push(chunk); });answer.pipe(res);- answer.on("end", () => finish());+ answer.on("end", () => {+ if (captured.length) {+ const raw = Buffer.concat(captured);+ try { writeFileSync(dumpName(".response.txt"), decodeBody(raw, answer.headers["content-encoding"] as string | undefined) ?? raw); } catch { /* experiments only */ }+ }+ finish();+ });answer.on("error", (error) => finish(String(error)));});outbound.on("error", (error) => { if (!res.headersSent) res.writeHead(502); res.end(); finish(String(error)); });// Codex may drop the connection mid-stream; still log the request once.res.on("close", () => finish(res.writableFinished ? undefined : "client closed before the response ended"));- if (body) outbound.end(body);+ if (attempt.body) outbound.end(attempt.body);else { collect(); req.pipe(outbound); }}, (error) => {res.writeHead(502, { "content-type": "text/plain" });res.end(`codex-attachment-manager proxy: cannot reach ${upstream}`);finish(String(error));- });- if (!rewrite && !claudeRewrite) { send(forwardHeaders(req.headers, upstream), null); return; }+ }); };+ if (!rewrite && !claudeRewrite) { send([{ body: null, report: null, edited: false }]); return; }collect();req.on("end", () => {const original = Buffer.concat(chunks);const encoding = req.headers["content-encoding"] as string | undefined;- let out: { body: Buffer; report: Json };- try { out = claudeRewrite ? rewriteClaudeBody(original, encoding, claudeSession!) : rewriteBody(original, encoding, identity.threadId!, sessionsDir, selectionDir, identity.turnId); }+ let out: { body: Buffer; report: Json; attempts?: ClaudeAttempt[] };+ try { out = claudeRewrite ? rewriteClaudeBody(original, encoding, claudeSession!, undefined, undefined, undefined, thinking) : rewriteBody(original, encoding, identity.threadId!, sessionsDir, selectionDir, identity.turnId); }catch (error) { out = { body: original, report: { skipped: `rewrite failed: ${String(error)}` } }; }- extra = { rewrite: out.report };- if (dumpDir && out.body !== original) sentBody = out.body;- const headers = forwardHeaders(req.headers, upstream);- headers["content-length"] = String(out.body.length);- if (out.report.experiment?.beta) headers["anthropic-beta"] = [String(headers["anthropic-beta"] ?? ""), out.report.experiment.beta].filter(Boolean).join(",");- send(headers, out.body, claudeRewrite && out.body !== original ? original : null);+ const attempts: Attempt[] = out.attempts?.length ? out.attempts.map((attempt) => ({ ...attempt, edited: attempt.body !== original })) : [{ body: out.body, report: out.report, edited: out.body !== original }];+ send(attempts);});};diff --git a/spike/src/claude-thinking.test.ts b/spike/src/claude-thinking.test.tsnew file mode 100644index 0000000..1a3b278--- /dev/null+++ b/spike/src/claude-thinking.test.ts@@ -0,0 +1,101 @@+// Purpose: v0.4 — claude-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.++import assert from "node:assert/strict";+import { mkdtempSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";+import { chainOf, fitThinking, readThinkingRecord, rememberSent, writeThinkingRecord, type ThinkingRecord } from "../../plugin/src/claude-thinking.ts";++type Json = Record<string, any>;+const think = (signature: string) => ({ type: "thinking", thinking: "", signature });+const text = (value: string, extra: Json = {}) => ({ type: "text", text: value, ...extra });+const image = (data: string) => ({ type: "image", source: { type: "base64", media_type: "image/png", data } });+const user = (...content: Json[]) => ({ role: "user", content });+const assistant = (...content: Json[]) => ({ role: "assistant", content });++// Turn 1 shows an image; turns 1 and 2 think after it.+function session() {+ const m0 = user(image("AAAA"), text("What is it?"));+ const a1 = assistant(think("s1"), text("Red."));+ const m2 = user(text("And now?"));+ const a3 = assistant(think("s3"), text("Still red."));+ const m4 = user(text("Next."));+ return { m0, a1, m2, a3, m4, original: [m0, a1, m2, a3, m4] };+}+// The engine's edit: the image becomes a placeholder, and a note follows its message.+const omitted = (m0: Json) => [user(text("[IMG-001 omitted]"), m0.content[1]), { role: "system", content: "note" }];++test("nothing changed: every thinking block stays, and what is sent is the history", () => {+ const { original } = session();+ const fit = fitThinking(original, original, new Map());+ assert.deepEqual([fit.kept, fit.left], [2, 0]);+ assert.deepEqual(fit.messages, original);+ assert.equal(fit.sent, fit.history);+});++test("thinking made after the history as it was leaves once an image before it is left out", () => {+ const s = session();+ const fit = fitThinking(s.original, [...omitted(s.m0), s.a1, s.m2, s.a3, s.m4], new Map());+ assert.deepEqual([fit.kept, fit.left], [0, 2]);+ assert.deepEqual(fit.messages[2].content, [text("Red.")]);+ assert.deepEqual(fit.messages[4].content, [text("Still red.")]);+ assert.notEqual(fit.sent, fit.history);+});++test("thinking made after what the engine sent stays, as long as the same goes out before it", () => {+ const s = session();+ // The request of turn 2: the image already left out, s1 with it.+ const before = fitThinking([s.m0, s.a1, s.m2], [...omitted(s.m0), s.a1, s.m2], new Map());+ assert.equal(before.left, 1);+ const record: ThinkingRecord = { strict: true, sent: new Map() };+ rememberSent(record, before.history, before.sent);+ // Turn 3: s3 was made after what turn 2 sent.+ const fit = fitThinking(s.original, [...omitted(s.m0), s.a1, s.m2, s.a3, s.m4], record.sent);+ assert.deepEqual([fit.kept, fit.left], [1, 1]);+ assert.deepEqual(fit.messages[4], s.a3);+ // The image checked again: s1 fits again; s3 was made while the image was left out, so it does not.+ const back = fitThinking(s.original, s.original, record.sent);+ assert.deepEqual([back.kept, back.left], [1, 1]);+ assert.deepEqual(back.messages[1], s.a1);+ assert.deepEqual(back.messages[3].content, [text("Still red.")]);+});++test("an edit after a thinking block leaves that block alone", () => {+ const s = session();+ const m2 = user(text("And now?"), image("BBBB"));+ const fit = fitThinking([s.m0, s.a1, m2, s.a3], [s.m0, s.a1, user(text("And now?"), text("[IMG-002 omitted]")), { role: "system", content: "note" }, s.a3], new Map());+ assert.deepEqual([fit.kept, fit.left], [1, 1]);+ assert.deepEqual(fit.messages[1], s.a1);+});++test("cache breakpoints are not part of the history; a message of thinking alone is not emptied", () => {+ const s = session();+ const moved = [s.m0, s.a1, s.m2, s.a3, user(text("Next.", { cache_control: { type: "ephemeral" } }))];+ assert.equal(chainOf(moved), chainOf(s.original));+ const alone = assistant(think("s9"));+ const fit = fitThinking([s.m0, alone], [...omitted(s.m0), alone], new Map());+ assert.deepEqual([fit.kept, fit.left], [1, 0]);+});++test("the record: what was sent per history, kept per session id, latest entries only", () => {+ const dir = mkdtempSync(join(tmpdir(), "cam-thinking-"));+ const id = "11111111-2222-4333-8444-555555555555";+ const record = readThinkingRecord(id, dir);+ assert.deepEqual(record, { strict: false, sent: new Map() });+ record.strict = true;+ rememberSent(record, "h1", "s1");+ // A history sent as it was needs no entry, and drops an older one.+ rememberSent(record, "h2", "s2");+ rememberSent(record, "h2", "h2");+ writeThinkingRecord(id, record, dir);+ assert.deepEqual(readThinkingRecord(id, dir), { strict: true, sent: new Map([["h1", "s1"]]) });+ writeThinkingRecord("../elsewhere", record, dir);+ assert.equal(readThinkingRecord("../elsewhere", dir).strict, false);+ for (let i = 0; i < 2100; i++) rememberSent(record, `k${i}`, `v${i}`);+ assert.equal(record.sent.size, 2000);+ assert.equal(record.sent.has("h1"), false);+ assert.equal(record.sent.get("k2099"), "v2099");+});diff --git a/spike/src/proxy.test.ts b/spike/src/proxy.test.tsindex 99c6830..20945c4 100644--- a/spike/src/proxy.test.ts+++ b/spike/src/proxy.test.ts@@ -229,11 +229,52 @@ test("a Claude Code request is rewritten from the session's transcript and selecconst experiment = rewriteClaudeBody(body, undefined, session, dir, home, { CAM_EXPERIMENT_BLOCK_BINDING: "error" });assert.deepEqual(JSON.parse(experiment.body.toString("utf8")).thinking, { type: "adaptive", block_binding: { prefix_mismatch_behavior: "error" } });assert.equal(experiment.report.experiment.beta, "thinking-binding-controls-2026-08-01");+ // What to send in turn: the rewrite, then the original as Claude Code built it.+ assert.deepEqual(out.attempts.map((attempt: any) => [attempt.body === body, attempt.report.fallback ?? null]), [[false, null], [true, "thinking-signature"]]);// Image sizes by key, as the panel's baseline.const sizes = claudeImageSizes(usualRequest(), buildClaudeIndex(session, t.records));assert.deepEqual(Object.keys(sizes).length, 4);});+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 { rememberSent } = await import("../../plugin/src/claude-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";+ const { t, p1 } = usualSession();+ mkdirSync(join(home, "projects", "D--work"), { recursive: true });+ writeFileSync(join(home, "projects", "D--work", `${session}.jsonl`), t.records.map((record) => JSON.stringify(record)).join("\n") + "\n");+ const body = Buffer.from(JSON.stringify({ model: "claude-haiku-5-5", thinking: { type: "adaptive" }, messages: usualRequest() }));+ writeSelection({ threadId: session, unchecked: { [`${p1}#1`]: { id: "IMG-002", at: "2026-10-10T00:00:00Z" } } }, dir);+ const record = { strict: false, sent: new Map<string, string>() };+ // Not known yet: the rewrite as it is, then without the thinking after the placeholder, then the original.+ const first = rewriteClaudeBody(body, undefined, session, dir, home, {}, record);+ assert.deepEqual(first.attempts.map((attempt: any) => [attempt.report.retry ?? null, attempt.report.fallback ?? null, attempt.report.thinking ?? null]), [+ [null, null, null],+ ["thinking-signature", null, { kept: 0, left: 1 }],+ [null, "thinking-signature", null],+ ]);+ const fitted = JSON.parse(first.attempts[1].body.toString("utf8")).messages;+ assert.equal(fitted[1].role, "system");+ assert.deepEqual(fitted[2].content.map((block: any) => block.type), ["text"]);+ // Known: that rewrite first.+ record.strict = true;+ const strict = rewriteClaudeBody(body, undefined, session, dir, home, {}, record);+ assert.deepEqual(strict.attempts.map((attempt: any) => attempt.report.thinking?.left ?? null), [1, null]);+ rememberSent(record, strict.attempts[0].history!, strict.attempts[0].sent!);+ // The next request carries thinking made after that; with the image checked again it no longer fits, while the+ // thinking made before the edit fits again.+ const next = [...usualRequest(), { role: "assistant", content: [{ type: "thinking", thinking: "", signature: "sig-9" }, text("Blue.")] }, { role: "user", content: [text("More?")] }];+ writeSelection({ threadId: session, unchecked: {} }, dir);+ const again = rewriteClaudeBody(Buffer.from(JSON.stringify({ model: "claude-haiku-5-5", thinking: { type: "adaptive" }, messages: next })), undefined, session, dir, home, {}, record);+ assert.deepEqual(again.attempts.map((attempt: any) => attempt.report.thinking ?? null), [{ kept: 1, left: 1 }, null]);+ const sent = JSON.parse(again.attempts[0].body.toString("utf8")).messages;+ assert.deepEqual(sent[1].content.map((block: any) => block.type), ["thinking", "text"]);+ assert.deepEqual(sent[9].content.map((block: any) => block.type), ["text"]);+});+test("Anthropic refusing the thinking after an edited history is told apart from other 400s", async () => {const { thinkingRejected } = await import("../../plugin/src/proxy.ts");const rejected = JSON.stringify({ type: "error", error: { type: "invalid_request_error", message: "messages.3.content.0: Invalid `signature` in `thinking` block. The block is bound to a different conversation." } });