From 5b8596ee69f990e36c73c3b2fe90d48723de6e98 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sun, 4 Oct 2026 10:46:53 +0800 Subject: [PATCH 01/11] feat: image recovery channel for stripImages (#1995) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit stripImages drops historical image parts with no way back: decompress is text-only and image_full (#1095) only restores downsampled originals, so once stripped the pixels are gone from the model's view forever — while the sliding keep-recent window rewrites one message per turn and busts the prompt cache on the most expensive bytes (the pi#593 cost source). Either way the user pays. Add a recovery channel. Each request indexes the images still present in the client's resent raw history by their mNNNNN ref (via stable message ids), gated on stripImages so non-strip sessions pay nothing. decompress gains an optional imageRef: "list" enumerates what is restorable; an mNNNNN ref writes the original bytes to a host-readable file under /retrieve/img/ and returns the path for the model's read tool. File-first delivery is uniform across all four wires — no per-protocol inline-image rendering. The index is built from the UNSTRIPPED body before strip drops the parts, and cleared when stripImages is off. Wires imageRef into every decompress variant (range and no-range alike; it is CCR-independent, unlike startId/endId). Regenerates the wire-contract goldens accordingly — verified the diff is exactly the decompress description note plus the imageRef property, nothing else. Proxy-mode coverage: the proxy never mutates client state, so every inbound request carries full raw history and stripped pixels are always recoverable. Native agents own their own decompress (their self-folded images are theirs, cf pi#594); this recovers what the PROXY strips. Gap2 (reducing cache-bust frequency via a compression-anchored strip boundary) stays tracked as the remaining facet of #1995 — a token-vs-cache tradeoff pending owner sign-off, not shipped here. Closes #1995 --- src/compress-tool.ts | 39 ++- src/decompress-shared.ts | 41 +++ src/image-restore.ts | 240 ++++++++++++++++++ src/server.ts | 10 + src/session.ts | 11 +- tests/golden/wire-contract/bili.json | 54 +++- .../wire-contract/manifest-default.json | 18 +- .../golden/wire-contract/manifest-optin.json | 18 +- tests/image-restore.test.ts | 186 ++++++++++++++ 9 files changed, 590 insertions(+), 27 deletions(-) create mode 100644 src/image-restore.ts create mode 100644 tests/image-restore.test.ts diff --git a/src/compress-tool.ts b/src/compress-tool.ts index 5bea604f70..1c8e588aa0 100644 --- a/src/compress-tool.ts +++ b/src/compress-tool.ts @@ -190,10 +190,24 @@ function withRangeParams(schema: JsonSchemaObject): JsonSchemaObject { return { ...schema, properties: { ...schema.properties, startId: DECOMPRESS_RANGE_PARAM_START, endId: DECOMPRESS_RANGE_PARAM_END } }; } -export const BILI_DECOMPRESS_TOOL = { name: DECOMPRESS_TOOL.name, description: DECOMPRESS_TOOL.description, input_schema: withRangeParams(DECOMPRESS_TOOL.input_schema) }; -export const BILI_DECOMPRESS_TOOL_OPENAI = { type: "function" as const, function: { name: DECOMPRESS_TOOL_OPENAI.function.name, description: DECOMPRESS_TOOL_OPENAI.function.description, parameters: withRangeParams(DECOMPRESS_TOOL_OPENAI.function.parameters) } }; -export const BILI_DECOMPRESS_TOOL_RESPONSES = { type: "function" as const, name: DECOMPRESS_TOOL_RESPONSES.name, description: DECOMPRESS_TOOL_RESPONSES.description, parameters: withRangeParams(DECOMPRESS_TOOL_RESPONSES.parameters) }; -export const BILI_DECOMPRESS_TOOL_GOOGLE = { name: DECOMPRESS_TOOL_GOOGLE.name, description: DECOMPRESS_TOOL_GOOGLE.description, parameters: withRangeParams(DECOMPRESS_TOOL_GOOGLE.parameters) }; +// #1995: image-recovery extension of decompress. An optional imageRef (an mNNNNN +// ref, or "list") restores a stripped/folded image's original pixels to a +// host-readable file. It is independent of blockId/range AND of CCR, so — unlike +// startId/endId (#1712, which are advertised only where CCR can arm them) — it is +// offered in EVERY decompress variant, range and no-range alike. +const DECOMPRESS_IMAGE_PARAM = { + type: "string", + description: "Optional mNNNNN message ref whose IMAGE payload you want restored (an image that was stripped or folded away). Pass \"list\" to enumerate every image currently restorable. Restored images are written to host-readable files and their paths returned — open them with the read tool. Independent of blockId/range and of CCR.", +}; +const DECOMPRESS_IMAGE_NOTE = " Pass imageRef (an mNNNNN ref) to restore a stripped/folded image's original pixels to a file you open with the read tool; imageRef:\"list\" shows what is restorable."; +function withImageRestoreParam(schema: JsonSchemaObject): JsonSchemaObject { + return { ...schema, properties: { ...schema.properties, imageRef: DECOMPRESS_IMAGE_PARAM } }; +} + +export const BILI_DECOMPRESS_TOOL = { name: DECOMPRESS_TOOL.name, description: DECOMPRESS_TOOL.description + DECOMPRESS_IMAGE_NOTE, input_schema: withImageRestoreParam(withRangeParams(DECOMPRESS_TOOL.input_schema)) }; +export const BILI_DECOMPRESS_TOOL_OPENAI = { type: "function" as const, function: { name: DECOMPRESS_TOOL_OPENAI.function.name, description: DECOMPRESS_TOOL_OPENAI.function.description + DECOMPRESS_IMAGE_NOTE, parameters: withImageRestoreParam(withRangeParams(DECOMPRESS_TOOL_OPENAI.function.parameters)) } }; +export const BILI_DECOMPRESS_TOOL_RESPONSES = { type: "function" as const, name: DECOMPRESS_TOOL_RESPONSES.name, description: DECOMPRESS_TOOL_RESPONSES.description + DECOMPRESS_IMAGE_NOTE, parameters: withImageRestoreParam(withRangeParams(DECOMPRESS_TOOL_RESPONSES.parameters)) }; +export const BILI_DECOMPRESS_TOOL_GOOGLE = { name: DECOMPRESS_TOOL_GOOGLE.name, description: DECOMPRESS_TOOL_GOOGLE.description + DECOMPRESS_IMAGE_NOTE, parameters: withImageRestoreParam(withRangeParams(DECOMPRESS_TOOL_GOOGLE.parameters)) }; export const BILI_ACP_TOOLS_ANTHROPIC = ACP_TOOLS_ANTHROPIC.map((t) => (t.name === SEARCH_CONTEXT_TOOL_NAME ? BILI_SEARCH_CONTEXT_TOOL : t.name === DECOMPRESS_TOOL_NAME ? BILI_DECOMPRESS_TOOL : t)); export const BILI_ACP_TOOLS_OPENAI = ACP_TOOLS_OPENAI.map((t) => (t.function.name === SEARCH_CONTEXT_TOOL_NAME ? BILI_SEARCH_CONTEXT_TOOL_OPENAI : t.function.name === DECOMPRESS_TOOL_NAME ? BILI_DECOMPRESS_TOOL_OPENAI : t)); @@ -202,12 +216,17 @@ export const BILI_ACP_TOOLS_GOOGLE = ACP_TOOLS_GOOGLE.map((t) => (t.name === SEA // #1712: no-range variants — identical except decompress lacks startId/endId. // Served where range restore cannot be armed so the advertised schema never -// offers what execution will refuse (see the #1179 note above). -export const BILI_ACP_TOOLS_ANTHROPIC_NO_RANGE = ACP_TOOLS_ANTHROPIC.map((t) => (t.name === SEARCH_CONTEXT_TOOL_NAME ? BILI_SEARCH_CONTEXT_TOOL : t)); -export const BILI_ACP_TOOLS_OPENAI_NO_RANGE = ACP_TOOLS_OPENAI.map((t) => (t.function.name === SEARCH_CONTEXT_TOOL_NAME ? BILI_SEARCH_CONTEXT_TOOL_OPENAI : t)); -export const BILI_ACP_TOOLS_RESPONSES_NO_RANGE = ACP_TOOLS_RESPONSES.map((t) => (t.name === SEARCH_CONTEXT_TOOL_NAME ? BILI_SEARCH_CONTEXT_TOOL_RESPONSES : t)); -export const BILI_ACP_TOOLS_GOOGLE_NO_RANGE = ACP_TOOLS_GOOGLE.map((t) => (t.name === SEARCH_CONTEXT_TOOL_NAME ? BILI_SEARCH_CONTEXT_TOOL_GOOGLE : t)); -export const BILI_ACP_READONLY_TOOLS_RESPONSES_NO_RANGE = ACP_READONLY_TOOLS_RESPONSES.map((t) => (t.name === SEARCH_CONTEXT_TOOL_NAME ? BILI_SEARCH_CONTEXT_TOOL_RESPONSES : t)); +// offers what execution will refuse (see the #1179 note above). Image recovery +// still applies here (it does not require CCR), so these keep imageRef. +const BILI_DECOMPRESS_IMG_ANTHROPIC = { name: DECOMPRESS_TOOL.name, description: DECOMPRESS_TOOL.description + DECOMPRESS_IMAGE_NOTE, input_schema: withImageRestoreParam(DECOMPRESS_TOOL.input_schema) }; +const BILI_DECOMPRESS_IMG_OPENAI = { type: "function" as const, function: { name: DECOMPRESS_TOOL_OPENAI.function.name, description: DECOMPRESS_TOOL_OPENAI.function.description + DECOMPRESS_IMAGE_NOTE, parameters: withImageRestoreParam(DECOMPRESS_TOOL_OPENAI.function.parameters) } }; +const BILI_DECOMPRESS_IMG_RESPONSES = { type: "function" as const, name: DECOMPRESS_TOOL_RESPONSES.name, description: DECOMPRESS_TOOL_RESPONSES.description + DECOMPRESS_IMAGE_NOTE, parameters: withImageRestoreParam(DECOMPRESS_TOOL_RESPONSES.parameters) }; +const BILI_DECOMPRESS_IMG_GOOGLE = { name: DECOMPRESS_TOOL_GOOGLE.name, description: DECOMPRESS_TOOL_GOOGLE.description + DECOMPRESS_IMAGE_NOTE, parameters: withImageRestoreParam(DECOMPRESS_TOOL_GOOGLE.parameters) }; +export const BILI_ACP_TOOLS_ANTHROPIC_NO_RANGE = ACP_TOOLS_ANTHROPIC.map((t) => (t.name === SEARCH_CONTEXT_TOOL_NAME ? BILI_SEARCH_CONTEXT_TOOL : t.name === DECOMPRESS_TOOL_NAME ? BILI_DECOMPRESS_IMG_ANTHROPIC : t)); +export const BILI_ACP_TOOLS_OPENAI_NO_RANGE = ACP_TOOLS_OPENAI.map((t) => (t.function.name === SEARCH_CONTEXT_TOOL_NAME ? BILI_SEARCH_CONTEXT_TOOL_OPENAI : t.function.name === DECOMPRESS_TOOL_NAME ? BILI_DECOMPRESS_IMG_OPENAI : t)); +export const BILI_ACP_TOOLS_RESPONSES_NO_RANGE = ACP_TOOLS_RESPONSES.map((t) => (t.name === SEARCH_CONTEXT_TOOL_NAME ? BILI_SEARCH_CONTEXT_TOOL_RESPONSES : t.name === DECOMPRESS_TOOL_NAME ? BILI_DECOMPRESS_IMG_RESPONSES : t)); +export const BILI_ACP_TOOLS_GOOGLE_NO_RANGE = ACP_TOOLS_GOOGLE.map((t) => (t.name === SEARCH_CONTEXT_TOOL_NAME ? BILI_SEARCH_CONTEXT_TOOL_GOOGLE : t.name === DECOMPRESS_TOOL_NAME ? BILI_DECOMPRESS_IMG_GOOGLE : t)); +export const BILI_ACP_READONLY_TOOLS_RESPONSES_NO_RANGE = ACP_READONLY_TOOLS_RESPONSES.map((t) => (t.name === SEARCH_CONTEXT_TOOL_NAME ? BILI_SEARCH_CONTEXT_TOOL_RESPONSES : t.name === DECOMPRESS_TOOL_NAME ? BILI_DECOMPRESS_IMG_RESPONSES : t)); export const BILI_ACP_READONLY_TOOLS_RESPONSES = ACP_READONLY_TOOLS_RESPONSES.map((t) => (t.name === SEARCH_CONTEXT_TOOL_NAME ? BILI_SEARCH_CONTEXT_TOOL_RESPONSES : t.name === DECOMPRESS_TOOL_NAME ? BILI_DECOMPRESS_TOOL_RESPONSES : t)); // The kernel ships no Responses-format absorb const (the four ACP tools have diff --git a/src/decompress-shared.ts b/src/decompress-shared.ts index 1855b24270..a39ee056d1 100644 --- a/src/decompress-shared.ts +++ b/src/decompress-shared.ts @@ -22,6 +22,7 @@ import { ccrEnabled, contentStoreOf } from "./store.js"; import { safePrefix } from "./text-safe.js"; import { decompressTmpCap as knobDecompressTmpCap } from "./knobs.js"; import { toolFail, toolOk, type ProxyToolResult } from "./proxy-tool-result.js"; +import { describeRestorable, writeRestoredImage } from "./image-restore.js"; /** Bounded retention for large-decompress temp files. Each decompress with * body > 10000 writes one file under tmpdir(); the reaper unlinks oldest past @@ -166,6 +167,12 @@ export function resolveDecompress( args: Record, ctx: ProxyToolCtx, ): ProxyToolResult { + // #1995: image recovery is a distinct mode selected by imageRef (an mNNNNN ref, + // or "list"), independent of blockId/range — intercepted first so an image-ref + // call never trips the blockId-required gate below. + if (args.imageRef !== undefined) { + return resolveImageRestore(args, ctx); + } const rawBlockId = args.blockId; if (typeof rawBlockId !== "string" || rawBlockId.length === 0) { return toolFail("[decompress FAILED: blockId is required]"); @@ -251,6 +258,40 @@ export function resolveDecompress( return toolOk(`${header}\n${body}\n\n${refoldHint(blockId, marked.result)}`); } +// #1995: restore the original pixels of a stripped/folded image by ref. Delivery +// is file-first — each image is written under /retrieve/img/ and its +// path returned for the model to open with its read tool — uniform across all four +// wires (no per-protocol inline-image rendering). "list" enumerates what is +// currently restorable instead of writing anything. +function resolveImageRestore(args: Record, ctx: ProxyToolCtx): ProxyToolResult { + const index = ctx.session.incomingImageIndex; + const raw = typeof args.imageRef === "string" ? args.imageRef.trim() : ""; + if (raw === "" || raw.toLowerCase() === "list") { + if (!index || index.size === 0) { + return toolOk("[No restorable images right now — this request carries no indexed historical images (stripImages must be enabled and the client must resend them).]"); + } + const lines = describeRestorable(index); + return toolOk(`[Restorable images (${lines.length}):]\n${lines.join("\n")}\nRestore one with decompress({ imageRef: "" }); it is written to a file you open with the read tool.`); + } + if (!index) { + return toolFail(`[decompress FAILED: no image history is indexed for this request (stripImages off?) — cannot restore "${raw}".]`); + } + const imgs = index.get(raw); + if (!imgs || imgs.length === 0) { + return toolFail(`[decompress FAILED: no restorable image for ref "${raw}" (it carries no image, is URL-sourced with no stored bytes, or is not in this request's history). Call decompress({ imageRef: "list" }) to see what is available.]`); + } + const written: string[] = []; + for (let i = 0; i < imgs.length; i++) { + const p = writeRestoredImage(raw, i, imgs[i]); + if (p) written.push(p); + } + if (written.length === 0) { + return toolFail(`[decompress FAILED: could not write restored image(s) for "${raw}" to disk.]`); + } + ctx.log(`[acp-image-restore] ${raw}: restored ${written.length} image(s) → ${written.join(", ")}`); + return toolOk(`[Restored ${written.length} image(s) for ${raw}:\n${written.map((p) => ` ${p}`).join("\n")}\nOpen them with the read tool to view the pixels.]`); +} + // #1294 P2: close the loop on an inline restore — kernel K2 updates the // inline-restored block IN PLACE when re-compressed (same id, replaced // summary) instead of rejecting "already compressed". Degrades to a generic diff --git a/src/image-restore.ts b/src/image-restore.ts new file mode 100644 index 0000000000..af5d171bea --- /dev/null +++ b/src/image-restore.ts @@ -0,0 +1,240 @@ +// #1995: recovery channel for stripImages. Stripping drops historical image +// parts with no trace left behind — decompress is text-only and image_full only +// covers downsampled originals (#1095), so once an image is stripped the model +// can never see those pixels again. The client re-sends full raw history every +// turn, so the original bytes are always present in the incoming request; this +// module indexes them by kernel-assigned mNNNNN ref (via each message's stable +// id) so decompress({ imageRef }) can pull a specific image back. Delivery is +// file-first (a host-readable path the model opens with its read tool) — uniform +// across all four wires, no per-protocol inline-image rendering required. +// +// Scope note: this only recovers images bili itself can see in the inbound +// request. A plugin-mode agent that folded an image away in its OWN local store +// sends no such bytes to the proxy, so those belong to the agent's in-process +// recovery (cf. billion-context-pi#594), not here. + +import { mkdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { + anthropicToCore, + googleToCore, + openaiToCore, + parseDataUrl, + responsesToCore, + type AnthropicRequestBody, + type BiliMessage, + type GoogleRequestBody, + type OpenAIRequestBody, + type ResponsesRequestBody, +} from "acp-kernel/wire"; +import type { CompressionState, CoreMessage } from "acp-kernel"; +import { log as loggerLog } from "./logger.js"; +import { stateDir } from "./paths.js"; +import { decodeImageDims } from "./image-tokens.js"; +import type { WireProtocol } from "./util.js"; + +/** One recoverable image: base64 payload plus enough metadata to name the file + * and describe it. `bytes` is the DECODED length (base64 length × 3/4), not the + * b64 string length. */ +export interface RestorableImage { + mediaType: string; + b64: string; + bytes: number; +} + +function isObj(v: unknown): v is Record { + return typeof v === "object" && v !== null; +} + +function dataUrlRef(url: unknown): { mediaType?: string; b64?: string } | undefined { + if (typeof url !== "string") return undefined; + const d = parseDataUrl(url); + return d ? { mediaType: d.mediaType, b64: d.base64 } : undefined; +} + +function b64Bytes(b64: string): number { + return Math.floor((Buffer.byteLength(b64, "base64") || 0)); +} + +/** The base64 images this core message carries, in wire order, across all four + * protocols (anthropic / openai / responses / google). URL-sourced images whose + * bytes we cannot obtain (non-data URLs) yield no entry — only carryable + * base64 payloads are indexed. Returns [] for plain-text messages (the common + * case). */ +export function messageImageBytes(m: CoreMessage): RestorableImage[] { + const mm = m as BiliMessage; + const out: RestorableImage[] = []; + // Anthropic: each image block becomes its own core message; the same sidecar + // field also carries structured tool_results, so gate on type === "image". + const ab = mm.rawAnthropicBlock; + if (isObj(ab) && ab.type === "image") { + const s = ab.source; + const mediaType = isObj(s) && typeof s.media_type === "string" ? s.media_type : "image/png"; + if (isObj(s)) { + if (s.type === "base64" && typeof s.data === "string") { + out.push({ mediaType, b64: s.data, bytes: b64Bytes(s.data) }); + } else if (s.type === "url") { + const r = dataUrlRef(s.url); + if (r?.b64) out.push({ mediaType: r.mediaType ?? mediaType, b64: r.b64, bytes: b64Bytes(r.b64) }); + } + } + return out; + } + // Responses: the original item keeps every input_image part (the singular + // imageBase64 sidecar covers only the first), so walk the item's content. + const ri = mm.rawResponsesItem; + if (isObj(ri) && Array.isArray(ri.content)) { + for (const part of ri.content) { + if (!isObj(part) || part.type !== "input_image") continue; + const u = isObj(part.image_url) ? part.image_url.url : part.image_url; + const r = dataUrlRef(u); + if (r?.b64) out.push({ mediaType: r.mediaType ?? "image/png", b64: r.b64, bytes: b64Bytes(r.b64) }); + } + if (out.length > 0) return out; + } + // Multi-part sources come FIRST: the shared singular imageBase64 sidecar is + // set by every protocol for a single data-URL image, so checking it earlier + // would shadow the multi-part fields and drop every image after the first. + // Google: inlineData parts (raw base64 in .data, mime in .mimeType). + if (Array.isArray(mm.rawGoogleParts)) { + for (const part of mm.rawGoogleParts as unknown[]) { + if (!isObj(part)) continue; + const inline = part.inlineData; + if (isObj(inline) && typeof inline.data === "string") { + const mediaType = typeof inline.mimeType === "string" ? inline.mimeType : "image/png"; + out.push({ mediaType, b64: inline.data, bytes: b64Bytes(inline.data) }); + } + } + if (out.length > 0) return out; + } + // OpenAI chat: multi-image → rawOpenaiContentParts; a lone image_url may also + // sit in rawOpenaiContent. + if (Array.isArray(mm.rawOpenaiContentParts)) { + for (const p of mm.rawOpenaiContentParts) { + if (!isObj(p) || p.type !== "image_url") continue; + const u = isObj(p.image_url) ? p.image_url.url : undefined; + const r = dataUrlRef(u); + if (r?.b64) out.push({ mediaType: r.mediaType ?? "image/png", b64: r.b64, bytes: b64Bytes(r.b64) }); + } + if (out.length > 0) return out; + } + if (isObj(mm.rawOpenaiContent) && mm.rawOpenaiContent.type === "image_url") { + const u = isObj(mm.rawOpenaiContent.image_url) ? mm.rawOpenaiContent.image_url.url : undefined; + const r = dataUrlRef(u); + if (r?.b64) out.push({ mediaType: r.mediaType ?? "image/png", b64: r.b64, bytes: b64Bytes(r.b64) }); + if (out.length > 0) return out; + } + // Singular fallback: the shared imageBase64 sidecar (one data-URL image). + if (typeof mm.imageBase64 === "string") { + out.push({ mediaType: typeof mm.imageMediaType === "string" ? mm.imageMediaType : "image/png", b64: mm.imageBase64, bytes: b64Bytes(mm.imageBase64) }); + } + return out; +} + +/** Extract the core-message array from a protocol toCore() result, tolerating + * both `{ msgs }` object returns and bare arrays. Returns undefined when the + * shape is unrecognized (caller degrades to an empty index). */ +function coreMsgsOf(result: unknown): CoreMessage[] | undefined { + if (Array.isArray(result)) return result as CoreMessage[]; + if (isObj(result) && Array.isArray((result as { msgs?: unknown }).msgs)) { + return (result as { msgs: CoreMessage[] }).msgs; + } + return undefined; +} + +/** Parse the INBOUND wire body into core messages and index every carried image + * by its mNNNNN ref. A message is indexed only when it is already known to the + * session (`state.messageRefs.byRaw[message.id]` resolves) — brand-new tail + * messages have no ref yet and sit inside the keep window anyway, so they are + * never strip targets. Returns an empty map when nothing is recoverable (no + * images, no refs, or an unparseable body). */ +export function buildIncomingImageIndex( + parsed: unknown, + protocol: WireProtocol, + state: CompressionState, +): Map { + const index = new Map(); + const byRaw = state?.messageRefs?.byRaw; + if (!byRaw) return index; + let result: unknown; + try { + switch (protocol) { + case "anthropic": result = anthropicToCore(parsed as AnthropicRequestBody); break; + case "openai": result = openaiToCore(parsed as OpenAIRequestBody); break; + case "google": result = googleToCore(parsed as GoogleRequestBody); break; + case "responses": result = responsesToCore(parsed as ResponsesRequestBody); break; + } + } catch { + return index; + } + const msgs = coreMsgsOf(result); + if (!msgs) return index; + for (const m of msgs) { + const ref = m.id ? byRaw[m.id] : undefined; + if (!ref) continue; + const imgs = messageImageBytes(m); + if (imgs.length === 0) continue; + const existing = index.get(ref); + if (existing) existing.push(...imgs); + else index.set(ref, imgs); + } + return index; +} + +function refNum(ref: string): number { + const m = /^m(\d+)$/i.exec(ref.trim()); + return m ? Number.parseInt(m[1], 10) : Number.MAX_SAFE_INTEGER; +} + +/** Human-readable one-line-per-image listing of what is currently restorable + * ("m00042 [png 1024x768 · 240KB]"), sorted by ref then position. Capped so a + * very image-heavy history cannot blow up the tool result. */ +export function describeRestorable(index: Map, cap = 50): string[] { + const lines: string[] = []; + const refs = [...index.keys()].sort((a, b) => refNum(a) - refNum(b)); + outer: for (const ref of refs) { + const imgs = index.get(ref)!; + for (let i = 0; i < imgs.length; i++) { + const im = imgs[i]; + let note = im.mediaType.includes("/") ? im.mediaType.split("/").pop()! : im.mediaType; + try { + const dims = decodeImageDims(im.b64); + if (dims) note += ` ${dims.w}x${dims.h}`; + } catch {} + note += ` · ${Math.max(1, Math.round(im.bytes / 1024))}KB`; + lines.push(`${ref}${i > 0 ? `[-${i}]` : ""} [${note}]`); + if (lines.length >= cap) break outer; + } + } + return lines; +} + +/** Directory restored images are written to: /retrieve/img/, sharing + * the CCR retrieve tree so operators find both under one place. */ +export function restoreExportDir(): string { + return join(stateDir(), "retrieve", "img"); +} + +function extFor(mediaType: string): string { + const sub = (mediaType.split("/")[1] ?? "").toLowerCase(); + const map: Record = { png: "png", jpeg: "jpg", jpg: "jpg", gif: "gif", webp: "webp", svg: "svg" }; + return map[sub] ?? "img"; +} + +/** Write one restorable image to disk (decoded bytes, 0600 — conversation + * content is not world-readable on multi-user hosts) and return its absolute + * path. Content-addressed by ref (+index), so a repeated restore rewrites + * identical bytes (idempotent). Returns null on write failure. */ +export function writeRestoredImage(ref: string, idx: number, img: RestorableImage): string | null { + const safeRef = ref.replace(/[^a-zA-Z0-9_-]/g, "-"); + const dir = restoreExportDir(); + const path = join(dir, `${safeRef}${idx > 0 ? `-${idx}` : ""}.${extFor(img.mediaType)}`); + try { + mkdirSync(dir, { recursive: true }); + writeFileSync(path, Buffer.from(img.b64, "base64"), { mode: 0o600 }); + return path; + } catch (e) { + loggerLog("warn", `[image-restore] write failed (${path}): ${String(e)}`); + return null; + } +} diff --git a/src/server.ts b/src/server.ts index 11c1cc0bb4..5cc5529271 100644 --- a/src/server.ts +++ b/src/server.ts @@ -69,6 +69,7 @@ import { import { ABSORB_TOOL_NAME, COMPRESS_TOOL, BILI_ACP_TOOLS_ANTHROPIC, BILI_ACP_TOOLS_ANTHROPIC_NO_RANGE, BILI_ACP_TOOLS_GOOGLE, BILI_ACP_TOOLS_GOOGLE_NO_RANGE, BILI_ACP_TOOLS_OPENAI, BILI_ACP_TOOLS_OPENAI_NO_RANGE, BILI_ACP_TOOLS_RESPONSES, BILI_ACP_TOOLS_RESPONSES_NO_RANGE, BILI_ACP_READONLY_TOOLS_RESPONSES, BILI_ACP_READONLY_TOOLS_RESPONSES_NO_RANGE, COMPRESS_TOOL_NAME, IMAGE_FULL_TOOL, IMAGE_FULL_TOOL_GOOGLE, IMAGE_FULL_TOOL_OPENAI, IMAGE_FULL_TOOL_RESPONSES, RULE_TOOL, RULE_TOOL_GOOGLE, RULE_TOOL_OPENAI, RULE_TOOL_RESPONSES, absorbToolsFor, retrieveToolsFor, buildAbsorbSystemPrompt, buildAcpTagsOnlyPrompt, buildCompressSystemPrompt, buildCompressHybridSystemPrompt, withMarkerIntegrityNote, withStagedCompressGuidance, withSummaryBudgetNote } from "./compress-tool.js"; import { applyAbsorbView, absorbEnabled, absorbToolName, storeEffectiveAbsorb } from "./absorb.js"; import { adoptContentStore, ccrEnabled, ccrLoopConfig, ccrPluginWireOk, commitRetrievals, commitRetrievalNotes, contentStoreOf, dropRetrievals, executeRetrieve, pruneExpiredRetrievals, reconcileReloadedRetrievals, renderRetrievalNotes, retrieveToolName, snapshotPendingRetrievals, snapshotRetrievalNotes, storeEffectiveCcr, type CcrSettings } from "./store.js"; +import { buildIncomingImageIndex } from "./image-restore.js"; import { applyImageCompressionPass, imageCompressionEnabled, imageFullTrailingNote, imageUsageSuffix, storeEffectiveImageCompression, type ImageCompressionSettings } from "./image-compress.js"; import { rulesEnabled, storeEffectiveRules } from "./rules-feature.js"; import { storeEffectiveSearchPlanAware } from "./decompress-shared.js"; @@ -3229,6 +3230,15 @@ async function handle( const stripped = cs.stripImages ? stripHistoricalImages(parsed, protocol, keepRecent) : { body: parsed, removed: 0 }; + // #1995: index recoverable historical images by ref from the UNSTRIPPED + // body before stripping drops them, so decompress({ imageRef }) can pull + // specific pixels back later. Gated on stripImages (recovery is only + // meaningful when stripping removes something); latest-wins per request. + if (cs.stripImages && protocol) { + session.incomingImageIndex = buildIncomingImageIndex(parsed, protocol, session.state); + } else if (session.incomingImageIndex) { + session.incomingImageIndex = undefined; + } if (opts.debug && stripped.removed > 0) { log("info", `[debug] strip-images: dropped ${stripped.removed} historical image part(s), kept last ${keepRecent} (session=${session.id})`); } diff --git a/src/session.ts b/src/session.ts index efb342131d..1286b7b466 100644 --- a/src/session.ts +++ b/src/session.ts @@ -336,8 +336,15 @@ export type Session = { * non-CCR riders (#1207 range restore, ccr:false). Legacy sessions from * before the rework may still carry ccr:true entries; the reconcile/ * commit/drop machinery below handles them (they are never re-created). */ - pendingRetrievals: PendingRetrieval[]; - /** #1095 in-memory only (NOT persisted): deterministic encode cache keyed + pendingRetrievals: PendingRetrieval[]; + /** #1995 in-memory only (NOT persisted — buildRecord omits it): ref → images + * index built per request from the INBOUND body while stripImages is armed, + * so decompress({ imageRef }) can pull a stripped/folded image's original + * pixels back. Latest-wins (the client re-sends full history every turn, so + * each request's index is complete); cleared when stripImages is off. Values + * hold references to base64 already resident from parsing the request. */ + incomingImageIndex?: Map>; + /** #1095 in-memory only (NOT persisted): deterministic encode cache keyed * by sha256 of the ORIGINAL base64 → encoded payload. Identical inputs * must yield identical wire bytes across turns/restarts (prefix-cache * invariant), so this is a pure CPU cache, never a correctness source. */ diff --git a/tests/golden/wire-contract/bili.json b/tests/golden/wire-contract/bili.json index c2a3db3875..4fc1486f53 100644 --- a/tests/golden/wire-contract/bili.json +++ b/tests/golden/wire-contract/bili.json @@ -121,7 +121,7 @@ }, { "name": "decompress", - "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context.", + "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context. Pass imageRef (an mNNNNN ref) to restore a stripped/folded image's original pixels to a file you open with the read tool; imageRef:\"list\" shows what is restorable.", "input_schema": { "type": "object", "properties": { @@ -144,6 +144,10 @@ "endId": { "type": "string", "description": "Optional mNNNNN message ref, inclusive upper bound. Used together with startId; omit both to restore the whole block." + }, + "imageRef": { + "type": "string", + "description": "Optional mNNNNN message ref whose IMAGE payload you want restored (an image that was stripped or folded away). Pass \"list\" to enumerate every image currently restorable. Restored images are written to host-readable files and their paths returned — open them with the read tool. Independent of blockId/range and of CCR." } }, "required": [ @@ -323,7 +327,7 @@ "type": "function", "function": { "name": "decompress", - "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context.", + "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context. Pass imageRef (an mNNNNN ref) to restore a stripped/folded image's original pixels to a file you open with the read tool; imageRef:\"list\" shows what is restorable.", "parameters": { "type": "object", "properties": { @@ -346,6 +350,10 @@ "endId": { "type": "string", "description": "Optional mNNNNN message ref, inclusive upper bound. Used together with startId; omit both to restore the whole block." + }, + "imageRef": { + "type": "string", + "description": "Optional mNNNNN message ref whose IMAGE payload you want restored (an image that was stripped or folded away). Pass \"list\" to enumerate every image currently restorable. Restored images are written to host-readable files and their paths returned — open them with the read tool. Independent of blockId/range and of CCR." } }, "required": [ @@ -532,7 +540,7 @@ { "type": "function", "name": "decompress", - "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context.", + "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context. Pass imageRef (an mNNNNN ref) to restore a stripped/folded image's original pixels to a file you open with the read tool; imageRef:\"list\" shows what is restorable.", "parameters": { "type": "object", "properties": { @@ -555,6 +563,10 @@ "endId": { "type": "string", "description": "Optional mNNNNN message ref, inclusive upper bound. Used together with startId; omit both to restore the whole block." + }, + "imageRef": { + "type": "string", + "description": "Optional mNNNNN message ref whose IMAGE payload you want restored (an image that was stripped or folded away). Pass \"list\" to enumerate every image currently restorable. Restored images are written to host-readable files and their paths returned — open them with the read tool. Independent of blockId/range and of CCR." } }, "required": [ @@ -659,7 +671,7 @@ }, { "name": "decompress", - "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context.", + "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context. Pass imageRef (an mNNNNN ref) to restore a stripped/folded image's original pixels to a file you open with the read tool; imageRef:\"list\" shows what is restorable.", "parameters": { "type": "object", "properties": { @@ -682,6 +694,10 @@ "endId": { "type": "string", "description": "Optional mNNNNN message ref, inclusive upper bound. Used together with startId; omit both to restore the whole block." + }, + "imageRef": { + "type": "string", + "description": "Optional mNNNNN message ref whose IMAGE payload you want restored (an image that was stripped or folded away). Pass \"list\" to enumerate every image currently restorable. Restored images are written to host-readable files and their paths returned — open them with the read tool. Independent of blockId/range and of CCR." } }, "required": [ @@ -722,7 +738,7 @@ { "type": "function", "name": "decompress", - "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context.", + "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context. Pass imageRef (an mNNNNN ref) to restore a stripped/folded image's original pixels to a file you open with the read tool; imageRef:\"list\" shows what is restorable.", "parameters": { "type": "object", "properties": { @@ -745,6 +761,10 @@ "endId": { "type": "string", "description": "Optional mNNNNN message ref, inclusive upper bound. Used together with startId; omit both to restore the whole block." + }, + "imageRef": { + "type": "string", + "description": "Optional mNNNNN message ref whose IMAGE payload you want restored (an image that was stripped or folded away). Pass \"list\" to enumerate every image currently restorable. Restored images are written to host-readable files and their paths returned — open them with the read tool. Independent of blockId/range and of CCR." } }, "required": [ @@ -889,7 +909,7 @@ }, "decompressAnthropic": { "name": "decompress", - "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context.", + "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context. Pass imageRef (an mNNNNN ref) to restore a stripped/folded image's original pixels to a file you open with the read tool; imageRef:\"list\" shows what is restorable.", "input_schema": { "type": "object", "properties": { @@ -912,6 +932,10 @@ "endId": { "type": "string", "description": "Optional mNNNNN message ref, inclusive upper bound. Used together with startId; omit both to restore the whole block." + }, + "imageRef": { + "type": "string", + "description": "Optional mNNNNN message ref whose IMAGE payload you want restored (an image that was stripped or folded away). Pass \"list\" to enumerate every image currently restorable. Restored images are written to host-readable files and their paths returned — open them with the read tool. Independent of blockId/range and of CCR." } }, "required": [ @@ -923,7 +947,7 @@ "type": "function", "function": { "name": "decompress", - "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context.", + "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context. Pass imageRef (an mNNNNN ref) to restore a stripped/folded image's original pixels to a file you open with the read tool; imageRef:\"list\" shows what is restorable.", "parameters": { "type": "object", "properties": { @@ -946,6 +970,10 @@ "endId": { "type": "string", "description": "Optional mNNNNN message ref, inclusive upper bound. Used together with startId; omit both to restore the whole block." + }, + "imageRef": { + "type": "string", + "description": "Optional mNNNNN message ref whose IMAGE payload you want restored (an image that was stripped or folded away). Pass \"list\" to enumerate every image currently restorable. Restored images are written to host-readable files and their paths returned — open them with the read tool. Independent of blockId/range and of CCR." } }, "required": [ @@ -957,7 +985,7 @@ "decompressResponses": { "type": "function", "name": "decompress", - "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context.", + "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context. Pass imageRef (an mNNNNN ref) to restore a stripped/folded image's original pixels to a file you open with the read tool; imageRef:\"list\" shows what is restorable.", "parameters": { "type": "object", "properties": { @@ -980,6 +1008,10 @@ "endId": { "type": "string", "description": "Optional mNNNNN message ref, inclusive upper bound. Used together with startId; omit both to restore the whole block." + }, + "imageRef": { + "type": "string", + "description": "Optional mNNNNN message ref whose IMAGE payload you want restored (an image that was stripped or folded away). Pass \"list\" to enumerate every image currently restorable. Restored images are written to host-readable files and their paths returned — open them with the read tool. Independent of blockId/range and of CCR." } }, "required": [ @@ -989,7 +1021,7 @@ }, "decompressGoogle": { "name": "decompress", - "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context.", + "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context. Pass imageRef (an mNNNNN ref) to restore a stripped/folded image's original pixels to a file you open with the read tool; imageRef:\"list\" shows what is restorable.", "parameters": { "type": "object", "properties": { @@ -1012,6 +1044,10 @@ "endId": { "type": "string", "description": "Optional mNNNNN message ref, inclusive upper bound. Used together with startId; omit both to restore the whole block." + }, + "imageRef": { + "type": "string", + "description": "Optional mNNNNN message ref whose IMAGE payload you want restored (an image that was stripped or folded away). Pass \"list\" to enumerate every image currently restorable. Restored images are written to host-readable files and their paths returned — open them with the read tool. Independent of blockId/range and of CCR." } }, "required": [ diff --git a/tests/golden/wire-contract/manifest-default.json b/tests/golden/wire-contract/manifest-default.json index 608ff91c57..6fed6d98ad 100644 --- a/tests/golden/wire-contract/manifest-default.json +++ b/tests/golden/wire-contract/manifest-default.json @@ -132,7 +132,7 @@ }, { "name": "decompress", - "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context.", + "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context. Pass imageRef (an mNNNNN ref) to restore a stripped/folded image's original pixels to a file you open with the read tool; imageRef:\"list\" shows what is restorable.", "input_schema": { "type": "object", "properties": { @@ -147,6 +147,10 @@ "full": { "type": "boolean", "description": "Restore all the way to original messages" + }, + "imageRef": { + "type": "string", + "description": "Optional mNNNNN message ref whose IMAGE payload you want restored (an image that was stripped or folded away). Pass \"list\" to enumerate every image currently restorable. Restored images are written to host-readable files and their paths returned — open them with the read tool. Independent of blockId/range and of CCR." } }, "required": [ @@ -326,7 +330,7 @@ "type": "function", "function": { "name": "decompress", - "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context.", + "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context. Pass imageRef (an mNNNNN ref) to restore a stripped/folded image's original pixels to a file you open with the read tool; imageRef:\"list\" shows what is restorable.", "parameters": { "type": "object", "properties": { @@ -341,6 +345,10 @@ "full": { "type": "boolean", "description": "Restore all the way to original messages" + }, + "imageRef": { + "type": "string", + "description": "Optional mNNNNN message ref whose IMAGE payload you want restored (an image that was stripped or folded away). Pass \"list\" to enumerate every image currently restorable. Restored images are written to host-readable files and their paths returned — open them with the read tool. Independent of blockId/range and of CCR." } }, "required": [ @@ -527,7 +535,7 @@ { "type": "function", "name": "decompress", - "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context.", + "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context. Pass imageRef (an mNNNNN ref) to restore a stripped/folded image's original pixels to a file you open with the read tool; imageRef:\"list\" shows what is restorable.", "parameters": { "type": "object", "properties": { @@ -542,6 +550,10 @@ "full": { "type": "boolean", "description": "Restore all the way to original messages" + }, + "imageRef": { + "type": "string", + "description": "Optional mNNNNN message ref whose IMAGE payload you want restored (an image that was stripped or folded away). Pass \"list\" to enumerate every image currently restorable. Restored images are written to host-readable files and their paths returned — open them with the read tool. Independent of blockId/range and of CCR." } }, "required": [ diff --git a/tests/golden/wire-contract/manifest-optin.json b/tests/golden/wire-contract/manifest-optin.json index 30d230024d..6de01d0876 100644 --- a/tests/golden/wire-contract/manifest-optin.json +++ b/tests/golden/wire-contract/manifest-optin.json @@ -135,7 +135,7 @@ }, { "name": "decompress", - "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context.", + "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context. Pass imageRef (an mNNNNN ref) to restore a stripped/folded image's original pixels to a file you open with the read tool; imageRef:\"list\" shows what is restorable.", "input_schema": { "type": "object", "properties": { @@ -158,6 +158,10 @@ "endId": { "type": "string", "description": "Optional mNNNNN message ref, inclusive upper bound. Used together with startId; omit both to restore the whole block." + }, + "imageRef": { + "type": "string", + "description": "Optional mNNNNN message ref whose IMAGE payload you want restored (an image that was stripped or folded away). Pass \"list\" to enumerate every image currently restorable. Restored images are written to host-readable files and their paths returned — open them with the read tool. Independent of blockId/range and of CCR." } }, "required": [ @@ -395,7 +399,7 @@ "type": "function", "function": { "name": "decompress", - "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context.", + "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context. Pass imageRef (an mNNNNN ref) to restore a stripped/folded image's original pixels to a file you open with the read tool; imageRef:\"list\" shows what is restorable.", "parameters": { "type": "object", "properties": { @@ -418,6 +422,10 @@ "endId": { "type": "string", "description": "Optional mNNNNN message ref, inclusive upper bound. Used together with startId; omit both to restore the whole block." + }, + "imageRef": { + "type": "string", + "description": "Optional mNNNNN message ref whose IMAGE payload you want restored (an image that was stripped or folded away). Pass \"list\" to enumerate every image currently restorable. Restored images are written to host-readable files and their paths returned — open them with the read tool. Independent of blockId/range and of CCR." } }, "required": [ @@ -671,7 +679,7 @@ { "type": "function", "name": "decompress", - "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context.", + "description": "Restores previously compressed content. Use when you need exact details lost in compression. By default restores one tier up. Use full:true for all the way to original messages. Use toFile to write to file instead of inflating context. Pass imageRef (an mNNNNN ref) to restore a stripped/folded image's original pixels to a file you open with the read tool; imageRef:\"list\" shows what is restorable.", "parameters": { "type": "object", "properties": { @@ -686,6 +694,10 @@ "full": { "type": "boolean", "description": "Restore all the way to original messages" + }, + "imageRef": { + "type": "string", + "description": "Optional mNNNNN message ref whose IMAGE payload you want restored (an image that was stripped or folded away). Pass \"list\" to enumerate every image currently restorable. Restored images are written to host-readable files and their paths returned — open them with the read tool. Independent of blockId/range and of CCR." } }, "required": [ diff --git a/tests/image-restore.test.ts b/tests/image-restore.test.ts new file mode 100644 index 0000000000..d3b0e9690c --- /dev/null +++ b/tests/image-restore.test.ts @@ -0,0 +1,186 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, mkdtempSync, readFileSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { anthropicToCore, googleToCore, openaiToCore, responsesToCore } from "acp-kernel/wire"; +import { createInitialState } from "acp-kernel"; +import { + buildIncomingImageIndex, + describeRestorable, + messageImageBytes, + writeRestoredImage, + type RestorableImage, +} from "../src/image-restore.ts"; +import { resolveDecompress, type ProxyToolCtx } from "../src/decompress-shared.ts"; +import type { WireProtocol } from "../src/util.js"; + +// Isolate stateDir() (hence restoreExportDir()) under a throwaway dir before any +// write. node --test gives each file its own process, so the env mutation is safe. +process.env.XDG_STATE_HOME = mkdtempSync(join(tmpdir(), "bili-img-restore-")); + +// A valid 1x1 PNG so decodeImageDims() resolves real dimensions. +const PNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="; +const pngImg: RestorableImage = { mediaType: "image/png", b64: PNG, bytes: Buffer.byteLength(PNG, "base64") }; +const dataUrl = `data:image/png;base64,${PNG}`; + +// Each wire converter has a distinct concrete signature; the test drives them +// uniformly on already-shaped bodies, so they are widened at the single call +// site below rather than forced into one callable type here. +const TO_CORE = { + anthropic: anthropicToCore, + openai: openaiToCore, + responses: responsesToCore, + google: googleToCore, +}; +function coreMsgs(r: unknown): Array<{ id?: string }> { + const m = Array.isArray(r) ? r : (r as { msgs?: unknown }).msgs; + return (Array.isArray(m) ? m : []) as Array<{ id?: string }>; +} +// Run the protocol parser, assign each produced core message a deterministic ref +// (m00001..), then build the index. excludeImaged leaves imaged messages unref'd to +// exercise the "unref'd tail messages are skipped" path. +function buildIndex(proto: WireProtocol, body: unknown, excludeImaged = false) { + const conv = TO_CORE[proto] as unknown as (b: unknown) => unknown; + const msgs = coreMsgs(conv(body)); + const state = createInitialState(); + msgs.forEach((m, i) => { + if (!m.id) return; + if (excludeImaged && messageImageBytes(m as never).length > 0) return; + state.messageRefs.byRaw[m.id] = `m${String(i + 1).padStart(5, "0")}`; + }); + return buildIncomingImageIndex(body, proto, state); +} +function ctxWith(index: Map | undefined): ProxyToolCtx { + // Only the imageRef branch of resolveDecompress is exercised here; it touches + // nothing but session.incomingImageIndex and log, so a minimal ctx suffices. + return { session: { incomingImageIndex: index }, log: () => undefined } as unknown as ProxyToolCtx; +} + +test("messageImageBytes: extracts base64 across all four wire sidecars", () => { + const anthro = messageImageBytes({ rawAnthropicBlock: { type: "image", source: { type: "base64", media_type: "image/png", data: PNG } } } as never); + assert.equal(anthro.length, 1); + assert.equal(anthro[0].b64, PNG); + assert.equal(anthro[0].mediaType, "image/png"); + + const anthroUrl = messageImageBytes({ rawAnthropicBlock: { type: "image", source: { type: "url", url: dataUrl } } } as never); + assert.equal(anthroUrl.length, 1); + assert.equal(anthroUrl[0].b64, PNG); + + // A tool_result block shares the sidecar field but is not an image. + assert.deepEqual(messageImageBytes({ rawAnthropicBlock: { type: "tool_result", content: [] } } as never), []); + + const oaMulti = messageImageBytes({ rawOpenaiContentParts: [{ type: "text", text: "hi" }, { type: "image_url", image_url: { url: dataUrl } }] } as never); + assert.equal(oaMulti.length, 1); + assert.equal(oaMulti[0].b64, PNG); + + const resp = messageImageBytes({ rawResponsesItem: { type: "message", role: "user", content: [{ type: "input_text", text: "see" }, { type: "input_image", image_url: dataUrl }] } } as never); + assert.equal(resp.length, 1); + assert.equal(resp[0].b64, PNG); + + const g = messageImageBytes({ rawGoogleParts: [{ text: "see" }, { inlineData: { mimeType: "image/png", data: PNG } }] } as never); + assert.equal(g.length, 1); + assert.equal(g[0].b64, PNG); + + // Singular fallback: the shared imageBase64 sidecar. + const single = messageImageBytes({ imageBase64: PNG, imageMediaType: "image/jpeg" } as never); + assert.equal(single.length, 1); + assert.equal(single[0].mediaType, "image/jpeg"); + + // Plain text carries nothing. + assert.deepEqual(messageImageBytes({ role: "user", text: "hello" } as never), []); +}); + +test("messageImageBytes: multi-image yields every part, not just the first", () => { + const two = messageImageBytes({ rawGoogleParts: [{ inlineData: { mimeType: "image/png", data: PNG } }, { inlineData: { mimeType: "image/gif", data: PNG } }] } as never); + assert.equal(two.length, 2); + assert.equal(two[0].mediaType, "image/png"); + assert.equal(two[1].mediaType, "image/gif"); +}); + +test("buildIncomingImageIndex: indexes carried images by mNNNNN ref (all protocols)", () => { + const openai = buildIndex("openai", { model: "gpt", messages: [ + { role: "user", content: [{ type: "text", text: "hi" }, { type: "image_url", image_url: { url: dataUrl } }] }, + { role: "assistant", content: "ok" }, + ] }); + assert.equal(openai.size, 1, "exactly one imaged message indexed"); + const [ref, imgs] = [...openai.entries()][0]; + assert.match(ref, /^m\d+$/); + assert.equal(imgs[0].b64, PNG); + + // Anthropic splits a multi-block message into one core msg per block; only the + // image block is indexed. + const anthro = buildIndex("anthropic", { model: "claude", messages: [ + { role: "user", content: [{ type: "text", text: "look" }, { type: "image", source: { type: "base64", media_type: "image/png", data: PNG } }] }, + { role: "assistant", content: [{ type: "text", text: "ok" }] }, + ] }); + assert.equal(anthro.size, 1); + assert.equal([...anthro.values()][0][0].b64, PNG); + + const responses = buildIndex("responses", { model: "gpt", input: [ + { type: "message", role: "user", content: [{ type: "input_text", text: "see" }, { type: "input_image", image_url: dataUrl }] }, + { type: "message", role: "assistant", content: [{ type: "output_text", text: "hi" }] }, + ] }); + assert.equal(responses.size, 1); + assert.equal([...responses.values()][0][0].b64, PNG); + + const google = buildIndex("google", { contents: [{ role: "user", parts: [{ text: "see" }, { inlineData: { mimeType: "image/png", data: PNG } }] }] }); + assert.equal(google.size, 1); + assert.equal([...google.values()][0][0].b64, PNG); +}); + +test("buildIncomingImageIndex: skips unref'd tail messages and image-free bodies", () => { + const body = { model: "gpt", messages: [ + { role: "user", content: [{ type: "image_url", image_url: { url: dataUrl } }] }, + { role: "assistant", content: "ok" }, + ] }; + // Leave the imaged message unref'd -> nothing recoverable even though an image is present. + assert.equal(buildIndex("openai", body, true).size, 0); + // No images at all -> empty. + assert.equal(buildIndex("openai", { model: "gpt", messages: [{ role: "user", content: "plain" }] }).size, 0); +}); + +test("describeRestorable: one line per image, sorted, capped", () => { + const idx = new Map([ + ["m00005", [pngImg, { ...pngImg, mediaType: "image/gif" }]], + ["m00002", [pngImg]], + ]); + const lines = describeRestorable(idx); + assert.equal(lines.length, 3); + assert.match(lines[0], /^m00002 \[png 1x1 · \d+KB\]$/); + assert.match(lines[1], /^m00005 \[png 1x1 · \d+KB\]$/); + assert.match(lines[2], /^m00005\[-1\] \[gif 1x1 · \d+KB\]$/); + assert.equal(describeRestorable(idx, 1).length, 1, "cap honored"); +}); + +test("writeRestoredImage: writes decoded bytes 0600 under retrieve/img, idempotent", () => { + const p = writeRestoredImage("m00042", 0, pngImg); + assert.ok(p && p.endsWith(join("retrieve", "img", "m00042.png")), `path ${p}`); + assert.ok(existsSync(p!)); + assert.deepEqual(readFileSync(p!), Buffer.from(PNG, "base64"), "decoded bytes round-trip"); + assert.equal(statSync(p!).mode & 0o777, 0o600, "not world-readable"); + // Multi-image suffix + extension mapping. + const p2 = writeRestoredImage("m00042", 1, pngImg); + assert.ok(p2!.endsWith("m00042-1.png")); + const jpg = writeRestoredImage("m00042", 0, { ...pngImg, mediaType: "image/jpeg" }); + assert.ok(jpg!.endsWith("m00042.jpg")); + // Idempotent rewrite of identical bytes. + assert.equal(writeRestoredImage("m00042", 0, pngImg), p); +}); + +test("resolveDecompress({ imageRef }): lists, restores to file, and reports misses", () => { + const idx = new Map([["m00042", [pngImg]]]); + const list = resolveDecompress({ imageRef: "list" }, ctxWith(idx)); + assert.match(list, /\[Restorable images \(1\):\]/); + assert.match(list, /m00042/); + + const restored = resolveDecompress({ imageRef: "m00042" }, ctxWith(idx)); + assert.match(restored, /Restored 1 image\(s\) for m00042/); + const pathMatch = restored.match(/(\S*m00042\.png)/); + assert.ok(pathMatch && existsSync(pathMatch[1]), "restored file exists"); + assert.deepEqual(readFileSync(pathMatch![1]), Buffer.from(PNG, "base64")); + + assert.match(resolveDecompress({ imageRef: "m99999" }, ctxWith(idx)), /no restorable image for ref "m99999"/); + assert.match(resolveDecompress({ imageRef: "" }, ctxWith(idx)), /\[Restorable images \(1\):\]/, "empty string == list"); + assert.match(resolveDecompress({ imageRef: "list" }, ctxWith(undefined)), /No restorable images right now/, "absent index degrades gracefully"); +}); From 3e449eb39fb687f60eec2eb1cc2936d328fa84d4 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Sun, 4 Oct 2026 11:09:33 +0800 Subject: [PATCH 02/11] test: #1995 extend #1179 decompress schema guard to the sanctioned imageRef addition The PR added an optional imageRef param plus an exact description note to decompress in all wire shapes but left the #1179 drift guard in tests/search-context-cross-session.test.ts pinning 'kernel + startId/endId only', so CI failed on all four test-matrix jobs. The guard now treats imageRef as a third sanctioned bili-only optional param and strips the note by exact suffix match (wording drift still fails the test). --- tests/search-context-cross-session.test.ts | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/tests/search-context-cross-session.test.ts b/tests/search-context-cross-session.test.ts index d6be8d5079..cb421ec58b 100644 --- a/tests/search-context-cross-session.test.ts +++ b/tests/search-context-cross-session.test.ts @@ -48,7 +48,7 @@ function compressInto(session: Session) { return core; } -type FlatTool = { name?: string; description?: string; input_schema?: Record; parameters?: Record; function?: { name?: string; parameters?: Record } }; +type FlatTool = { name?: string; description?: string; input_schema?: Record; parameters?: Record; function?: { name?: string; description?: string; parameters?: Record } }; function searchEntry(arr: readonly unknown[], shape: "flat" | "openai"): FlatTool | undefined { return arr.find((t) => { @@ -83,21 +83,24 @@ test("#841 schema: BILI arrays no longer add conversation_id to search_context ( const e = t as FlatTool; return shape === "openai" ? e.function?.name : e.name; }; - // #1179: decompress gains exactly two optional range params; everything else stays identical + // #1179: decompress gains exactly two optional range params; #1995 adds one optional imageRef param plus its exact description note; everything else stays identical + const IMAGE_NOTE = ` Pass imageRef (an mNNNNN ref) to restore a stripped/folded image's original pixels to a file you open with the read tool; imageRef:"list" shows what is restorable.`; const stripRange = (e: FlatTool): FlatTool => { const params = paramsOf(e) as Record; const props = { ...(params.properties as Record) }; delete props.startId; delete props.endId; + delete props.imageRef; const p = { ...params, properties: props }; - if (e.function) return { ...e, function: { ...e.function, parameters: p } }; - if (e.input_schema) return { ...e, input_schema: p }; - return { ...e, parameters: p }; + const note = (d?: string) => (d?.endsWith(IMAGE_NOTE) ? d.slice(0, -IMAGE_NOTE.length) : d); + if (e.function) return { ...e, function: { ...e.function, parameters: p, description: note(e.function.description) } }; + if (e.input_schema) return { ...e, input_schema: p, description: note(e.description) }; + return { ...e, parameters: p, description: note(e.description) }; }; const biliDec = bili.find((t) => nameOf(t) === DECOMPRESS_TOOL_NAME) as FlatTool | undefined; const kernelDec = kernel.find((t) => nameOf(t) === DECOMPRESS_TOOL_NAME) as FlatTool | undefined; assert.ok(biliDec && kernelDec, `decompress missing in ${shape} array`); - assert.deepEqual(stripRange(biliDec), stripRange(kernelDec), "decompress differs only by the added range params"); + assert.deepEqual(stripRange(biliDec), stripRange(kernelDec), "decompress differs only by the added range params + #1995 imageRef note"); const biliProps = paramsOf(biliDec).properties as Record>; assert.equal(biliProps.startId?.type, "string"); assert.equal(biliProps.endId?.type, "string"); From f23034501f4fcb09645001e39f175d77c81813df Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Sun, 4 Oct 2026 11:20:15 +0800 Subject: [PATCH 03/11] test: #1995 gate the 0600-mode assertion to POSIX (NTFS ignores mode bits) writeRestoredImage passes {mode:0o600} which NTFS does not apply, so the restored-file permission check failed both Windows test-matrix jobs with 438 !== 384. Byte round-trip and idempotency assertions stay platform-wide. --- tests/image-restore.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/image-restore.test.ts b/tests/image-restore.test.ts index d3b0e9690c..30e6847ea5 100644 --- a/tests/image-restore.test.ts +++ b/tests/image-restore.test.ts @@ -158,7 +158,7 @@ test("writeRestoredImage: writes decoded bytes 0600 under retrieve/img, idempote assert.ok(p && p.endsWith(join("retrieve", "img", "m00042.png")), `path ${p}`); assert.ok(existsSync(p!)); assert.deepEqual(readFileSync(p!), Buffer.from(PNG, "base64"), "decoded bytes round-trip"); - assert.equal(statSync(p!).mode & 0o777, 0o600, "not world-readable"); + if (process.platform !== "win32") assert.equal(statSync(p!).mode & 0o777, 0o600, "not world-readable"); // Multi-image suffix + extension mapping. const p2 = writeRestoredImage("m00042", 1, pngImg); assert.ok(p2!.endsWith("m00042-1.png")); From 51efa9a426b72b9757a71e55dddd28f8e0af034c Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sun, 4 Oct 2026 15:36:11 +0800 Subject: [PATCH 04/11] fix: #1995 bound incomingImageIndex memory by spilling images at index-time MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The review of #1995 found incomingImageIndex pinned every resent image's base64 in session memory for the session's lifetime — for screenshot-dense sessions that is ~cumulative image bytes, unbounded. Fix at the root: spill each image to /retrieve/img/ at index-time (skip-if-exists) and retain only metadata + path (IndexedImage), so residency is O(refs) regardless of image volume. decompress({ imageRef }) now returns the stored path (a pure lookup, never re-writing bytes); an externally-evicted file degrades to an explicit 're-spilled on next request' message instead of a dangling path. Non-strip sessions still pay nothing (index build gated off). No tool-schema change, so wire-contract goldens are untouched. --- src/decompress-shared.ts | 31 ++++++++++++----------- src/image-restore.ts | 49 +++++++++++++++++++++++++++---------- src/session.ts | 15 ++++++------ tests/image-restore.test.ts | 28 ++++++++++++--------- 4 files changed, 77 insertions(+), 46 deletions(-) diff --git a/src/decompress-shared.ts b/src/decompress-shared.ts index a39ee056d1..242791c6d3 100644 --- a/src/decompress-shared.ts +++ b/src/decompress-shared.ts @@ -12,7 +12,7 @@ import { type CoreMessage, type InlineRestoreResult, } from "acp-kernel"; -import { mkdirSync, unlinkSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, unlinkSync, writeFileSync } from "node:fs"; import { dirname, join, resolve as resolvePath } from "node:path"; import { tmpdir } from "node:os"; import { fileURLToPath } from "node:url"; @@ -22,7 +22,7 @@ import { ccrEnabled, contentStoreOf } from "./store.js"; import { safePrefix } from "./text-safe.js"; import { decompressTmpCap as knobDecompressTmpCap } from "./knobs.js"; import { toolFail, toolOk, type ProxyToolResult } from "./proxy-tool-result.js"; -import { describeRestorable, writeRestoredImage } from "./image-restore.js"; +import { describeRestorable } from "./image-restore.js"; /** Bounded retention for large-decompress temp files. Each decompress with * body > 10000 writes one file under tmpdir(); the reaper unlinks oldest past @@ -259,10 +259,10 @@ export function resolveDecompress( } // #1995: restore the original pixels of a stripped/folded image by ref. Delivery -// is file-first — each image is written under /retrieve/img/ and its -// path returned for the model to open with its read tool — uniform across all four -// wires (no per-protocol inline-image rendering). "list" enumerates what is -// currently restorable instead of writing anything. +// is file-first — images are spilled under /retrieve/img/ at index time +// and their paths returned for the model to open with its read tool — uniform +// across all four wires (no per-protocol inline-image rendering). "list" enumerates +// what is currently restorable instead of writing anything. function resolveImageRestore(args: Record, ctx: ProxyToolCtx): ProxyToolResult { const index = ctx.session.incomingImageIndex; const raw = typeof args.imageRef === "string" ? args.imageRef.trim() : ""; @@ -280,16 +280,19 @@ function resolveImageRestore(args: Record, ctx: ProxyToolCtx): if (!imgs || imgs.length === 0) { return toolFail(`[decompress FAILED: no restorable image for ref "${raw}" (it carries no image, is URL-sourced with no stored bytes, or is not in this request's history). Call decompress({ imageRef: "list" }) to see what is available.]`); } - const written: string[] = []; - for (let i = 0; i < imgs.length; i++) { - const p = writeRestoredImage(raw, i, imgs[i]); - if (p) written.push(p); + // Files were spilled at index-time, so restoring is a pure lookup: return the + // stored paths (verifying presence), never re-decoding or re-writing bytes. + const paths: string[] = []; + let missing = 0; + for (const im of imgs) { + if (existsSync(im.path)) paths.push(im.path); + else missing++; } - if (written.length === 0) { - return toolFail(`[decompress FAILED: could not write restored image(s) for "${raw}" to disk.]`); + if (paths.length === 0) { + return toolFail(`[decompress FAILED: the restored image(s) for "${raw}" are no longer on disk (evicted/cleaned since indexing). They will be re-spilled automatically on the next request.]`); } - ctx.log(`[acp-image-restore] ${raw}: restored ${written.length} image(s) → ${written.join(", ")}`); - return toolOk(`[Restored ${written.length} image(s) for ${raw}:\n${written.map((p) => ` ${p}`).join("\n")}\nOpen them with the read tool to view the pixels.]`); + ctx.log(`[acp-image-restore] ${raw}: located ${paths.length} image(s) at ${paths.join(", ")}${missing ? ` (${missing} missing)` : ""}`); + return toolOk(`[Restored ${paths.length} image(s) for ${raw}:\n${paths.map((p) => ` ${p}`).join("\n")}\nOpen them with the read tool to view the pixels.${missing ? `\n(${missing} image(s) could not be located on disk.)` : ""}]`); } // #1294 P2: close the loop on an inline restore — kernel K2 updates the diff --git a/src/image-restore.ts b/src/image-restore.ts index af5d171bea..53e9779f45 100644 --- a/src/image-restore.ts +++ b/src/image-restore.ts @@ -13,7 +13,7 @@ // sends no such bytes to the proxy, so those belong to the agent's in-process // recovery (cf. billion-context-pi#594), not here. -import { mkdirSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { anthropicToCore, @@ -42,6 +42,18 @@ export interface RestorableImage { bytes: number; } +/** A spilled image as retained in the session index: metadata plus the on-disk + * path, but NO base64 — the bytes live in the file, so a long image-heavy + * session pins only O(refs) of metadata in memory instead of every pixel + * (unbounded-residency finding from the #1995 review). */ +export interface IndexedImage { + mediaType: string; + bytes: number; + width?: number; + height?: number; + path: string; +} + function isObj(v: unknown): v is Record { return typeof v === "object" && v !== null; } @@ -152,8 +164,8 @@ export function buildIncomingImageIndex( parsed: unknown, protocol: WireProtocol, state: CompressionState, -): Map { - const index = new Map(); +): Map { + const index = new Map(); const byRaw = state?.messageRefs?.byRaw; if (!byRaw) return index; let result: unknown; @@ -174,9 +186,22 @@ export function buildIncomingImageIndex( if (!ref) continue; const imgs = messageImageBytes(m); if (imgs.length === 0) continue; - const existing = index.get(ref); - if (existing) existing.push(...imgs); - else index.set(ref, imgs); + const arr = index.get(ref) ?? []; + if (!index.has(ref)) index.set(ref, arr); + imgs.forEach((im, i) => { + // #1995 review: spill at index-time so the session retains only + // metadata + path (never base64). Skip-if-exists keeps the steady + // state to one stat per image per turn, not a full decode + write. + const path = writeRestoredImage(ref, i, im); + if (!path) return; + let width: number | undefined; + let height: number | undefined; + try { + const d = decodeImageDims(im.b64); + if (d) { width = d.w; height = d.h; } + } catch {} + arr.push({ mediaType: im.mediaType, bytes: im.bytes, width, height, path }); + }); } return index; } @@ -189,7 +214,7 @@ function refNum(ref: string): number { /** Human-readable one-line-per-image listing of what is currently restorable * ("m00042 [png 1024x768 · 240KB]"), sorted by ref then position. Capped so a * very image-heavy history cannot blow up the tool result. */ -export function describeRestorable(index: Map, cap = 50): string[] { +export function describeRestorable(index: Map, cap = 50): string[] { const lines: string[] = []; const refs = [...index.keys()].sort((a, b) => refNum(a) - refNum(b)); outer: for (const ref of refs) { @@ -197,10 +222,7 @@ export function describeRestorable(index: Map, cap = for (let i = 0; i < imgs.length; i++) { const im = imgs[i]; let note = im.mediaType.includes("/") ? im.mediaType.split("/").pop()! : im.mediaType; - try { - const dims = decodeImageDims(im.b64); - if (dims) note += ` ${dims.w}x${dims.h}`; - } catch {} + if (im.width != null && im.height != null) note += ` ${im.width}x${im.height}`; note += ` · ${Math.max(1, Math.round(im.bytes / 1024))}KB`; lines.push(`${ref}${i > 0 ? `[-${i}]` : ""} [${note}]`); if (lines.length >= cap) break outer; @@ -223,13 +245,14 @@ function extFor(mediaType: string): string { /** Write one restorable image to disk (decoded bytes, 0600 — conversation * content is not world-readable on multi-user hosts) and return its absolute - * path. Content-addressed by ref (+index), so a repeated restore rewrites - * identical bytes (idempotent). Returns null on write failure. */ + * path. Content-addressed by ref (+index); a repeated call skips the rewrite + * when the file is already present (idempotent). Returns null on write failure. */ export function writeRestoredImage(ref: string, idx: number, img: RestorableImage): string | null { const safeRef = ref.replace(/[^a-zA-Z0-9_-]/g, "-"); const dir = restoreExportDir(); const path = join(dir, `${safeRef}${idx > 0 ? `-${idx}` : ""}.${extFor(img.mediaType)}`); try { + if (existsSync(path)) return path; mkdirSync(dir, { recursive: true }); writeFileSync(path, Buffer.from(img.b64, "base64"), { mode: 0o600 }); return path; diff --git a/src/session.ts b/src/session.ts index 1286b7b466..2dd6b56461 100644 --- a/src/session.ts +++ b/src/session.ts @@ -337,13 +337,14 @@ export type Session = { * before the rework may still carry ccr:true entries; the reconcile/ * commit/drop machinery below handles them (they are never re-created). */ pendingRetrievals: PendingRetrieval[]; - /** #1995 in-memory only (NOT persisted — buildRecord omits it): ref → images - * index built per request from the INBOUND body while stripImages is armed, - * so decompress({ imageRef }) can pull a stripped/folded image's original - * pixels back. Latest-wins (the client re-sends full history every turn, so - * each request's index is complete); cleared when stripImages is off. Values - * hold references to base64 already resident from parsing the request. */ - incomingImageIndex?: Map>; + /** #1995 in-memory only (NOT persisted — buildRecord omits it): ref → images + * index built per request from the INBOUND body while stripImages is armed, + * so decompress({ imageRef }) can pull a stripped/folded image's original + * pixels back. Latest-wins (the client re-sends full history every turn, so + * each request's index is complete); cleared when stripImages is off. Values + * hold only metadata + the on-disk path (bytes are spilled at index-time and + * never retained), so residency stays O(refs) regardless of image volume. */ + incomingImageIndex?: Map>; /** #1095 in-memory only (NOT persisted): deterministic encode cache keyed * by sha256 of the ORIGINAL base64 → encoded payload. Identical inputs * must yield identical wire bytes across turns/restarts (prefix-cache diff --git a/tests/image-restore.test.ts b/tests/image-restore.test.ts index 30e6847ea5..d5a0ba21b7 100644 --- a/tests/image-restore.test.ts +++ b/tests/image-restore.test.ts @@ -10,6 +10,7 @@ import { describeRestorable, messageImageBytes, writeRestoredImage, + type IndexedImage, type RestorableImage, } from "../src/image-restore.ts"; import { resolveDecompress, type ProxyToolCtx } from "../src/decompress-shared.ts"; @@ -51,7 +52,7 @@ function buildIndex(proto: WireProtocol, body: unknown, excludeImaged = false) { }); return buildIncomingImageIndex(body, proto, state); } -function ctxWith(index: Map | undefined): ProxyToolCtx { +function ctxWith(index: Map | undefined): ProxyToolCtx { // Only the imageRef branch of resolveDecompress is exercised here; it touches // nothing but session.incomingImageIndex and log, so a minimal ctx suffices. return { session: { incomingImageIndex: index }, log: () => undefined } as unknown as ProxyToolCtx; @@ -106,7 +107,9 @@ test("buildIncomingImageIndex: indexes carried images by mNNNNN ref (all protoco assert.equal(openai.size, 1, "exactly one imaged message indexed"); const [ref, imgs] = [...openai.entries()][0]; assert.match(ref, /^m\d+$/); - assert.equal(imgs[0].b64, PNG); + assert.ok(existsSync(imgs[0].path), "image spilled to disk at index time"); + assert.deepEqual(readFileSync(imgs[0].path), Buffer.from(PNG, "base64"), "spilled bytes round-trip"); + assert.ok(!("b64" in imgs[0]), "index retains metadata + path only, never base64 (#1995 memory bound)"); // Anthropic splits a multi-block message into one core msg per block; only the // image block is indexed. @@ -115,18 +118,18 @@ test("buildIncomingImageIndex: indexes carried images by mNNNNN ref (all protoco { role: "assistant", content: [{ type: "text", text: "ok" }] }, ] }); assert.equal(anthro.size, 1); - assert.equal([...anthro.values()][0][0].b64, PNG); + assert.deepEqual(readFileSync([...anthro.values()][0][0].path), Buffer.from(PNG, "base64")); const responses = buildIndex("responses", { model: "gpt", input: [ { type: "message", role: "user", content: [{ type: "input_text", text: "see" }, { type: "input_image", image_url: dataUrl }] }, { type: "message", role: "assistant", content: [{ type: "output_text", text: "hi" }] }, ] }); assert.equal(responses.size, 1); - assert.equal([...responses.values()][0][0].b64, PNG); + assert.deepEqual(readFileSync([...responses.values()][0][0].path), Buffer.from(PNG, "base64")); const google = buildIndex("google", { contents: [{ role: "user", parts: [{ text: "see" }, { inlineData: { mimeType: "image/png", data: PNG } }] }] }); assert.equal(google.size, 1); - assert.equal([...google.values()][0][0].b64, PNG); + assert.deepEqual(readFileSync([...google.values()][0][0].path), Buffer.from(PNG, "base64")); }); test("buildIncomingImageIndex: skips unref'd tail messages and image-free bodies", () => { @@ -141,9 +144,10 @@ test("buildIncomingImageIndex: skips unref'd tail messages and image-free bodies }); test("describeRestorable: one line per image, sorted, capped", () => { - const idx = new Map([ - ["m00005", [pngImg, { ...pngImg, mediaType: "image/gif" }]], - ["m00002", [pngImg]], + const meta = (mediaType: string): IndexedImage => ({ mediaType, bytes: Buffer.byteLength(PNG, "base64"), width: 1, height: 1, path: "/nonexistent/x.png" }); + const idx = new Map([ + ["m00005", [meta("image/png"), meta("image/gif")]], + ["m00002", [meta("image/png")]], ]); const lines = describeRestorable(idx); assert.equal(lines.length, 3); @@ -169,16 +173,16 @@ test("writeRestoredImage: writes decoded bytes 0600 under retrieve/img, idempote }); test("resolveDecompress({ imageRef }): lists, restores to file, and reports misses", () => { - const idx = new Map([["m00042", [pngImg]]]); + const p = writeRestoredImage("m00042", 0, pngImg)!; + const idx = new Map([["m00042", [{ mediaType: "image/png", bytes: Buffer.byteLength(PNG, "base64"), width: 1, height: 1, path: p }]]]); const list = resolveDecompress({ imageRef: "list" }, ctxWith(idx)); assert.match(list, /\[Restorable images \(1\):\]/); assert.match(list, /m00042/); const restored = resolveDecompress({ imageRef: "m00042" }, ctxWith(idx)); assert.match(restored, /Restored 1 image\(s\) for m00042/); - const pathMatch = restored.match(/(\S*m00042\.png)/); - assert.ok(pathMatch && existsSync(pathMatch[1]), "restored file exists"); - assert.deepEqual(readFileSync(pathMatch![1]), Buffer.from(PNG, "base64")); + assert.ok(existsSync(p), "restored file exists"); + assert.deepEqual(readFileSync(p), Buffer.from(PNG, "base64")); assert.match(resolveDecompress({ imageRef: "m99999" }, ctxWith(idx)), /no restorable image for ref "m99999"/); assert.match(resolveDecompress({ imageRef: "" }, ctxWith(idx)), /\[Restorable images \(1\):\]/, "empty string == list"); From 9a354dbd792d500a86acfd5288efa3e573b5af28 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 6 Oct 2026 23:10:25 +0800 Subject: [PATCH 05/11] fix: namespace image restore files by session id (#1995 review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit mNNNNN refs are per-session sequence numbers, so the flat /retrieve/img/.png layout let two sessions' same-numbered refs collide: with skip-if-exists, whichever session spilled first owned the file forever, and every other session's decompress({imageRef}) for that number returned the FIRST session's pixels — with listing metadata (dims/bytes) describing the caller's own image, so the mismatch was invisible to the model. Adjacent CCR exports avoid this by rewriting on every retrieve; recovery here stays skip-if-exists (refs are deterministic within one session) and takes the other half of the fix: the session id is now part of the path. - restoreExportDir(sessionId) -> /retrieve/img// - buildIncomingImageIndex / writeRestoredImage take the session id - server.ts passes session.id at the index call site - regression test: two sessions, identical ref numbering, distinct bytes -> distinct files, each restores its own pixels Also resolves the rebase onto master's ProxyToolResult migration: resolveImageRestore now returns toolOk/toolFail outcomes. --- src/image-restore.ts | 26 ++++++++++------ src/server.ts | 2 +- tests/image-restore.test.ts | 62 +++++++++++++++++++++++++++++-------- 3 files changed, 67 insertions(+), 23 deletions(-) diff --git a/src/image-restore.ts b/src/image-restore.ts index 53e9779f45..a416e8c68c 100644 --- a/src/image-restore.ts +++ b/src/image-restore.ts @@ -164,6 +164,7 @@ export function buildIncomingImageIndex( parsed: unknown, protocol: WireProtocol, state: CompressionState, + sessionId: string, ): Map { const index = new Map(); const byRaw = state?.messageRefs?.byRaw; @@ -192,7 +193,7 @@ export function buildIncomingImageIndex( // #1995 review: spill at index-time so the session retains only // metadata + path (never base64). Skip-if-exists keeps the steady // state to one stat per image per turn, not a full decode + write. - const path = writeRestoredImage(ref, i, im); + const path = writeRestoredImage(ref, i, im, sessionId); if (!path) return; let width: number | undefined; let height: number | undefined; @@ -231,10 +232,14 @@ export function describeRestorable(index: Map, cap = 50) return lines; } -/** Directory restored images are written to: /retrieve/img/, sharing - * the CCR retrieve tree so operators find both under one place. */ -export function restoreExportDir(): string { - return join(stateDir(), "retrieve", "img"); +/** Directory restored images are written to: /retrieve/img//. + * mNNNNN refs are PER-SESSION sequence numbers, so the session id MUST be part + * of the path — a flat retrieve/img/ would let two sessions' same-numbered refs + * collide, and with skip-if-exists the first session's pixels would be served + * for the second session's ref forever (cross-session finding from review). */ +export function restoreExportDir(sessionId: string): string { + const safe = sessionId.replace(/[^a-zA-Z0-9_-]/g, "-").slice(0, 100) || "session"; + return join(stateDir(), "retrieve", "img", safe); } function extFor(mediaType: string): string { @@ -245,11 +250,14 @@ function extFor(mediaType: string): string { /** Write one restorable image to disk (decoded bytes, 0600 — conversation * content is not world-readable on multi-user hosts) and return its absolute - * path. Content-addressed by ref (+index); a repeated call skips the rewrite - * when the file is already present (idempotent). Returns null on write failure. */ -export function writeRestoredImage(ref: string, idx: number, img: RestorableImage): string | null { + * path. Addressed by session + ref (+index) — refs alone are per-session, so + * the session id is what keeps concurrent sessions from overwriting each + * other; a repeated call skips the rewrite when the file is already present + * (idempotent within one session, where refs are deterministic). Returns null + * on write failure. */ +export function writeRestoredImage(ref: string, idx: number, img: RestorableImage, sessionId: string): string | null { const safeRef = ref.replace(/[^a-zA-Z0-9_-]/g, "-"); - const dir = restoreExportDir(); + const dir = restoreExportDir(sessionId); const path = join(dir, `${safeRef}${idx > 0 ? `-${idx}` : ""}.${extFor(img.mediaType)}`); try { if (existsSync(path)) return path; diff --git a/src/server.ts b/src/server.ts index 5cc5529271..2858508be2 100644 --- a/src/server.ts +++ b/src/server.ts @@ -3235,7 +3235,7 @@ async function handle( // specific pixels back later. Gated on stripImages (recovery is only // meaningful when stripping removes something); latest-wins per request. if (cs.stripImages && protocol) { - session.incomingImageIndex = buildIncomingImageIndex(parsed, protocol, session.state); + session.incomingImageIndex = buildIncomingImageIndex(parsed, protocol, session.state, session.id); } else if (session.incomingImageIndex) { session.incomingImageIndex = undefined; } diff --git a/tests/image-restore.test.ts b/tests/image-restore.test.ts index d5a0ba21b7..c44f7963f7 100644 --- a/tests/image-restore.test.ts +++ b/tests/image-restore.test.ts @@ -41,7 +41,7 @@ function coreMsgs(r: unknown): Array<{ id?: string }> { // Run the protocol parser, assign each produced core message a deterministic ref // (m00001..), then build the index. excludeImaged leaves imaged messages unref'd to // exercise the "unref'd tail messages are skipped" path. -function buildIndex(proto: WireProtocol, body: unknown, excludeImaged = false) { +function buildIndex(proto: WireProtocol, body: unknown, excludeImaged = false, sessionId = "s1") { const conv = TO_CORE[proto] as unknown as (b: unknown) => unknown; const msgs = coreMsgs(conv(body)); const state = createInitialState(); @@ -50,7 +50,7 @@ function buildIndex(proto: WireProtocol, body: unknown, excludeImaged = false) { if (excludeImaged && messageImageBytes(m as never).length > 0) return; state.messageRefs.byRaw[m.id] = `m${String(i + 1).padStart(5, "0")}`; }); - return buildIncomingImageIndex(body, proto, state); + return buildIncomingImageIndex(body, proto, state, sessionId); } function ctxWith(index: Map | undefined): ProxyToolCtx { // Only the imageRef branch of resolveDecompress is exercised here; it touches @@ -158,33 +158,69 @@ test("describeRestorable: one line per image, sorted, capped", () => { }); test("writeRestoredImage: writes decoded bytes 0600 under retrieve/img, idempotent", () => { - const p = writeRestoredImage("m00042", 0, pngImg); - assert.ok(p && p.endsWith(join("retrieve", "img", "m00042.png")), `path ${p}`); + const p = writeRestoredImage("m00042", 0, pngImg, "sess-A"); + assert.ok(p && p.endsWith(join("retrieve", "img", "sess-A", "m00042.png")), `path ${p}`); assert.ok(existsSync(p!)); assert.deepEqual(readFileSync(p!), Buffer.from(PNG, "base64"), "decoded bytes round-trip"); if (process.platform !== "win32") assert.equal(statSync(p!).mode & 0o777, 0o600, "not world-readable"); // Multi-image suffix + extension mapping. - const p2 = writeRestoredImage("m00042", 1, pngImg); + const p2 = writeRestoredImage("m00042", 1, pngImg, "sess-A"); assert.ok(p2!.endsWith("m00042-1.png")); - const jpg = writeRestoredImage("m00042", 0, { ...pngImg, mediaType: "image/jpeg" }); + const jpg = writeRestoredImage("m00042", 0, { ...pngImg, mediaType: "image/jpeg" }, "sess-B"); assert.ok(jpg!.endsWith("m00042.jpg")); // Idempotent rewrite of identical bytes. - assert.equal(writeRestoredImage("m00042", 0, pngImg), p); + assert.equal(writeRestoredImage("m00042", 0, pngImg, "sess-A"), p); }); test("resolveDecompress({ imageRef }): lists, restores to file, and reports misses", () => { - const p = writeRestoredImage("m00042", 0, pngImg)!; + const p = writeRestoredImage("m00042", 0, pngImg, "sess-A")!; const idx = new Map([["m00042", [{ mediaType: "image/png", bytes: Buffer.byteLength(PNG, "base64"), width: 1, height: 1, path: p }]]]); - const list = resolveDecompress({ imageRef: "list" }, ctxWith(idx)); + const list = resolveDecompress({ imageRef: "list" }, ctxWith(idx)).text; assert.match(list, /\[Restorable images \(1\):\]/); assert.match(list, /m00042/); - const restored = resolveDecompress({ imageRef: "m00042" }, ctxWith(idx)); + const restored = resolveDecompress({ imageRef: "m00042" }, ctxWith(idx)).text; assert.match(restored, /Restored 1 image\(s\) for m00042/); assert.ok(existsSync(p), "restored file exists"); assert.deepEqual(readFileSync(p), Buffer.from(PNG, "base64")); - assert.match(resolveDecompress({ imageRef: "m99999" }, ctxWith(idx)), /no restorable image for ref "m99999"/); - assert.match(resolveDecompress({ imageRef: "" }, ctxWith(idx)), /\[Restorable images \(1\):\]/, "empty string == list"); - assert.match(resolveDecompress({ imageRef: "list" }, ctxWith(undefined)), /No restorable images right now/, "absent index degrades gracefully"); + assert.match(resolveDecompress({ imageRef: "m99999" }, ctxWith(idx)).text, /no restorable image for ref "m99999"/); + assert.equal(resolveDecompress({ imageRef: "m99999" }, ctxWith(idx)).outcome, "failure"); + assert.match(resolveDecompress({ imageRef: "" }, ctxWith(idx)).text, /\[Restorable images \(1\):\]/, "empty string == list"); + assert.match(resolveDecompress({ imageRef: "list" }, ctxWith(undefined)).text, /No restorable images right now/, "absent index degrades gracefully"); +}); + +test("cross-session isolation: same ref number in two sessions never collides", () => { + // Regression for the review blocker: refs are per-session sequence numbers, + // so a flat retrieve/img/ let session B's m00001 hit session A's file via + // skip-if-exists — B's restore would return A's pixels. The session id is + // now part of the directory, so each session spills under its own tree. + const GIF = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"; + const gifImg: RestorableImage = { mediaType: "image/gif", b64: GIF, bytes: Buffer.byteLength(GIF, "base64") }; + const pa = writeRestoredImage("m00001", 0, pngImg, "conv-alpha")!; + const pb = writeRestoredImage("m00001", 0, gifImg, "conv-beta")!; + assert.notEqual(pa, pb, "two sessions' m00001 must be distinct files"); + assert.ok(pa.includes(join("retrieve", "img", "conv-alpha"))); + assert.ok(pb.includes(join("retrieve", "img", "conv-beta"))); + assert.deepEqual(readFileSync(pa), Buffer.from(PNG, "base64"), "alpha's file holds alpha's pixels"); + assert.deepEqual(readFileSync(pb), Buffer.from(GIF, "base64"), "beta's file holds beta's pixels — not skipped as a duplicate"); + + // End-to-end through the index builder: identical ref numbering, different + // sessions -> each index's path resolves to that session's own bytes. + const body = { model: "gpt", messages: [ + { role: "user", content: [{ type: "text", text: "see" }, { type: "image_url", image_url: { url: dataUrl } }] }, + { role: "assistant", content: "ok" }, + ] }; + const bodyGif = { model: "gpt", messages: [ + { role: "user", content: [{ type: "text", text: "see" }, { type: "image_url", image_url: { url: `data:image/gif;base64,${GIF}` } }] }, + { role: "assistant", content: "ok" }, + ] }; + const idxA = buildIndex("openai", body, false, "conv-alpha"); + const idxB = buildIndex("openai", bodyGif, false, "conv-beta"); + const a = [...idxA.entries()][0]; + const b = [...idxB.entries()][0]; + assert.equal(a[0], b[0], "both sessions legitimately number the image m00001-style"); + assert.notEqual(a[1][0].path, b[1][0].path, "but the spilled paths differ by session"); + assert.deepEqual(readFileSync(a[1][0].path), Buffer.from(PNG, "base64")); + assert.deepEqual(readFileSync(b[1][0].path), Buffer.from(GIF, "base64"), "beta restores its own pixels, not alpha's"); }); From dccf575400f2731e00234626f72c54f58c0dd1d1 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 6 Oct 2026 23:35:25 +0800 Subject: [PATCH 06/11] fix: index tool-result-nested images so every stripped shape is recoverable (#1995 review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit stripNestedImages removes images from anthropic tool_result.content, Responses function_call_output/custom_tool_call_output .output, and Gemini functionResponse.parts — but messageImageBytes only walked the plain-content sidecars, so that whole class was stripped with no recovery path (the exact #1995 failure, just for nested shapes). - anthropic: walk tool_result.content[] image blocks (base64 + data-URL) - responses: pick the parts array by item type (.output for function_call_output / custom_tool_call_output, .content otherwise), mirroring the strip side's key choice exactly - google: descend into functionResponse.parts for image-mime inlineData; nested fileData stays unindexable (remote reference, no bytes transit the proxy — same disclosed class as URL-sourced images) Tests: per-wire nested extraction (incl. pdf part untouched, fileData skip) + end-to-end anthropic tool_result recovery through the index builder (spilled under the tool message's ref, pixels round-trip). --- src/image-restore.ts | 66 ++++++++++++++++++++++++++++++------- tests/image-restore.test.ts | 52 +++++++++++++++++++++++++++++ 2 files changed, 106 insertions(+), 12 deletions(-) diff --git a/src/image-restore.ts b/src/image-restore.ts index a416e8c68c..5a2e5cd984 100644 --- a/src/image-restore.ts +++ b/src/image-restore.ts @@ -69,10 +69,13 @@ function b64Bytes(b64: string): number { } /** The base64 images this core message carries, in wire order, across all four - * protocols (anthropic / openai / responses / google). URL-sourced images whose - * bytes we cannot obtain (non-data URLs) yield no entry — only carryable - * base64 payloads are indexed. Returns [] for plain-text messages (the common - * case). */ + * protocols (anthropic / openai / responses / google) — INCLUDING images nested + * in tool results (anthropic tool_result.content, Responses function_call_output + * .output, Gemini functionResponse.parts), which the strip side also removes: + * every stripped shape must have a recovery path or it is lost forever (#1995). + * URL/fileData-sourced images whose bytes we cannot obtain yield no entry — + * only carryable base64 payloads are indexed. Returns [] for plain-text + * messages (the common case). */ export function messageImageBytes(m: CoreMessage): RestorableImage[] { const mm = m as BiliMessage; const out: RestorableImage[] = []; @@ -92,22 +95,51 @@ export function messageImageBytes(m: CoreMessage): RestorableImage[] { } return out; } + // Anthropic tool_results carry images NESTED in their content array — the + // strip side removes them (stripNestedImages), so they must be indexed here + // too or that whole class would be stripped-but-unrecoverable (#1995). + if (isObj(ab) && ab.type === "tool_result" && Array.isArray(ab.content)) { + for (const c of ab.content) { + if (!isObj(c) || c.type !== "image") continue; + const s = c.source; + const mediaType = isObj(s) && typeof s.media_type === "string" ? s.media_type : "image/png"; + if (!isObj(s)) continue; + if (s.type === "base64" && typeof s.data === "string") { + out.push({ mediaType, b64: s.data, bytes: b64Bytes(s.data) }); + } else if (s.type === "url") { + const r = dataUrlRef(s.url); + if (r?.b64) out.push({ mediaType: r.mediaType ?? mediaType, b64: r.b64, bytes: b64Bytes(r.b64) }); + } + } + return out; + } // Responses: the original item keeps every input_image part (the singular // imageBase64 sidecar covers only the first), so walk the item's content. + // Tool outputs (function_call_output / custom_tool_call_output) keep their + // parts in `.output` instead of `.content` — the strip side reads them from + // there, so the index must too (#1995 nested-tool-image parity). const ri = mm.rawResponsesItem; - if (isObj(ri) && Array.isArray(ri.content)) { - for (const part of ri.content) { - if (!isObj(part) || part.type !== "input_image") continue; - const u = isObj(part.image_url) ? part.image_url.url : part.image_url; - const r = dataUrlRef(u); - if (r?.b64) out.push({ mediaType: r.mediaType ?? "image/png", b64: r.b64, bytes: b64Bytes(r.b64) }); + if (isObj(ri)) { + const arr = ri.type === "function_call_output" || ri.type === "custom_tool_call_output" + ? (Array.isArray(ri.output) ? ri.output : undefined) + : (Array.isArray(ri.content) ? ri.content : undefined); + if (arr) { + for (const part of arr) { + if (!isObj(part) || part.type !== "input_image") continue; + const u = isObj(part.image_url) ? part.image_url.url : part.image_url; + const r = dataUrlRef(u); + if (r?.b64) out.push({ mediaType: r.mediaType ?? "image/png", b64: r.b64, bytes: b64Bytes(r.b64) }); + } + if (out.length > 0) return out; } - if (out.length > 0) return out; } // Multi-part sources come FIRST: the shared singular imageBase64 sidecar is // set by every protocol for a single data-URL image, so checking it earlier // would shadow the multi-part fields and drop every image after the first. - // Google: inlineData parts (raw base64 in .data, mime in .mimeType). + // Google: inlineData parts (raw base64 in .data, mime in .mimeType), plus + // images NESTED in functionResponse.parts — the strip side removes those + // too (image-mime inlineData/fileData there). fileData entries are remote + // references with no carried bytes, so only inlineData is indexable. if (Array.isArray(mm.rawGoogleParts)) { for (const part of mm.rawGoogleParts as unknown[]) { if (!isObj(part)) continue; @@ -116,6 +148,16 @@ export function messageImageBytes(m: CoreMessage): RestorableImage[] { const mediaType = typeof inline.mimeType === "string" ? inline.mimeType : "image/png"; out.push({ mediaType, b64: inline.data, bytes: b64Bytes(inline.data) }); } + const fr = part.functionResponse; + if (isObj(fr) && Array.isArray(fr.parts)) { + for (const np of fr.parts) { + if (!isObj(np)) continue; + const ni = np.inlineData; + if (isObj(ni) && typeof ni.data === "string" && typeof ni.mimeType === "string" && ni.mimeType.startsWith("image/")) { + out.push({ mediaType: ni.mimeType, b64: ni.data, bytes: b64Bytes(ni.data) }); + } + } + } } if (out.length > 0) return out; } diff --git a/tests/image-restore.test.ts b/tests/image-restore.test.ts index c44f7963f7..1483cf04bb 100644 --- a/tests/image-restore.test.ts +++ b/tests/image-restore.test.ts @@ -224,3 +224,55 @@ test("cross-session isolation: same ref number in two sessions never collides", assert.deepEqual(readFileSync(a[1][0].path), Buffer.from(PNG, "base64")); assert.deepEqual(readFileSync(b[1][0].path), Buffer.from(GIF, "base64"), "beta restores its own pixels, not alpha's"); }); + +test("messageImageBytes: tool-result-nested images are indexed on every wire that strips them", () => { + // anthropic tool_result.content — strip side removes these (stripNestedImages), + // so the index must see them or they are unrecoverable. + const tr = messageImageBytes({ rawAnthropicBlock: { type: "tool_result", tool_use_id: "t1", content: [ + { type: "text", text: "screenshot attached" }, + { type: "image", source: { type: "base64", media_type: "image/png", data: PNG } }, + { type: "image", source: { type: "url", url: dataUrl } }, + ] } } as never); + assert.equal(tr.length, 2, "both nested images extracted, text part ignored"); + assert.equal(tr[0].b64, PNG); + assert.equal(tr[1].mediaType, "image/png"); + + // responses function_call_output keeps parts in `.output`, not `.content`. + const fco = messageImageBytes({ rawResponsesItem: { type: "function_call_output", call_id: "c1", output: [ + { type: "output_text", text: "see" }, + { type: "input_image", image_url: dataUrl }, + ] } } as never); + assert.equal(fco.length, 1, "image found in .output array"); + assert.equal(fco[0].b64, PNG); + + // google functionResponse.parts nested inlineData (image mime only). + const fr = messageImageBytes({ rawGoogleParts: [{ functionResponse: { name: "shot", parts: [ + { inlineData: { mimeType: "image/png", data: PNG } }, + { inlineData: { mimeType: "application/pdf", data: "AAAA" } }, // document: stripped? no — not an image mime, strip keeps it + ] } } ] } as never); + assert.equal(fr.length, 1, "nested image-mime inlineData indexed, pdf part left alone"); + + // google nested fileData is a remote reference with no bytes -> nothing indexable. + const fd = messageImageBytes({ rawGoogleParts: [{ functionResponse: { name: "shot", parts: [ + { fileData: { mimeType: "image/png", fileUri: "https://files.example/x.png" } }, + ] } } ] } as never); + assert.equal(fd.length, 0, "remote fileData carries no bytes to recover"); +}); + +test("buildIncomingImageIndex: end-to-end nested tool_result recovery (anthropic)", () => { + // A user turn with a tool_use, then a tool_result carrying a screenshot. + // The strip side drops the nested image on the next turn; the index must + // have spilled it under the tool message's ref before that happens. + const idx = buildIndex("anthropic", { model: "claude", messages: [ + { role: "user", content: [{ type: "text", text: "run it" }, { type: "tool_use", id: "t1", name: "screenshot", input: {} }] }, + { role: "assistant", content: [{ type: "text", text: "running" }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: [ + { type: "image", source: { type: "base64", media_type: "image/png", data: PNG } }, + ] }] }, + ] }); + assert.equal(idx.size, 1, "the tool_result message is indexed"); + const [ref, imgs] = [...idx.entries()][0]; + assert.match(ref, /^m\d+$/); + assert.ok(existsSync(imgs[0].path), "nested image spilled at index time"); + assert.deepEqual(readFileSync(imgs[0].path), Buffer.from(PNG, "base64"), "nested pixels round-trip"); +}); From fb52111ecf202cd0f5d6c89474bc32ffde197d2a Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Wed, 7 Oct 2026 00:47:25 +0800 Subject: [PATCH 07/11] fix: fold-anchored stripImages cutoff, ref-carrying summary notes, restore-file eviction (#1995 gap 2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Kernel: - stripHistoricalImages gains opts.cutoffIndex (protocol-neutral): an explicit wire-message index replaces the sliding len-keepRecent cutoff, so a host can pin the strip boundary and keep the stripped prefix byte-stable between compression events (prompt-cache stability — the sliding window breaks the cache at the image bytes every turn). - anthropicToCore tags every flattened core message with its source wire ordinal (BiliMessage.wireIndex) so hosts can map fold coverage (core ids) back to wire positions without re-deriving codec split behavior. - image-only anthropic tool_results collapse to the empty string instead of a "[image]" text part: the derived id is seeded from concatenated TEXT parts, so "" keeps it byte-identical across the strip ("[image]" would flip it). - kernel 0.0.104 -> 0.0.105. Host: - foldAnchoredCutoff (anthropic only — the other wires flip ids on strip and keep the sliding window until placeholders are id-neutral): with an active fold, the strip cutoff anchors to the last covered wire message; a partially-covered boundary wire message (live image in the same message) is never stripped. Falls back to the sliding window when nothing is covered. - server wires the anchor into stripHistoricalImages; count_tokens requests keep the same cutoff (token parity) but skip the bookkeeping index rebuild. - summary image notes now carry the ref ([image: png 1024x768 · m00042]) so the fold's own text points at decompress({imageRef}) long after the wire dropped the pixels. - pruneRetrieveImgExports: best-effort 7-day TTL eviction for spilled restore files (throttled to once a minute in the request path; emptied dirs removed). Tests: kernel wire-strip-cutoff (5), host strip-cutoff-anchor (7); existing kernel pins updated for the empty-string tool_result collapse. --- kernel/package.json | 2 +- kernel/src/wire/anthropic.ts | 9 +- kernel/src/wire/bili-message.ts | 7 + kernel/src/wire/strip-images.ts | 29 +++- kernel/tests/wire-strip-cutoff.test.ts | 199 +++++++++++++++++++++++++ kernel/tests/wire-strip-images.test.ts | 8 +- src/config.ts | 17 ++- src/image-note.ts | 13 ++ src/image-restore.ts | 112 +++++++++++++- src/preflight.ts | 7 +- src/server.ts | 23 ++- src/session.ts | 22 +-- tests/responses-tool-images.test.ts | 4 +- tests/strip-cutoff-anchor.test.ts | 137 +++++++++++++++++ 14 files changed, 562 insertions(+), 27 deletions(-) create mode 100644 kernel/tests/wire-strip-cutoff.test.ts create mode 100644 tests/strip-cutoff-anchor.test.ts diff --git a/kernel/package.json b/kernel/package.json index b86a0ffe82..3dc5533b9f 100644 --- a/kernel/package.json +++ b/kernel/package.json @@ -1,6 +1,6 @@ { "name": "acp-kernel", - "version": "0.0.104", + "version": "0.0.105", "description": "Framework-agnostic context-compression engine (model-driven, 3-tier LSM). Pure core: no host dependency.", "license": "MIT", "author": "ranxianglei", diff --git a/kernel/src/wire/anthropic.ts b/kernel/src/wire/anthropic.ts index 90e9ce646b..fc92a3ed9a 100644 --- a/kernel/src/wire/anthropic.ts +++ b/kernel/src/wire/anthropic.ts @@ -90,7 +90,11 @@ export function anthropicToCore(body: AnthropicRequestBody): Flat { // (excludeTools / protectedTools / isNeverPreserveRecent) are name-based. // Not part of the result identity seed — ids must stay stable across versions. const toolNames = new Map(); - for (const m of body.messages) { + for (const [wireIndex, m] of body.messages.entries()) { + // #1995: record the source wire ordinal so host-side strip anchoring can + // map fold coverage (core-message space) back to wire positions without + // re-deriving the converter's block-split behavior. + const before = msgs.length; const blocks = typeof m.content === "string" ? [{ type: "text" as const, text: m.content }] @@ -198,6 +202,9 @@ export function anthropicToCore(body: AnthropicRequestBody): Flat { } } } + for (let k = before; k < msgs.length; k++) { + (msgs[k] as BiliMessage).wireIndex = wireIndex; + } } return { msgs, cacheControls }; } diff --git a/kernel/src/wire/bili-message.ts b/kernel/src/wire/bili-message.ts index ee5f1aafff..b8d7a0e7c2 100644 --- a/kernel/src/wire/bili-message.ts +++ b/kernel/src/wire/bili-message.ts @@ -42,6 +42,13 @@ export interface BiliMessage extends CoreMessage { * the content from these when present, so parts the core does not model * survive a round-trip. */ rawGoogleParts?: unknown[]; + /** Source wire-message ordinal for this core message, tagged by the + * converters (`wireIndex` of the protocol message it was flattened from). + * Host-side consumers use it to translate core-space fold coverage back + * into wire positions (e.g. #1995's fold-anchored stripImages cutoff) + * without re-deriving each codec's block-split behavior. Optional: + * converters adopt it incrementally; absence means "unknown". */ + wireIndex?: number; /** Anthropic thinking signature. Anthropic verifies thinking+signature * pairs; without it the request is rejected. Stored alongside the * reasoning text so coreToAnthropic can reattach it. */ diff --git a/kernel/src/wire/strip-images.ts b/kernel/src/wire/strip-images.ts index b391ca2e7c..378734d991 100644 --- a/kernel/src/wire/strip-images.ts +++ b/kernel/src/wire/strip-images.ts @@ -83,7 +83,14 @@ function stripNestedImages( return { part: { ...part, - content: kept.length > 0 ? kept : placeholderContent(protocol), + // #1995: an image-only tool_result collapses to the EMPTY STRING, not + // a "[image]" text part. anthropicToCore seeds the tool_result id from + // its concatenated TEXT parts (images contribute ""), so "" keeps the + // derived id byte-identical pre/post strip — a "[image]" part would + // flip the id and churn the ref projection / fold anchoring state + // (stripImages anchoring, src/image-restore.ts). String content is + // valid Anthropic tool_result shape. + content: kept.length > 0 ? kept : "", }, removed, }; @@ -140,19 +147,31 @@ function stripParts( /** Drop image parts from every message older than the most recent `keepRecent`. * `protocol` selects the wire dialect; `null` (unparseable) is a no-op. Returns * `{ body, removed }` where `body` is the input reference untouched (and - * `removed` is 0) when there was nothing to strip. */ + * `removed` is 0) when there was nothing to strip. + * + * `opts.cutoffIndex` (protocol-neutral, #1995): when present, replaces the + * sliding `len - keepRecent` cutoff with an explicit wire-message index — + * strip messages at index < cutoffIndex. Hosts use this to anchor the strip + * boundary to fold coverage so the stripped prefix only moves on compression + * events (prompt-cache stability) instead of every turn. When absent the + * historical sliding-window behavior applies. */ export function stripHistoricalImages( body: unknown, protocol: StripProtocol, keepRecent: number, + opts?: { cutoffIndex?: number }, ): StripResult { if (!protocol || !isObj(body)) return { body, removed: 0 }; const recentCount = Math.max(0, Math.floor(keepRecent)); + const explicitCutoff = + opts?.cutoffIndex !== undefined && Number.isFinite(opts.cutoffIndex) + ? Math.max(0, Math.floor(opts.cutoffIndex)) + : undefined; if (protocol === "responses") { const input = body.input; if (!Array.isArray(input)) return { body, removed: 0 }; - const cutoff = input.length - recentCount; + const cutoff = explicitCutoff ?? input.length - recentCount; let removed = 0; let touched = false; const nextInput = input.map((item, i) => { @@ -178,7 +197,7 @@ export function stripHistoricalImages( if (protocol === "google") { const contents = body.contents; if (!Array.isArray(contents)) return { body, removed: 0 }; - const cutoff = contents.length - recentCount; + const cutoff = explicitCutoff ?? contents.length - recentCount; let removed = 0; let touched = false; const nextContents = contents.map((c, i) => { @@ -198,7 +217,7 @@ export function stripHistoricalImages( const messages = body.messages; if (!Array.isArray(messages)) return { body, removed: 0 }; - const cutoff = messages.length - recentCount; + const cutoff = explicitCutoff ?? messages.length - recentCount; let removed = 0; let touched = false; const nextMessages = messages.map((m, i) => { diff --git a/kernel/tests/wire-strip-cutoff.test.ts b/kernel/tests/wire-strip-cutoff.test.ts new file mode 100644 index 0000000000..553cdfaec0 --- /dev/null +++ b/kernel/tests/wire-strip-cutoff.test.ts @@ -0,0 +1,199 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { stripHistoricalImages } from "../src/wire/strip-images.js"; +import { anthropicToCore } from "../src/wire/anthropic.js"; +import { hasMediaPayload } from "../src/protected.js"; +import type { AnthropicRequestBody } from "../src/wire/anthropic.js"; + +const DATA_URL = "data:image/png;base64,AAAA"; +const antImg = () => ({ + type: "image", + source: { type: "base64", media_type: "image/png", data: "AAAA" }, +}); +const antTxt = (t: string) => ({ type: "text", text: t }); +const oaiImg = (url: string) => ({ type: "image_url", image_url: { url } }); +const oaiTxt = (t: string) => ({ type: "text", text: t }); +const rspImg = (url: string) => ({ type: "input_image", image_url: url }); +const rspTxt = (t: string) => ({ type: "input_text", text: t }); + +/** #1995 gap 2: an explicit cutoffIndex replaces the sliding window. The + * stripped PREFIX must be byte-identical turn-over-turn (prompt-cache + * stability) — with an anchor, appending a new message does not move the + * boundary; with the legacy sliding window it does. */ +test("anthropic: cutoffIndex anchors the strip boundary; sliding moves it", () => { + const build = (n: number): AnthropicRequestBody => ({ + model: "claude", + messages: [ + { role: "user", content: [antTxt("look"), antImg()] }, + { role: "assistant", content: [antImg()] }, + { role: "user", content: [antTxt("hi"), antImg()] }, + ...Array.from({ length: n }, (_, i) => ({ + role: "user" as const, + content: [antTxt(`tail ${i}`)], + })), + ], + }); + const t0 = build(0); + const t1 = build(1); // one new message appended next turn + + // Anchor says: everything before wire index 3 is fold-covered. + const anchored0 = stripHistoricalImages(t0, "anthropic", 1, { cutoffIndex: 3 }); + const anchored1 = stripHistoricalImages(t1, "anthropic", 1, { cutoffIndex: 3 }); + assert.equal(anchored0.removed, 3); + assert.equal(anchored1.removed, 3); + const p0 = (anchored0.body as AnthropicRequestBody).messages.slice(0, 3); + const p1 = (anchored1.body as AnthropicRequestBody).messages.slice(0, 3); + assert.deepEqual(p1, p0); // prefix stable → cache break stays at the anchor + + // Legacy sliding window with keepRecent=1: the boundary moves every turn — + // at t0 (3 messages) the window keeps message 2 untouched; at t1 (one tail + // appended) message 2 crosses the window and gets freshly stripped (new + // cache break), while the anchor strips it IDENTICALLY in both turns. + const slide0 = stripHistoricalImages(t0, "anthropic", 1); + assert.deepEqual( + (slide0.body as AnthropicRequestBody).messages[2].content, + [antTxt("hi"), antImg()], + ); + const slide1 = stripHistoricalImages(t1, "anthropic", 1); + assert.deepEqual( + (slide1.body as AnthropicRequestBody).messages[2].content, + [antTxt("hi")], + ); + assert.deepEqual( + (anchored1.body as AnthropicRequestBody).messages[2].content, + [antTxt("hi")], + ); + // The uncovered tail never gets stripped under the anchor: + assert.deepEqual( + (anchored1.body as AnthropicRequestBody).messages[3].content, + [antTxt("tail 0")], + ); +}); + +test("cutoffIndex works for all four protocols (strip strictly before cutoff)", () => { + // openai + const oai = { + model: "gpt", + messages: [ + { role: "user", content: [oaiTxt("a"), oaiImg(DATA_URL)] }, + { role: "user", content: [oaiTxt("b")] }, + { role: "user", content: [oaiTxt("c"), oaiImg(DATA_URL)] }, + ], + }; + const r1 = stripHistoricalImages(oai, "openai", 5, { cutoffIndex: 3 }); + assert.equal(r1.removed, 2); // keepRecent=5 would strip nothing; anchor overrides + + // responses + const rsp = { + model: "gpt", + input: [ + { role: "user", content: [rspTxt("a"), rspImg(DATA_URL)] }, + { role: "user", content: [rspTxt("b")] }, + ], + }; + const r2 = stripHistoricalImages(rsp, "responses", 5, { cutoffIndex: 2 }); + assert.equal(r2.removed, 1); + + // google + const goo = { + contents: [ + { role: "user", parts: [{ text: "a" }, { inlineData: { mimeType: "image/png", data: "AAAA" } }] }, + { role: "user", parts: [{ text: "b" }] }, + ], + }; + const r3 = stripHistoricalImages(goo, "google", 5, { cutoffIndex: 2 }); + assert.equal(r3.removed, 1); +}); + +test("cutoffIndex clamps negative/NaN to the sliding fallback contract", () => { + const body = { + model: "claude", + messages: [ + { role: "user", content: [antTxt("a"), antImg()] }, + { role: "user", content: [antTxt("b")] }, + ], + }; + // Non-finite → ignored (sliding applies: keepRecent 2 keeps everything) + const r = stripHistoricalImages(body, "anthropic", 2, { cutoffIndex: Number.NaN }); + assert.equal(r.removed, 0); + // Negative clamps to 0 → strip nothing (same as keep-all) + const r2 = stripHistoricalImages(body, "anthropic", 2, { cutoffIndex: -3 }); + assert.equal(r2.removed, 0); +}); + +/** #1995 fold-anchoring id-stability invariant: stripping must not perturb + * the ids of messages a fold can COVER. Image-bearing messages (top-level + * image blocks, mixed/image-only tool_results with non-text content) are + * hasMediaPayload gaps — never compressible — so their ids may flip or drop + * without orphaning any fold. The ids that MUST survive are: text messages + * (no-op), image-only top-level messages (placeholder "[image]" IS the + * converter's id seed for image blocks), and image-only tool_results (the + * empty-string collapse added in this change — a "[image]" text part would + * have joined as "[image]" instead of "" and flipped the seed). */ +test("anthropic: strip keeps fold-coverable message ids stable", () => { + const body: AnthropicRequestBody = { + model: "claude", + messages: [ + { role: "user", content: [antTxt("plain question")] }, + { + role: "user", + content: [ + { type: "tool_result", tool_use_id: "t1", content: [{ type: "image", source: { type: "base64", media_type: "image/png", data: "AAAA" } }] }, + ], + }, + { role: "user", content: [antImg()] }, // image-only top-level + { role: "user", content: [antTxt("q"), antImg()] }, // mixed top-level + ], + }; + const before = anthropicToCore(body).msgs; + const strippedBody = stripHistoricalImages(body, "anthropic", 0).body as AnthropicRequestBody; + const after = anthropicToCore(strippedBody).msgs; + + const keyOf = (m: { text?: string; toolCallId?: string }) => + m.toolCallId ?? m.text ?? ""; + const beforeById = new Map(before.map((m) => [keyOf(m), m.id])); + for (const m of after) { + const pre = beforeById.get(keyOf(m)); + if (pre === undefined) continue; + // Every fold-coverable (non-media) message that survives strip keeps its id: + if (!hasMediaPayload(before.find((b) => b.id === pre)!)) { + assert.equal(m.id, pre, `id flipped for ${JSON.stringify(keyOf(m))}`); + } + } + // Spot-check the three stable classes explicitly: + assert.equal(after.find((m) => m.text === "plain question")?.id, beforeById.get("plain question")); + const t1After = after.find((m) => m.toolCallId === "t1"); + assert.equal(t1After?.id, beforeById.get("t1")); // image-only tool_result + const imgOnlyAfter = after.find((m) => m.text === "[image]"); + assert.equal(imgOnlyAfter?.id, before.find((m) => m.text === "[image]" && m.rawAnthropicBlock !== undefined)?.id); + + // The collapsed tool_result is string-empty, not a "[image]" part: + const mTool = strippedBody.messages[1]; + assert.equal((mTool.content as Array<{ type: string }>)[0].content, ""); +}); + +/** wireIndex tagging (#1995): every core message a wire message flattens into + * carries that wire message's ordinal, so host-side anchoring can map fold + * coverage (core ids) back to wire positions. */ +test("anthropic: wireIndex tags every flattened core message", () => { + const body: AnthropicRequestBody = { + model: "claude", + messages: [ + { role: "user", content: [antTxt("one")] }, + { + role: "user", + content: [antTxt("two-a"), antImg(), { type: "text", text: "two-b" }], + }, + { role: "assistant", content: [antTxt("three")] }, + ], + }; + const flat = anthropicToCore(body); + const byWire = new Map(); + for (const m of flat.msgs) { + assert.notEqual(m.wireIndex, undefined, `message ${m.id} lacks wireIndex`); + byWire.set(m.wireIndex!, (byWire.get(m.wireIndex!) ?? 0) + 1); + } + assert.equal(byWire.get(0), 1); + assert.equal(byWire.get(1), 3); // text + image + text from one wire message + assert.equal(byWire.get(2), 1); +}); diff --git a/kernel/tests/wire-strip-images.test.ts b/kernel/tests/wire-strip-images.test.ts index 3fab6fc4e4..060a47a548 100644 --- a/kernel/tests/wire-strip-images.test.ts +++ b/kernel/tests/wire-strip-images.test.ts @@ -214,7 +214,10 @@ test("anthropic: strips images nested inside tool_result content", () => { type: "tool_result", tool_use_id: "t2", is_error: false, - content: [{ type: "text", text: "[image]" }], + // #1995: image-only tool_result collapses to the EMPTY STRING (not a + // "[image]" text part) so the converter's derived id — seeded from the + // concatenated TEXT parts — stays byte-identical across the strip. + content: "", }, ]); assert.equal(m[1], body.messages[1]); @@ -257,7 +260,8 @@ test("anthropic: counts top-level and nested images in the same message", () => { type: "tool_result", tool_use_id: "t1", - content: [{ type: "text", text: "[image]" }], + // #1995: id-stable empty-string collapse (see wire-strip-cutoff.test.ts) + content: "", }, ], }); diff --git a/src/config.ts b/src/config.ts index 83b0ef32b4..9677d9562a 100644 --- a/src/config.ts +++ b/src/config.ts @@ -404,10 +404,23 @@ export type CompressSettings = { * the most recent {@link stripImagesKeepRecent} has its image parts dropped * before the wire rebuild (image-only content collapses to an "[image]" * placeholder). Off by default — the #488 image floor / overflow 502 stays - * the opt-in signal until this is enabled. */ + * the opt-in signal until this is enabled. + * + * [#1995] On anthropic sessions the strip boundary is FOLD-ANCHORED when + * an active compression fold exists: instead of the sliding `len - + * keepRecent` window (which moves the byte boundary every turn and breaks + * the prompt cache at the most expensive content), the cutoff sticks to + * the last fold-covered wire message and only moves on compression + * events — the stripped prefix is byte-stable between folds. Recovery for + * stripped pixels: `decompress({ imageRef })` (files under + * /retrieve/img//, one-week TTL) and the ref-carrying + * `[image: … · mNNNNN]` notes summaries emit. The other wires keep the + * sliding window until their strip placeholders are made id-stable + * (openai/google flip ids on strip; see src/image-restore.ts). */ stripImages?: boolean; /** With {@link stripImages}, how many trailing messages keep their images - * verbatim (default 5). Ignored unless stripImages is true. */ + * verbatim (default 5). Ignored unless stripImages is true. Serves as the + * FALLBACK window on anthropic when no active fold anchors the boundary. */ stripImagesKeepRecent?: number; /** [#651] Drop oversized reasoning (thinking) from closed-turn `compress` * tool calls at request time (src/reasoning-drop.ts, aligned with diff --git a/src/image-note.ts b/src/image-note.ts index a9c137acfc..fc605d28c0 100644 --- a/src/image-note.ts +++ b/src/image-note.ts @@ -99,3 +99,16 @@ export function imagePlaceholders(m: CoreMessage): string[] { return note ? `[image: ${note}]` : IMAGE_PLACEHOLDER; }); } + +/** #1995: summary-side placeholders with the message's mNNNNN ref appended + * (`[image: png 1024x768 · m00042]`). The fold's summary is what SURVIVES — + * once the range is compressed the live wire no longer carries these images, + * so recording the ref in the summary text is what tells a later turn that + * `decompress({ imageRef: "m00042" })` can pull the pixels back (the + * #2022 restore channel indexes by exactly this ref). `ref` undefined → + * plain placeholders (callers without a ref mapping degrade gracefully). */ +export function imagePlaceholdersForSummary(m: CoreMessage, ref: string | undefined): string[] { + const notes = imagePlaceholders(m); + if (ref === undefined) return notes; + return notes.map((n) => `${n.slice(0, -1)} · ${ref}]`); +} diff --git a/src/image-restore.ts b/src/image-restore.ts index 5a2e5cd984..0528b2c9de 100644 --- a/src/image-restore.ts +++ b/src/image-restore.ts @@ -13,7 +13,7 @@ // sends no such bytes to the proxy, so those belong to the agent's in-process // recovery (cf. billion-context-pi#594), not here. -import { existsSync, mkdirSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readdirSync, rmdirSync, statSync, unlinkSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { anthropicToCore, @@ -249,6 +249,116 @@ export function buildIncomingImageIndex( return index; } +/** Protocol-dispatching convenience: run the inbound body through the wire + * → core converter and return the flattened core messages (or undefined when + * the body does not parse for that protocol). */ +export function coreMessagesFor( + parsed: unknown, + protocol: WireProtocol, +): BiliMessage[] | undefined { + let result: unknown; + try { + switch (protocol) { + case "anthropic": result = anthropicToCore(parsed as AnthropicRequestBody); break; + case "openai": result = openaiToCore(parsed as OpenAIRequestBody); break; + case "google": result = googleToCore(parsed as GoogleRequestBody); break; + case "responses": result = responsesToCore(parsed as ResponsesRequestBody); break; + } + } catch { + return undefined; + } + return coreMsgsOf(result); +} + +/** #1995 gap 2 — fold-anchored strip cutoff for stripImages. + * + * Today the strip window SLIDES (`len - keepRecent`), so every new message + * moves the byte boundary of the outgoing body one message earlier: the + * prompt cache breaks at that point every turn, and the most expensive bytes + * in the window (images) are re-billed as cache writes forever. Instead, when + * an active fold exists we anchor the cutoff to fold coverage: strip exactly + * the wire messages covered by (or older than) the latest active fold. The + * cutoff then only moves on compression events, so the stripped prefix is + * byte-stable between folds and the cache break stays put. + * + * ANTHROPIC ONLY, deliberately. Anchoring is only safe where stripping does + * not perturb kernel message ids: anthropic's strip placeholder "[image]" is + * byte-identical to the id seed the converter derives for image blocks, so a + * stripped image keeps the id the fold recorded at compression time. The + * other three wires flip ids on strip (openai/google drop to "" vs "[image]"; + * responses concatenates text+"[image]"), so anchoring there would orphan + * fold coverage at T+1 — they keep the sliding window until their + * placeholders are made id-neutral (follow-up to #1995). + * + * Returns `undefined` when there is no anchor (no active fold covers any + * message with a known wire index), so the caller falls back to the sliding + * window. */ +export function foldAnchoredCutoff( + parsed: unknown, + protocol: WireProtocol, + state: CompressionState, +): number | undefined { + if (protocol !== "anthropic") return undefined; + const blocks = (state as { blocks?: { active?: boolean; effectiveMessageIds?: string[] }[] })?.blocks; + if (!Array.isArray(blocks)) return undefined; + const covered = new Set(); + for (const b of blocks) { + if (!b?.active) continue; + for (const id of b.effectiveMessageIds ?? []) covered.add(id); + } + if (covered.size === 0) return undefined; + const msgs = coreMessagesFor(parsed, protocol); + if (!msgs) return undefined; + let last = -1; + let boundaryFull = false; + for (const m of msgs) { + if (m.wireIndex === undefined) continue; + if (covered.has(m.id)) { + if (m.wireIndex > last) { last = m.wireIndex; boundaryFull = true; } + else if (m.wireIndex === last) boundaryFull = boundaryFull && true; + } else if (m.wireIndex === last) { + // A core message sharing the boundary wire message but NOT covered + // (e.g. an image block in the same anthropic message the fold + // stopped before): stripping that wire message would strip a LIVE + // image, so the boundary message itself stays intact. + boundaryFull = false; + } + } + if (last < 0) return undefined; + return last + (boundaryFull ? 1 : 0); +} + +/** Best-effort expiry for spilled restore files (#1995): `decompress imageRef` + * needs the bytes long after the wire dropped them, but sessions end and disk + * is not infinite — default TTL one week. Prunes only THIS session's export + * dir. Errors are swallowed (eviction must never take down a request). */ +export function pruneRetrieveImgExports(sessionId: string, ttlMs = 7 * 24 * 3600 * 1000): number { + const dir = restoreExportDir(sessionId); + let entries: string[]; + try { + entries = readdirSync(dir); + } catch { + return 0; + } + const now = Date.now(); + let removed = 0; + for (const name of entries) { + const p = join(dir, name); + try { + const st = statSync(p); + if (st.isFile() && now - st.mtimeMs > ttlMs) { unlinkSync(p); removed++; } + } catch {} + } + if (removed > 0) { + try { + // Drop the dir too when we emptied it, so finished sessions leave + // no residue. + if (readdirSync(dir).length === 0) rmdirSync(dir); + } catch {} + } + return removed; +} + function refNum(ref: string): number { const m = /^m(\d+)$/i.exec(ref.trim()); return m ? Number.parseInt(m[1], 10) : Number.MAX_SAFE_INTEGER; diff --git a/src/preflight.ts b/src/preflight.ts index d15abd8d9e..88a4341493 100644 --- a/src/preflight.ts +++ b/src/preflight.ts @@ -8,7 +8,7 @@ import { type PackSurface, } from "acp-kernel"; import { buildCompressSystemPrompt, parseCompressInput } from "./compress-tool.js"; -import { IMAGE_PLACEHOLDER, imagePlaceholders } from "./image-note.js"; +import { IMAGE_PLACEHOLDER, imagePlaceholdersForSummary } from "./image-note.js"; import { applyAbsorbView } from "./absorb.js"; import { adoptContentStore, ccrLoopConfig, contentStoreOf } from "./store.js"; import { applyRanges, normalizeRangeOrder, type RewriteCtx } from "./stream.js"; @@ -1353,6 +1353,9 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa // sidecars the kernel never sees. Consumed child blocks render through the // kernel from the original state so they stay summaries. const idxById = new Map(messages.map((m, i) => [m.id, i])); + // #1995: summary notes carry the ref so the fold's own text + // points at the restore channel (decompress imageRef). + const byRaw = deps.session.state?.messageRefs?.byRaw; const parts: string[] = []; const droppedParts: string[] = []; for (const id of planned.directMessageIds) { @@ -1360,7 +1363,7 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa if (i === undefined) { droppedParts.push(`message ${id} not found in current messages`); continue; } const m = messages[i]; let text = m.text ?? ""; - const notes = imagePlaceholders(m); + const notes = imagePlaceholdersForSummary(m, byRaw?.[m.id]); if (notes.length > 0) { const note = notes.join(" "); text = text === IMAGE_PLACEHOLDER ? note : text ? `${text}\n${note}` : note; diff --git a/src/server.ts b/src/server.ts index 2858508be2..bccfca9e4b 100644 --- a/src/server.ts +++ b/src/server.ts @@ -69,7 +69,7 @@ import { import { ABSORB_TOOL_NAME, COMPRESS_TOOL, BILI_ACP_TOOLS_ANTHROPIC, BILI_ACP_TOOLS_ANTHROPIC_NO_RANGE, BILI_ACP_TOOLS_GOOGLE, BILI_ACP_TOOLS_GOOGLE_NO_RANGE, BILI_ACP_TOOLS_OPENAI, BILI_ACP_TOOLS_OPENAI_NO_RANGE, BILI_ACP_TOOLS_RESPONSES, BILI_ACP_TOOLS_RESPONSES_NO_RANGE, BILI_ACP_READONLY_TOOLS_RESPONSES, BILI_ACP_READONLY_TOOLS_RESPONSES_NO_RANGE, COMPRESS_TOOL_NAME, IMAGE_FULL_TOOL, IMAGE_FULL_TOOL_GOOGLE, IMAGE_FULL_TOOL_OPENAI, IMAGE_FULL_TOOL_RESPONSES, RULE_TOOL, RULE_TOOL_GOOGLE, RULE_TOOL_OPENAI, RULE_TOOL_RESPONSES, absorbToolsFor, retrieveToolsFor, buildAbsorbSystemPrompt, buildAcpTagsOnlyPrompt, buildCompressSystemPrompt, buildCompressHybridSystemPrompt, withMarkerIntegrityNote, withStagedCompressGuidance, withSummaryBudgetNote } from "./compress-tool.js"; import { applyAbsorbView, absorbEnabled, absorbToolName, storeEffectiveAbsorb } from "./absorb.js"; import { adoptContentStore, ccrEnabled, ccrLoopConfig, ccrPluginWireOk, commitRetrievals, commitRetrievalNotes, contentStoreOf, dropRetrievals, executeRetrieve, pruneExpiredRetrievals, reconcileReloadedRetrievals, renderRetrievalNotes, retrieveToolName, snapshotPendingRetrievals, snapshotRetrievalNotes, storeEffectiveCcr, type CcrSettings } from "./store.js"; -import { buildIncomingImageIndex } from "./image-restore.js"; +import { buildIncomingImageIndex, foldAnchoredCutoff, pruneRetrieveImgExports } from "./image-restore.js"; import { applyImageCompressionPass, imageCompressionEnabled, imageFullTrailingNote, imageUsageSuffix, storeEffectiveImageCompression, type ImageCompressionSettings } from "./image-compress.js"; import { rulesEnabled, storeEffectiveRules } from "./rules-feature.js"; import { storeEffectiveSearchPlanAware } from "./decompress-shared.js"; @@ -3227,15 +3227,32 @@ async function handle( const visibilityMarkers = cs.visibilityMarkers ?? true; const reasoningCfg = cs.reasoning; const keepRecent = cs.stripImagesKeepRecent ?? DEFAULT_STRIP_IMAGES_KEEP_RECENT; + // #1995 gap 2: when an active fold exists (anthropic only — + // see foldAnchoredCutoff for the id-stability proof), anchor + // the strip boundary to fold coverage instead of the sliding + // window so the stripped prefix is byte-stable between folds + // and the prompt cache survives turn-over-turn. Falls back to + // the sliding window when there is nothing to anchor to. + const anchoredCutoff = cs.stripImages && protocol + ? foldAnchoredCutoff(parsed, protocol, session.state) + : undefined; const stripped = cs.stripImages - ? stripHistoricalImages(parsed, protocol, keepRecent) + ? stripHistoricalImages(parsed, protocol, keepRecent, anchoredCutoff !== undefined ? { cutoffIndex: anchoredCutoff } : undefined) : { body: parsed, removed: 0 }; // #1995: index recoverable historical images by ref from the UNSTRIPPED // body before stripping drops them, so decompress({ imageRef }) can pull // specific pixels back later. Gated on stripImages (recovery is only // meaningful when stripping removes something); latest-wins per request. - if (cs.stripImages && protocol) { + // count_tokens requests skip the (pure bookkeeping) index rebuild but + // still strip with the same cutoff, so token counts stay representative + // of what the model turn would send. Eviction rides along (best-effort, + // throttled to once a minute). + if (cs.stripImages && protocol && !countTokens) { session.incomingImageIndex = buildIncomingImageIndex(parsed, protocol, session.state, session.id); + if (session.lastImgPrune === undefined || Date.now() - session.lastImgPrune > 60_000) { + session.lastImgPrune = Date.now(); + pruneRetrieveImgExports(session.id); + } } else if (session.incomingImageIndex) { session.incomingImageIndex = undefined; } diff --git a/src/session.ts b/src/session.ts index 2dd6b56461..a21a6ad326 100644 --- a/src/session.ts +++ b/src/session.ts @@ -336,15 +336,19 @@ export type Session = { * non-CCR riders (#1207 range restore, ccr:false). Legacy sessions from * before the rework may still carry ccr:true entries; the reconcile/ * commit/drop machinery below handles them (they are never re-created). */ - pendingRetrievals: PendingRetrieval[]; - /** #1995 in-memory only (NOT persisted — buildRecord omits it): ref → images - * index built per request from the INBOUND body while stripImages is armed, - * so decompress({ imageRef }) can pull a stripped/folded image's original - * pixels back. Latest-wins (the client re-sends full history every turn, so - * each request's index is complete); cleared when stripImages is off. Values - * hold only metadata + the on-disk path (bytes are spilled at index-time and - * never retained), so residency stays O(refs) regardless of image volume. */ - incomingImageIndex?: Map>; + pendingRetrievals: PendingRetrieval[]; + /** #1995 in-memory only (NOT persisted — buildRecord omits it): ref → images + * index built per request from the INBOUND body while stripImages is armed, + * so decompress({ imageRef }) can pull a stripped/folded image's original + * pixels back. Latest-wins (the client re-sends full history every turn, so + * each request's index is complete); cleared when stripImages is off. Values + * hold only metadata + the on-disk path (bytes are spilled at index-time and + * never retained), so residency stays O(refs) regardless of image volume. */ + incomingImageIndex?: Map>; + /** #1995 in-memory only: timestamp of the last best-effort + * pruneRetrieveImgExports sweep for this session (throttled to once a + * minute in the request path). */ + lastImgPrune?: number; /** #1095 in-memory only (NOT persisted): deterministic encode cache keyed * by sha256 of the ORIGINAL base64 → encoded payload. Identical inputs * must yield identical wire bytes across turns/restarts (prefix-cache diff --git a/tests/responses-tool-images.test.ts b/tests/responses-tool-images.test.ts index 8c82436985..819072a5ba 100644 --- a/tests/responses-tool-images.test.ts +++ b/tests/responses-tool-images.test.ts @@ -201,7 +201,9 @@ test("host preflight includes notes for mixed and image-only tool outputs withou await response.text(); assert.ok(summaries.length > 0, "genuine text pressure triggers preflight"); const summaryInput = summaries.map((body) => JSON.stringify(body)).join("\n"); - assert.equal(summaryInput.split("[image: png 2048x1152]").length - 1, 2); + // #1995: summary notes now carry the ref ("... · mNNNNN") so the fold's + // own text points at the decompress imageRef restore channel. + assert.equal((summaryInput.match(/\[image: png 2048x1152 · m\d+\]/g) ?? []).length, 2); assert.ok(summaryInput.includes("The screenshot shows a failure.")); assert.ok(!summaryInput.includes("data:image")); assert.ok(!summaryInput.includes(imageUrl.slice(22, 80))); diff --git a/tests/strip-cutoff-anchor.test.ts b/tests/strip-cutoff-anchor.test.ts new file mode 100644 index 0000000000..dcdd2aea23 --- /dev/null +++ b/tests/strip-cutoff-anchor.test.ts @@ -0,0 +1,137 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, existsSync, mkdirSync, writeFileSync, utimesSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + coreMessagesFor, + foldAnchoredCutoff, + pruneRetrieveImgExports, + restoreExportDir, +} from "../src/image-restore.ts"; +import { imagePlaceholdersForSummary } from "../src/image-note.ts"; +import type { CompressionState } from "acp-kernel"; + +const antTxt = (t: string) => ({ type: "text", text: t }); +const antImg = () => ({ + type: "image", + source: { type: "base64", media_type: "image/png", data: "AAAA" }, +}); + +function bodyOf(...contents: unknown[]) { + return { model: "claude", messages: contents.map((content) => ({ role: "user", content })) }; +} + +function stateWithCovers(ids: string[]): CompressionState { + return { + blocks: [{ blockId: "b1", effectiveMessageIds: ids, active: true }], + } as unknown as CompressionState; +} + +test("foldAnchoredCutoff: full boundary → cutoff just past the last covered wire message", () => { + const body = bodyOf([antTxt("a")], [antTxt("b")], [antTxt("c")], [antTxt("d")]); + const msgs = coreMessagesFor(body, "anthropic")!; + assert.equal(msgs.length, 4); + const cutoff = foldAnchoredCutoff(body, "anthropic", stateWithCovers([msgs[0].id, msgs[1].id])); + assert.equal(cutoff, 2); +}); + +test("foldAnchoredCutoff: partially-covered boundary wire message (live image) is NOT stripped", () => { + // Wire message 2 flattens to [text, image]; the fold covers the text but + // the image is a media gap — stripping wire 2 would strip a LIVE image. + const body = bodyOf([antTxt("a")], [antTxt("b")], [antTxt("c"), antImg()], [antTxt("d")]); + const msgs = coreMessagesFor(body, "anthropic")!; + assert.equal(msgs.length, 5); // a, b, c, image, d + const ids = [msgs[0].id, msgs[1].id, msgs[2].id]; // fold covers a, b, c — stops at the image gap + const cutoff = foldAnchoredCutoff(body, "anthropic", stateWithCovers(ids)); + assert.equal(cutoff, 2); // wire 2 stays intact +}); + +test("foldAnchoredCutoff: no active folds / other protocols → undefined (sliding fallback)", () => { + const body = bodyOf([antTxt("a")], [antTxt("b")]); + const empty = { blocks: [] } as unknown as CompressionState; + assert.equal(foldAnchoredCutoff(body, "anthropic", empty), undefined); + const inactive = { + blocks: [{ blockId: "b1", effectiveMessageIds: ["x"], active: false }], + } as unknown as CompressionState; + assert.equal(foldAnchoredCutoff(body, "anthropic", inactive), undefined); + const oai = { model: "gpt", messages: [{ role: "user", content: "hi" }] }; + assert.equal(foldAnchoredCutoff(oai, "openai", stateWithCovers(["whatever"])), undefined); +}); + +test("foldAnchoredCutoff: covered ids the client no longer sends anchor from the rest", () => { + const body = bodyOf([antTxt("a")], [antTxt("b")], [antTxt("c")]); + const msgs = coreMessagesFor(body, "anthropic")!; + // a deleted remotely, b still covered → still anchors at wire 1 + const cutoff = foldAnchoredCutoff(body, "anthropic", stateWithCovers(["h_gone", msgs[1].id])); + assert.equal(cutoff, 2); +}); + +test("foldAnchoredCutoff + stripHistoricalImages: stripped prefix byte-stable across turns", async () => { + // The cache-stability contract end-to-end: same body + same anchor two + // turns in a row (client re-sends identical history plus one new tail) + // → stripped messages 0..cutoff-1 serialize identically. + const base = bodyOf([antTxt("a"), antImg()], [antImg()], [antTxt("c"), antImg()]); + const msgs = coreMessagesFor(base, "anthropic")!; + const state = stateWithCovers(msgs.filter((m) => m.wireIndex !== undefined && m.wireIndex < 2).map((m) => m.id)); // covers wires 0 and 1 + const cutoff = foldAnchoredCutoff(base, "anthropic", state); + assert.equal(cutoff, 2); + + const { stripHistoricalImages } = await import("acp-kernel/wire"); + const t0 = stripHistoricalImages(base, "anthropic", 1, { cutoffIndex: cutoff }); + const t1Body = { + ...base, + messages: [...base.messages, { role: "user" as const, content: [antTxt("d")] }], + }; + const t1 = stripHistoricalImages(t1Body, "anthropic", 1, { cutoffIndex: cutoff }); + assert.equal( + JSON.stringify((t0.body as { messages: unknown[] }).messages.slice(0, cutoff)), + JSON.stringify((t1.body as { messages: unknown[] }).messages.slice(0, cutoff)), + ); +}); + +test("pruneRetrieveImgExports: removes files older than TTL, keeps fresh ones, drops emptied dirs", () => { + const dir = mkdtempSync(join(tmpdir(), "img-prune-")); + process.env.XDG_STATE_HOME = dir; + try { + const sid = "prune-test"; + const target = restoreExportDir(sid); + mkdirSync(target, { recursive: true }); + const fresh = join(target, "m00001.png"); + const stale = join(target, "m00002.png"); + writeFileSync(fresh, "fresh"); + writeFileSync(stale, "stale"); + const old = new Date(Date.now() - 30 * 24 * 3600 * 1000); + utimesSync(stale, old, old); + const removed = pruneRetrieveImgExports(sid, 7 * 24 * 3600 * 1000); + assert.equal(removed, 1); + assert.ok(!existsSync(stale)); + assert.ok(existsSync(fresh)); + // Dir still holds the fresh file → survives. + assert.ok(existsSync(target)); + // Backdate the survivor and tighten the TTL — deterministic instead of + // racing wall-clock milliseconds. + utimesSync(fresh, old, old); + const removed2 = pruneRetrieveImgExports(sid, 7 * 24 * 3600 * 1000 + 1); + assert.equal(removed2, 1); + assert.ok(!existsSync(target)); + } finally { + delete process.env.XDG_STATE_HOME; + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("imagePlaceholdersForSummary: appends the ref, degrades without one", () => { + const m = { + id: "x", + role: "user" as const, + contentType: "text" as const, + text: "[image]", + rawAnthropicBlock: { + type: "image", + source: { type: "base64", media_type: "image/png", data: "AAAA" }, + }, + }; + assert.deepEqual(imagePlaceholdersForSummary(m, "m00042"), ["[image: png · m00042]"]); + assert.deepEqual(imagePlaceholdersForSummary(m, undefined), ["[image: png]"]); +}); From be624b4d6ea4370e862911cd46d29f0df006077f Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 7 Oct 2026 01:03:22 +0800 Subject: [PATCH 08/11] refactor: #1995 drop no-op boundaryFull re-assertion in foldAnchoredCutoff --- src/image-restore.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/image-restore.ts b/src/image-restore.ts index 0528b2c9de..3893bcc3ba 100644 --- a/src/image-restore.ts +++ b/src/image-restore.ts @@ -315,7 +315,6 @@ export function foldAnchoredCutoff( if (m.wireIndex === undefined) continue; if (covered.has(m.id)) { if (m.wireIndex > last) { last = m.wireIndex; boundaryFull = true; } - else if (m.wireIndex === last) boundaryFull = boundaryFull && true; } else if (m.wireIndex === last) { // A core message sharing the boundary wire message but NOT covered // (e.g. an image block in the same anthropic message the fold From 478d7930534e8a4ecb4cec371ffdc3089d65bbc1 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 7 Oct 2026 01:03:22 +0800 Subject: [PATCH 09/11] docs: #1995 sync CONFIGURATION stripImages sections with fold-anchored cutoff + recovery channel --- CONFIGURATION.md | 6 +++--- CONFIGURATION.zh-CN.md | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index de77563496..81871e0d7c 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -207,7 +207,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `compress.minCompressRangeChars` | number (deprecated alias: minCompressRange) | kernel ≈5000 | — | Smallest foldable range, in characters; shorter ranges never fold. | | `compress.reconcile` | "off" \| "warn" \| "repair" | "repair" | BILI_FOLD_RECONCILE | Reconcile folded state when the client rewinds or rewrites history between turns. | | `compress.promptPack` | string (builtin: "default", "lean") | builtin "default" | — | Compression prompt pack, resolved project pack → user pack → builtin; not gated by acknowledgePromptsRisk. | -| `compress.stripImagesKeepRecent` | number | 5 | — | With stripImages on, images inside the N newest messages are kept. | +| `compress.stripImagesKeepRecent` | number | 5 | — | With stripImages on, images inside the N newest messages are kept (fallback window when no fold anchors the boundary). | | `compress.tiers` | boolean | true | — | Tiered T1→T3 distillation spreads folding cost across generations. | | `compress.protectedTools` | string[] | none | — | Hard exclusion across all history: results of listed tools never fold. | | `compress.protectedLatestTools` | string[] | none | — | Protects only the LATEST instance of cumulative-snapshot tools whose newest result supersedes older ones (e.g. todo lists). | @@ -1318,14 +1318,14 @@ For each request, the proxy resolves the settings by longest-URL-prefix match (t - **Type:** `boolean` - **Default:** `false` - **Status:** ACTIVE -- **Description:** Opt-in removal of historical image payloads. When `true`, every message **except** the most recent `stripImagesKeepRecent` has its image parts dropped before the wire rebuild; an image-only message collapses to a single `[image]` text placeholder (mixed text+image messages keep their text). Recent-N images are forwarded verbatim, and a freshly-sent image always falls inside that window on the turn it arrives. Off by default — while off, the #488 image-token floor and its overflow `502` stay the opt-in signal for image-heavy payloads. Applies to both compression modes (in plugin mode the agent's own history is untouched; only the upstream-bound wire is slimmed). See issue #617. +- **Description:** Opt-in removal of historical image payloads. When `true`, aged-out messages have their image parts dropped before the wire rebuild; an image-only message collapses to a single `[image]` text placeholder (mixed text+image messages keep their text). **Strip boundary (#1995):** on anthropic sessions with an active compression fold, the boundary is FOLD-ANCHORED — only wire messages covered by active folds are stripped, and the boundary moves only on compression events, so the stripped prefix stays byte-stable between folds (the prompt cache stops re-billing it every turn) and un-folded images stay live. Without an active fold, or on the other wires (whose strip placeholders would flip kernel message ids), the classic sliding window applies: every message except the most recent `stripImagesKeepRecent` is stripped. A freshly-sent image always sits in the un-stripped tail on the turn it arrives. **Recovery:** stripped pixels are recoverable via `decompress({ imageRef })` — each stripped image is indexed by its `mNNNNN` ref and spilled under `/retrieve/img//` (best-effort 7-day TTL); preflight fold summaries carry the ref in their notes (`[image: png 1024x768 · m00042]`). Off by default — while off, the #488 image-token floor and its overflow `502` stay the opt-in signal for image-heavy payloads. Applies to both compression modes (in plugin mode the agent's own history is untouched; only the upstream-bound wire is slimmed). See issue #617. #### `stripImagesKeepRecent` - **Type:** `number` - **Default:** `5` - **Status:** ACTIVE -- **Description:** With `stripImages: true`, how many trailing messages keep their images verbatim. Ignored unless `stripImages` is enabled. +- **Description:** With `stripImages: true`, how many trailing messages keep their images verbatim. Ignored unless `stripImages` is enabled. **Fallback role (#1995):** on anthropic sessions an active fold anchors the strip boundary instead; this window applies when no fold anchors it (and on all other wires). #### `visibilityMarkers` diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index f439171f5e..68f5c4d099 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -207,7 +207,7 @@ | `compress.minCompressRangeChars` | number (deprecated alias: minCompressRange) | kernel ≈5000 | — | 可折叠片段的最小字符数;更短的永不折叠。 | | `compress.reconcile` | "off" \| "warn" \| "repair" | "repair" | BILI_FOLD_RECONCILE | 客户端在轮次之间回退或改写历史时校准已折叠状态。 | | `compress.promptPack` | string (builtin: "default", "lean") | builtin "default" | — | 压缩提示词包,按 项目包 → 用户包 → 内置 解析;不受 acknowledgePromptsRisk 门控。 | -| `compress.stripImagesKeepRecent` | number | 5 | — | 开启剥离图片时,最新 N 条消息内的图片保留。 | +| `compress.stripImagesKeepRecent` | number | 5 | — | 开启剥离图片时,最新 N 条消息内的图片保留(无折叠锚定时的回退窗口)。 | | `compress.tiers` | boolean | true | — | T1→T3 分级蒸馏把折叠成本摊到多代。 | | `compress.protectedTools` | string[] | none | — | 全历史硬排除:列出工具的结果永不折叠。 | | `compress.protectedLatestTools` | string[] | none | — | 只保护累积快照类工具「最新一次」实例(新结果覆盖旧结果的工具,如 todo 列表)。 | @@ -1323,14 +1323,14 @@ - **类型:** `boolean` - **默认值:** `false` - **状态:** ACTIVE -- **说明:** 可选的历史图像载荷移除。设为 `true` 时,除最近 `stripImagesKeepRecent` 条消息外,所有消息在重建 wire 前都会丢弃其图像部分;纯图像消息折叠为单个 `[image]` 文本占位符(图文混合消息保留其文本)。最近 N 条的图像逐字转发,且新发送的图像在其到达的那一轮必然落在该窗口内。默认关闭 —— 关闭期间,#488 图像 token 下限及其溢出 `502` 仍是图像密集型载荷的显式信号。对两种压缩模式均生效(plugin 模式下 agent 自身历史不受影响,仅精简发往上游的 wire)。见 issue #617。 +- **说明:** 可选的历史图像载荷移除。设为 `true` 时,老化消息在重建 wire 前会丢弃其图像部分;纯图像消息折叠为单个 `[image]` 文本占位符(图文混合消息保留其文本)。**剥离边界(#1995):** anthropic 会话存在活跃压缩折叠时,边界为折叠锚定——只剥离被活跃折叠覆盖的 wire 消息,边界仅在压缩事件时移动,被剥离的前缀在两次折叠之间保持字节稳定(prompt cache 不再每轮重复计费),未折叠的图像保持可见。无活跃折叠时(以及其他 wire——其剥离占位符会翻转 kernel 消息 id)沿用经典滑动窗口:除最近 `stripImagesKeepRecent` 条外全部剥离。新发送的图像在其到达的那一轮必然落在未剥离尾部。**恢复:** 被剥离的像素可通过 `decompress({ imageRef })` 恢复——每个被剥离图像按 `mNNNNN` 引用建索引并 spill 到 `/retrieve/img//`(尽力而为的 7 天 TTL);preflight 折叠摘要的注释携带引用(`[image: png 1024x768 · m00042]`)。默认关闭 —— 关闭期间,#488 图像 token 下限及其溢出 `502` 仍是图像密集型载荷的显式信号。对两种压缩模式均生效(plugin 模式下 agent 自身历史不受影响,仅精简发往上游的 wire)。见 issue #617。 #### `stripImagesKeepRecent` - **类型:** `number` - **默认值:** `5` - **状态:** ACTIVE -- **说明:** 在 `stripImages: true` 时,末尾多少条消息保留其图像逐字转发。仅在启用 `stripImages` 时生效。 +- **说明:** 在 `stripImages: true` 时,末尾多少条消息保留其图像逐字转发。仅在启用 `stripImages` 时生效。**回退角色(#1995):** anthropic 会话存在活跃折叠时剥离边界改为折叠锚定;此窗口在无折叠锚定时(以及所有其他 wire 上)生效。 #### `visibilityMarkers` From 5cb8ffe35c651a07bb2bb20cd3f8d3712755ad67 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Wed, 7 Oct 2026 01:14:26 +0800 Subject: [PATCH 10/11] docs: #1995 fold-anchored fallback wording belongs in the yaml seed, not the artifact --- website/config-reference/compress.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/website/config-reference/compress.yaml b/website/config-reference/compress.yaml index fffad92188..3c1bc9c619 100644 --- a/website/config-reference/compress.yaml +++ b/website/config-reference/compress.yaml @@ -119,8 +119,8 @@ entries: group: compress id: cw.sikr render: compress-row - desc_en: "With stripImages on, images inside the N newest messages are kept." - desc_zh: "开启剥离图片时,最新 N 条消息内的图片保留。" + desc_en: "With stripImages on, images inside the N newest messages are kept (fallback window when no fold anchors the boundary)." + desc_zh: "开启剥离图片时,最新 N 条消息内的图片保留(无折叠锚定时的回退窗口)。" site_en: "With stripImages on, images inside the N newest messages (default 5) are kept." site_zh: "开启剥离图片时,最新 N 条消息(默认 5)内的图片保留。" - key: compress.tiers From 59c49cfb7f70ccaf5ef67e341766e92706c86187 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Wed, 7 Oct 2026 11:42:33 +0800 Subject: [PATCH 11/11] =?UTF-8?q?fix:=20address=20#1995=20review=20round?= =?UTF-8?q?=204=20=E2=80=94=20salt=20spill-dir=20sanitizer=20collisions,?= =?UTF-8?q?=20GC=20the=20image-spill=20tree,=20mirror=20the=20Gemini=20$re?= =?UTF-8?q?f=20guard,=20ref=20footers=20on=20model-driven=20folds?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/image-restore.ts | 38 ++++++++-- src/session-gc.ts | 55 +++++++++++++-- src/stream.ts | 25 +++++++ tests/session-gc.test.ts | 52 +++++++++++++- tests/strip-cutoff-anchor.test.ts | 113 +++++++++++++++++++++++++++++- 5 files changed, 269 insertions(+), 14 deletions(-) diff --git a/src/image-restore.ts b/src/image-restore.ts index 3893bcc3ba..1f71291097 100644 --- a/src/image-restore.ts +++ b/src/image-restore.ts @@ -14,6 +14,7 @@ // recovery (cf. billion-context-pi#594), not here. import { existsSync, mkdirSync, readdirSync, rmdirSync, statSync, unlinkSync, writeFileSync } from "node:fs"; +import { createHash } from "node:crypto"; import { join } from "node:path"; import { anthropicToCore, @@ -150,11 +151,20 @@ export function messageImageBytes(m: CoreMessage): RestorableImage[] { } const fr = part.functionResponse; if (isObj(fr) && Array.isArray(fr.parts)) { - for (const np of fr.parts) { - if (!isObj(np)) continue; - const ni = np.inlineData; - if (isObj(ni) && typeof ni.data === "string" && typeof ni.mimeType === "string" && ni.mimeType.startsWith("image/")) { - out.push({ mediaType: ni.mimeType, b64: ni.data, bytes: b64Bytes(ni.data) }); + // Review ⑤: mirror the strip side's Gemini-3 $ref guard (kernel + // strip-images.ts) — when `response` points at a part via + // {"$ref": displayName} the strip side leaves the part untouched, + // so there is nothing to restore: skip indexing (harmless waste, + // not corruption, but the index and the strip disagree for no + // reason without this). + const refGuarded = JSON.stringify(fr.response ?? null).includes('"$ref"'); + if (!refGuarded) { + for (const np of fr.parts) { + if (!isObj(np)) continue; + const ni = np.inlineData; + if (isObj(ni) && typeof ni.data === "string" && typeof ni.mimeType === "string" && ni.mimeType.startsWith("image/")) { + out.push({ mediaType: ni.mimeType, b64: ni.data, bytes: b64Bytes(ni.data) }); + } } } } @@ -388,9 +398,23 @@ export function describeRestorable(index: Map, cap = 50) * of the path — a flat retrieve/img/ would let two sessions' same-numbered refs * collide, and with skip-if-exists the first session's pixels would be served * for the second session's ref forever (cross-session finding from review). */ +/** Directory name (not path) for a session's spill tree — exported so the + * session GC can address the same dir under a test-provided root. */ +export function restoreExportDirName(sessionId: string): string { + const safe = sessionId.replace(/[^a-zA-Z0-9_-]/g, "-").slice(0, 100); + // Review ①: distinct raw ids that sanitize to the same safe form ("a/b" vs + // "a-b", or a >100-char truncation) must not share a directory — salt with + // a short hash of the RAW id whenever the sanitizer changed anything. The + // salt is deterministic, so the path survives restarts, and post-salt the + // map id -> dir is injective (two ids can only collide when both sanitize + // AND hash identically). Unsalted ids keep their historical path. + return safe === sessionId + ? (safe || "session") + : `${safe || "session"}-${createHash("sha256").update(sessionId).digest("hex").slice(0, 8)}`; +} + export function restoreExportDir(sessionId: string): string { - const safe = sessionId.replace(/[^a-zA-Z0-9_-]/g, "-").slice(0, 100) || "session"; - return join(stateDir(), "retrieve", "img", safe); + return join(stateDir(), "retrieve", "img", restoreExportDirName(sessionId)); } function extFor(mediaType: string): string { diff --git a/src/session-gc.ts b/src/session-gc.ts index 37781b9583..8ee22b89ce 100644 --- a/src/session-gc.ts +++ b/src/session-gc.ts @@ -6,6 +6,8 @@ import { defaultCountTokens } from "acp-kernel"; import { getStore, type SessionStore } from "./persist.js"; import { sessionsDir } from "./paths.js"; import { dropSessionForGc, peekSession } from "./session.js"; +import { stateDir } from "./paths.js"; +import { restoreExportDir, restoreExportDirName } from "./image-restore.js"; import { gcSettings as knobGcSettings } from "./knobs.js"; /** @@ -176,10 +178,12 @@ export interface GcResult { bytesFreed: number; /** #1180: content-store companion files removed (co-deletions + orphan sweeps) */ companionsRemoved: number; + /** #1995: image-spill directories removed (co-deletions + stale-mtime sweep) */ + imgDirsRemoved: number; } -export async function gcSessionFiles(opts?: { dir?: string; store?: SessionStore; now?: number }): Promise { - const result: GcResult = { removed: 0, kept: 0, unreadable: 0, bytesFreed: 0, companionsRemoved: 0 }; +export async function gcSessionFiles(opts?: { dir?: string; store?: SessionStore; now?: number; imgRoot?: string }): Promise { + const result: GcResult = { removed: 0, kept: 0, unreadable: 0, bytesFreed: 0, companionsRemoved: 0, imgDirsRemoved: 0 }; const cfg = gcConfigFromEnv(); if (!cfg.enabled) return result; const store = opts?.store ?? getStore(); @@ -271,6 +275,22 @@ export async function gcSessionFiles(opts?: { dir?: string; store?: SessionStore result.removed++; result.bytesFreed += st.size; deletedSessions.add(file); + // #1995 review ②: the stripImages restore spill tree + // (/retrieve/img//) shares this session's lifecycle — + // refs are per-session, so once the file is gone the spills are + // unreachable. Co-delete; anything this deterministic path misses (null + // id, a pre-salt dir name from an older build) is collected by the + // stale-mtime pass below. + if (view.id !== null) { + try { + const imgDir = opts?.imgRoot !== undefined + ? path.join(opts.imgRoot, restoreExportDirName(view.id)) + : restoreExportDir(view.id); + await rm(imgDir, { recursive: true, force: true }); + loggerLog("info", `[gc] removed image spills for session ${view.id}: ${path.relative(stateDir(), imgDir)}`); + result.imgDirsRemoved++; + } catch { /* mtime pass retries next sweep */ } + } if (compSt) { // Co-delete the companion so the sweep never leaves orphans. On // failure it surfaces as an orphan on the very next pass below. @@ -365,9 +385,36 @@ export async function gcSessionFiles(opts?: { dir?: string; store?: SessionStore const parent = path.dirname(companion); if (parent !== dir) await rmdir(parent).catch(() => {}); } - if (result.removed > 0 || result.unreadable > 0 || result.companionsRemoved > 0) { + // #1995 review ②+③: image-spill directories orphaned by anything but the + // co-delete above (crash between file rm and dir rm, unreadable ids, dir + // names from before the collision-salt). mtime = last spill write; spills + // are a pure cache — the next request re-spills whatever it needs — so an + // age-eligible dir is safe to drop even if its session survives (expiry + // self-heals by re-spill). Same age gate as every other artifact here. + const imgRoot = opts?.imgRoot ?? path.join(stateDir(), "retrieve", "img"); + try { + for (const e of await readdir(imgRoot, { withFileTypes: true })) { + if (!e.isDirectory()) continue; + const full = path.join(imgRoot, e.name); + let ist; + try { + ist = await stat(full); + } catch { + continue; + } + if (!ist.isDirectory() || now - ist.mtimeMs < cfg.maxAgeMs) continue; + try { + await rm(full, { recursive: true, force: true }); + } catch { + continue; + } + loggerLog("info", `[gc] removed stale image spill dir ${path.relative(stateDir(), full)}`); + result.imgDirsRemoved++; + } + } catch { /* no spill tree yet — nothing to sweep */ } + if (result.removed > 0 || result.unreadable > 0 || result.companionsRemoved > 0 || result.imgDirsRemoved > 0) { loggerLog(result.unreadable > 0 ? "warn" : "info", - `[gc] removed ${result.removed} stale session file(s)${result.companionsRemoved > 0 ? ` + ${result.companionsRemoved} content store file(s)` : ""} (age>${Math.round(cfg.maxAgeMs / DAY_MS)}d, ≤${cfg.maxTokens}tok), freed ${(result.bytesFreed / 1024).toFixed(1)} KB${result.unreadable > 0 ? `; left ${result.unreadable} unreadable file(s) in place` : ""}`); + `[gc] removed ${result.removed} stale session file(s)${result.companionsRemoved > 0 ? ` + ${result.companionsRemoved} content store file(s)` : ""}${result.imgDirsRemoved > 0 ? ` + ${result.imgDirsRemoved} image spill dir(s)` : ""} (age>${Math.round(cfg.maxAgeMs / DAY_MS)}d, ≤${cfg.maxTokens}tok), freed ${(result.bytesFreed / 1024).toFixed(1)} KB${result.unreadable > 0 ? `; left ${result.unreadable} unreadable file(s) in place` : ""}`); } return result; } diff --git a/src/stream.ts b/src/stream.ts index 15a4b8a898..d18dfb469b 100644 --- a/src/stream.ts +++ b/src/stream.ts @@ -8,6 +8,7 @@ import { effectiveAbsorbConfig, executeAbsorb, isProxyToolFor } from "./absorb.j import { executeSearchContextTarget, resolveDecompress } from "./decompress-shared.js"; import { adoptContentStore, contentStoreOf, ccrEnabled, drainPendingRetrievals, executeRetrieve, retrieveToolName } from "./store.js"; import { IMAGE_FULL_TOOL_NAME, executeImageFull, imageCompressionEnabled } from "./image-compress.js"; +import { imagePlaceholdersForSummary } from "./image-note.js"; import { containsBiliInternalText, containsMarkerLineText, containsRenderTagText, containsToolCallEmissionText, stripAcpTags } from "./loop/tag-echo-filter.js"; import { maxShrinkPerCompress } from "./fetch-util.js"; import { compressResult, toolFail, type ProxyToolResult } from "./proxy-tool-result.js"; @@ -505,6 +506,30 @@ export function applyRanges(parsed: ReturnType, ctx: adoptContentStore(ctx.session, storeCoveredOriginals(contentStoreOf(ctx.session), ctx.compressMessages ?? ctx.messages, res.state, newBlocks.map((b) => b.blockId), defaultCountTokens)); } } + // #1995 review ④: preflight summaries render host-side image notes with + // refs, but a MODEL-driven fold's summary is whatever the model wrote — + // sidecar images covered by the fold (e.g. responses tool-output + // screenshots, which are foldable) lose their discoverability pointer. + // Append the same ref-carrying notes as a compact footer so a later + // turn can still find decompress({ imageRef }). Appended AFTER the + // kernel's length validation — the footer is host bookkeeping, not + // model output, and stays bounded (one short note per covered image). + { + const view = ctx.compressMessages ?? ctx.messages; + const byRaw = ctx.session.state.messageRefs?.byRaw; + for (const b of res.state.blocks) { + if (beforeIds.has(b.blockId)) continue; + const notes: string[] = []; + for (const id of b.directMessageIds) { + const m = view.find((msg) => msg.id === id); + if (!m) continue; + notes.push(...imagePlaceholdersForSummary(m, byRaw?.[id])); + } + if (notes.length > 0) { + b.summary = `${b.summary}\n\n[folded images: ${notes.join(" ")} — decompress({ imageRef }) restores pixels]`; + } + } + } const r = res.result; const detail = ranges.map((rg) => `${rg.startRef}–${rg.endRef}`).join(", "); if (revs.length > 0) { diff --git a/tests/session-gc.test.ts b/tests/session-gc.test.ts index 13274744bd..dc4cac751c 100644 --- a/tests/session-gc.test.ts +++ b/tests/session-gc.test.ts @@ -1,9 +1,9 @@ -import { test, beforeEach, after } from "node:test"; +import { test, beforeEach, after, before } from "node:test"; import assert from "node:assert/strict"; import http from "node:http"; import os from "node:os"; import { once } from "node:events"; -import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, statSync, utimesSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; import path from "node:path"; import { defaultConfig } from "acp-kernel"; import { startServer } from "../src/server.js"; @@ -16,6 +16,7 @@ import { createStorageCodec, parseEncryptionKey } from "../src/encrypt.js"; import { _resetSessionsForTest, getSession, markDirty, peekSession } from "../src/session.js"; import type { Session } from "../src/session.js"; import { contentStoreTokens, gcConfigFromEnv, gcSessionFiles, isGcEligible, viewFromParsed } from "../src/session-gc.js"; +import { restoreExportDirName } from "../src/image-restore.js"; const DAY = 86_400_000; @@ -121,7 +122,21 @@ beforeEach(() => { _resetSessionsForTest(); }); +// #1995: the GC's stale image-spill pass reads /retrieve/img when no +// imgRoot is passed — isolate XDG_STATE_HOME for the whole file so sweeps under +// test never touch (or delete) a developer machine's real spill tree. +let gcStateRoot: string | undefined; +let prevStateHome: string | undefined; +before(() => { + prevStateHome = process.env.XDG_STATE_HOME; + gcStateRoot = mkdtempSync(path.join(os.tmpdir(), "bili-gc-state-")); + process.env.XDG_STATE_HOME = gcStateRoot; +}); + after(() => { + if (prevStateHome === undefined) delete process.env.XDG_STATE_HOME; + else process.env.XDG_STATE_HOME = prevStateHome; + if (gcStateRoot) rmSync(gcStateRoot, { recursive: true, force: true }); _setStoreForTest(new SessionStore({ enabled: false })); }); @@ -591,3 +606,36 @@ test("records rawInputTokens per turn and persists it (#1082)", async () => { } }); }); + +test("gcSessionFiles: session deletion co-deletes its image spill dir; stale spill dirs swept by mtime (#1995)", async () => { + const dir = tmpDir("bili-gc-img-"); + const imgRoot = tmpDir("bili-gc-imgroot-"); + await withEnv({ BILI_SESSION_GC: "1" }, async () => { + const store = new SessionStore({ dir, debounceMs: 500 }); + const oldSavedAt = Date.now() - 10 * DAY; + const fDel = writeFile(dir, "anthropic/host_del.json", JSON.stringify(envelope("gc-img-1", oldSavedAt, { metadata: { rawInputTokens: 5000 } })), 10); + // Spill dir for the deleted session, FRESH mtime — the deterministic + // co-delete (session id → dir name) must take it despite the age gate. + const spill = path.join(imgRoot, restoreExportDirName("gc-img-1")); + mkdirSync(spill, { recursive: true }); + writeFileSync(path.join(spill, "m00002.png"), "x"); + // Orphaned stale dir (no session at all), backdated past the age gate. + const orphan = path.join(imgRoot, "old-lane"); + mkdirSync(orphan, { recursive: true }); + writeFileSync(path.join(orphan, "m00001.png"), "x"); + const old = new Date(Date.now() - 30 * DAY); + utimesSync(orphan, old, old); + // Fresh orphan (recent mtime) — kept; live sessions keep their spills. + const fresh = path.join(imgRoot, "fresh-lane"); + mkdirSync(fresh, { recursive: true }); + writeFileSync(path.join(fresh, "m00001.png"), "x"); + + const res = await gcSessionFiles({ dir, store, now: Date.now(), imgRoot }); + assert.equal(res.removed, 1); + assert.equal(res.imgDirsRemoved, 2, `co-delete + stale orphan, got ${JSON.stringify(res)}`); + assert.ok(!existsSync(fDel)); + assert.ok(!existsSync(spill), "spill dir co-deleted with its session despite fresh mtime"); + assert.ok(!existsSync(orphan), "stale orphan swept"); + assert.ok(existsSync(fresh), "fresh spill dir kept"); + }); +}); diff --git a/tests/strip-cutoff-anchor.test.ts b/tests/strip-cutoff-anchor.test.ts index dcdd2aea23..0f9a953044 100644 --- a/tests/strip-cutoff-anchor.test.ts +++ b/tests/strip-cutoff-anchor.test.ts @@ -6,11 +6,13 @@ import { join } from "node:path"; import { coreMessagesFor, foldAnchoredCutoff, + messageImageBytes, pruneRetrieveImgExports, restoreExportDir, + restoreExportDirName, } from "../src/image-restore.ts"; import { imagePlaceholdersForSummary } from "../src/image-note.ts"; -import type { CompressionState } from "acp-kernel"; +import type { CompressionState, Config, CoreMessage } from "acp-kernel"; const antTxt = (t: string) => ({ type: "text", text: t }); const antImg = () => ({ @@ -135,3 +137,112 @@ test("imagePlaceholdersForSummary: appends the ref, degrades without one", () => assert.deepEqual(imagePlaceholdersForSummary(m, "m00042"), ["[image: png · m00042]"]); assert.deepEqual(imagePlaceholdersForSummary(m, undefined), ["[image: png]"]); }); + +test("restoreExportDirName: sanitizer collisions are salted apart; pure ids keep their historical name (#1995 review ①)", () => { + assert.equal(restoreExportDirName("plain-session"), "plain-session", "no sanitizer change → no salt"); + const slash = restoreExportDirName("a/b"); + const dash = restoreExportDirName("a-b"); + assert.notEqual(slash, dash, "'a/b' and 'a-b' must not share a spill dir"); + assert.match(slash, /^a-b-[0-9a-f]{8}$/); + assert.equal(dash, "a-b", "already-safe ids keep their historical unsalted name"); + assert.equal(slash, restoreExportDirName("a/b"), "salt is deterministic across restarts"); + const long = "L".repeat(120); + assert.match(restoreExportDirName(long), /^L{100}-[0-9a-f]{8}$/, "truncation also salts"); +}); + +test("messageImageBytes: mirrors the Gemini-3 $ref guard — ref-pointed parts are not indexed (#1995 review ⑤)", () => { + const imgPart = { inlineData: { mimeType: "image/png", data: "QUJD" } }; + const bodyOf = (response: unknown) => ({ + model: "gemini", + contents: [{ role: "user", parts: [{ functionResponse: { name: "shot", response, parts: [imgPart] } }] }], + }); + const guarded = coreMessagesFor(bodyOf({ $ref: "part_0" }), "google")!; + const guardedCarrier = guarded.find((m) => Array.isArray((m as { rawGoogleParts?: unknown }).rawGoogleParts)); + assert.ok(guardedCarrier, "google wire produced a sidecar-carrying core message"); + assert.equal(messageImageBytes(guardedCarrier).length, 0, "$ref-pointed response parts are skipped (strip side keeps them)"); + const plain = coreMessagesFor(bodyOf({ ok: true }), "google")!; + const plainCarrier = plain.find((m) => Array.isArray((m as { rawGoogleParts?: unknown }).rawGoogleParts)); + assert.ok(plainCarrier); + assert.equal(messageImageBytes(plainCarrier).length, 1, "ordinary nested inlineData is indexed"); +}); + +test("model-driven fold: summary gains a folded-images footer carrying refs (#1995 review ④)", async () => { + // The preflight path renders host-side image notes into its summaries; a + // MODEL-driven fold writes whatever the model wrote. The footer keeps the + // decompress({ imageRef }) discoverability pointer alive in that path too. + const { createCore, defaultConfig } = await import("acp-kernel"); + const { applyRanges } = await import("../src/stream.ts"); + const { parseCompressInput } = await import("../src/compress-tool.ts"); + const { getSession } = await import("../src/session.ts"); + const { applyCompressSettings } = await import("../src/compress-settings.ts"); + + const tinyPng = + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="; + const config = applyCompressSettings( + defaultConfig(200_000), + 200_000, + { ccr: { enabled: false, minToolTokens: 50 } }, + ) as Config; + const core = createCore(); + const session = getSession(`imgfoot-${Math.random().toString(36).slice(2)}`); + const msgs: CoreMessage[] = [ + { + id: "h_0", + role: "assistant", + contentType: "tool-call", + toolCallId: "c1", + toolName: "shot", + text: "capture the failure", + }, + { + id: "h_1", + role: "tool", + contentType: "tool-result", + toolCallId: "c1", + toolName: "shot", + text: "screenshot below", + rawResponsesItem: { + type: "function_call_output", + call_id: "c1", + output: [ + { type: "input_text", text: "screenshot below" }, + { type: "input_image", image_url: `data:image/png;base64,${tinyPng}` }, + ], + }, + } as CoreMessage & Record, + ]; + for (let i = 2; i < 24; i++) { + msgs.push({ + id: `h_${i}`, + role: i % 2 === 0 ? "user" : "assistant", + contentType: "text", + text: `detail ${i} ${"x".repeat(2000)}`, + }); + } + const turn = core.processTurn({ messages: msgs, state: session.state, config, tokenCount: 9999, renderTags: "text-only" }); + session.state = turn.state; + const ctx = { core, config, messages: turn.messages, session, log: () => {} }; + applyRanges( + parseCompressInput({ content: [{ startId: "m00001", endId: "m00008", summary: "Model's own summary of the early history, setup and diagnostics." }] }), + ctx, + ); + const block = [...session.state.blocks].find((b) => b.active); + assert.ok(block, "a block was created"); + assert.match(block.summary, /Model.s own summary of the early history/); + // The image-bearing tool result is message 2 → m00002; the footer names it + // with its ref so a later turn can find the restore channel. + assert.match( + block.summary, + /\[folded images: \[image: png 1x1 · m00002\] — decompress\(\{ imageRef \}\) restores pixels\]/, + ); + // And nothing was appended when the range has no sidecar images: fold the + // pure-text tail in a second block and check its summary stays untouched. + applyRanges( + parseCompressInput({ content: [{ startId: "m00009", endId: "m00014", summary: "Second stretch of text-only history and diagnostics notes." }] }), + ctx, + ); + const blocks = [...session.state.blocks].filter((b) => b.active); + const textOnly = blocks.find((b) => b.summary.startsWith("Second stretch")); + assert.ok(textOnly, "second fold landed"); + assert.ok(!textOnly.summary.includes("[folded images:"), "no footer without covered images"); +});