Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(storage): deduplicate outbox tool images losslessly
Seraph-xea9e4c214d70
diff --git a/apps/desktop/electron/main/persistence-outbox.ts b/apps/desktop/electron/main/persistence-outbox.tsindex 07d6e40d5..646e62239 100644--- a/apps/desktop/electron/main/persistence-outbox.ts+++ b/apps/desktop/electron/main/persistence-outbox.ts@@ -1,5 +1,7 @@import { mkdir, readFile, rename, writeFile } from "node:fs/promises";import { dirname, join } from "node:path";+import { decodeBinaryStorage, encodeBinaryStorage } from "@pi-desktop/host-runtime";+import { ErrorCodes } from "@pi-desktop/shared";import type { HostProcess } from "./host-process";type MessageAppend = {@@ -143,6 +145,19 @@ export class PersistenceOutbox {await this.dropSession(sessionId);}+ /** ID-based mutations require every earlier target-session append to be durable. */+ async prepareSessionMutation(+ sessionId: string,+ getHost: () => HostProcess | null,+ ): Promise<void> {+ await this.flush(getHost);+ if (this.entries.some((entry) => entry.sessionId === sessionId)) {+ throw Object.assign(new Error("Session mutation requires pending transcript appends to reach the host"), {+ errorCode: ErrorCodes.HOST_UNAVAILABLE,+ });+ }+ }+size(): number {return this.entries.length;}@@ -268,20 +283,13 @@ export class PersistenceOutbox {private async loadEntries(): Promise<void> {try {const raw = await readFile(this.path, "utf8");- const parsed = JSON.parse(raw);- if (Array.isArray(parsed)) {- this.entries = parsed.filter((entry): entry is MessageAppend => {- return (- entry &&- typeof entry.key === "string" &&- typeof entry.sessionId === "string" &&- ("message" in entry || ("usage" in entry && typeof entry.turnId === "string"))- );- });- }- } catch (error: any) {- if (error?.code !== "ENOENT") {+ const parsed: unknown = JSON.parse(raw);+ if (!Array.isArray(parsed)) throw new Error("Invalid session persistence outbox: expected an array");+ this.entries = parsed.map(decodeAppend);+ } catch (error: unknown) {+ if (!isMissingFile(error)) {this.logger("warn", "session persistence outbox load failed", String(error));+ throw error;}}}@@ -289,21 +297,20 @@ export class PersistenceOutbox {private async loadDeadLetters(): Promise<void> {try {const raw = await readFile(this.deadLetterPath, "utf8");- const parsed = JSON.parse(raw);- if (Array.isArray(parsed)) {- this.deadLetters = parsed.filter((entry): entry is QuarantinedAppend => {- return (- entry &&- typeof entry.key === "string" &&- typeof entry.sessionId === "string" &&- typeof entry.quarantinedAt === "string" &&- ("message" in entry || ("usage" in entry && typeof entry.turnId === "string"))- );- });- }- } catch (error: any) {- if (error?.code !== "ENOENT") {+ const parsed: unknown = JSON.parse(raw);+ if (!Array.isArray(parsed)) throw new Error("Invalid session persistence dead letters: expected an array");+ this.deadLetters = parsed.map((value) => {+ const entry = decodeAppend(value);+ if (!("quarantinedAt" in entry) || typeof entry.quarantinedAt !== "string" ||+ !("reason" in entry) || typeof entry.reason !== "string") {+ throw new Error("Invalid session persistence dead letter entry");+ }+ return entry as QuarantinedAppend;+ });+ } catch (error: unknown) {+ if (!isMissingFile(error)) {this.logger("warn", "session persistence outbox dead letter load failed", String(error));+ throw error;}}}@@ -319,7 +326,7 @@ export class PersistenceOutbox {}return;}- await writeFile(this.tempPath, `${JSON.stringify(this.entries)}\n`, "utf8");+ await writeFile(this.tempPath, `${JSON.stringify(this.entries.map(encodeBinaryStorage))}\n`, "utf8");await rename(this.tempPath, this.path);});this.persistChain = write.catch(() => undefined);@@ -337,7 +344,7 @@ export class PersistenceOutbox {}return;}- await writeFile(this.tempDeadLetterPath, `${JSON.stringify(this.deadLetters)}\n`, "utf8");+ await writeFile(this.tempDeadLetterPath, `${JSON.stringify(this.deadLetters.map(encodeBinaryStorage))}\n`, "utf8");await rename(this.tempDeadLetterPath, this.deadLetterPath);});this.persistChain = write.catch(() => undefined);@@ -368,3 +375,18 @@ function isPoisonMessageError(error: unknown): boolean {function isForeignKeyError(error: unknown): boolean {return /FOREIGN KEY constraint failed/i.test(String(error));}++function isMissingFile(error: unknown): boolean {+ return error instanceof Error && "code" in error && error.code === "ENOENT";+}++function decodeAppend(value: unknown): MessageAppend {+ const entry = decodeBinaryStorage(value);+ if (!entry || typeof entry !== "object" ||+ !("key" in entry) || typeof entry.key !== "string" ||+ !("sessionId" in entry) || typeof entry.sessionId !== "string" ||+ !("message" in entry || ("usage" in entry && "turnId" in entry && typeof entry.turnId === "string"))) {+ throw new Error("Invalid session persistence outbox entry");+ }+ return entry as MessageAppend;+}diff --git a/apps/desktop/test/persistence-outbox.test.mjs b/apps/desktop/test/persistence-outbox.test.mjsindex 83307067a..43ab80575 100644--- a/apps/desktop/test/persistence-outbox.test.mjs+++ b/apps/desktop/test/persistence-outbox.test.mjs@@ -502,3 +502,106 @@ test("a restarted host retries the paused head without waiting out the backoff (assert.equal(outbox.size(), 0, "a fresh host generation drains the paused head at once");assert.equal(calls.length, paused + 1);});++test("tool images persist once while flush restores all four business copies (#1868)", async () => {+ const dir = await mkdtemp(join(tmpdir(), "pi-outbox-images-"));+ const data = "AAABBBcccDDDeeeFFF0123456789+/==";+ const result = { content: [{ type: "image", mimeType: "image/png", data }], details: { images: [{ mimeType: "image/png", data, extra: "kept" }] } };+ const message = { id: "image", role: "tool", content: JSON.stringify(result, null, 2), toolResult: result, metadata: { unknown: [1, "unchanged"] } };+ const entry = { key: "message:s:image", sessionId: "s", message };+ await new PersistenceOutbox(dir, silent).enqueue(entry, () => null);+ const raw = await readFile(join(dir, "session-message-outbox.json"), "utf8");+ assert.equal(raw.split(data).length - 1, 1, "disk must retain only one image data string");+ const calls = [];+ const reloaded = new PersistenceOutbox(dir, silent);+ await reloaded.flush(() => mockHost(async (method, params) => { calls.push({ method, params }); }));+ assert.deepEqual(calls, [{ method: "session.appendMessage", params: { sessionId: "s", message, turnId: undefined } }]);+});++test("ID mutation refuses an undrained target session and retains every queued entry", async () => {+ const dir = await mkdtemp(join(tmpdir(), "pi-outbox-mutation-"));+ const outbox = new PersistenceOutbox(dir, silent);+ await outbox.enqueue({ key: "message:s:a", sessionId: "s", message: { id: "a" } }, () => null);+ await assert.rejects(outbox.prepareSessionMutation("s", () => null), (error) => error.errorCode === "HOST_UNAVAILABLE");+ assert.equal(outbox.size(), 1);+ await outbox.prepareSessionMutation("other", () => null);+ assert.equal(outbox.size(), 1);+ await outbox.prepareSessionMutation("s", () => mockHost(async () => undefined));+ assert.equal(outbox.size(), 0);+});++test("legacy array messages and usage retain unknown fields after reload", async () => {+ const dir = await mkdtemp(join(tmpdir(), "pi-outbox-legacy-"));+ const entries = [+ { key: "message:s:m", sessionId: "s", message: { id: "m", unknown: { nested: ["literal", 42] } }, unknown: "entry" },+ { key: "usage:s:t", sessionId: "s", turnId: "t", usage: { tokens: 17, details: { arbitrary: [1, 2] } } },+ ];+ await writeFile(join(dir, "session-message-outbox.json"), JSON.stringify(entries));+ const calls = [];+ await new PersistenceOutbox(dir, silent).flush(() => mockHost(async (method, params) => { calls.push({ method, params }); }));+ assert.deepEqual(calls, [+ { method: "session.appendMessage", params: { sessionId: "s", message: entries[0].message, turnId: undefined } },+ { method: "session.recordUsage", params: { sessionId: "s", usage: entries[1].usage, turnId: "t" } },+ ]);+});++test("image dead letters persist once and remain exact after reload and a later quarantine", async () => {+ const dir = await mkdtemp(join(tmpdir(), "pi-outbox-dead-images-"));+ const now = { value: 0 };+ const data = "longImageData1234567890+/==";+ const result = { content: [{ type: "image", mimeType: "image/png", data }], images: [{ mimeType: "image/png", data }] };+ const message = { id: "image", content: JSON.stringify(result), toolResult: result, extra: { unknown: true } };+ const outbox = new PersistenceOutbox(dir, silent, { now: () => now.value });+ const rejecting = mockHost(async () => { throw new Error("unclassified failure"); });+ await outbox.enqueue({ key: "message:s:image", sessionId: "s", message }, () => rejecting);+ assert.equal(await drain(outbox, rejecting, now), 0);+ const path = join(dir, DEAD_LETTER_FILE);+ const first = await readFile(path, "utf8");+ assert.equal(first.split(data).length - 1, 1);+ const reloaded = new PersistenceOutbox(dir, silent, { now: () => now.value });+ await reloaded.enqueue({ key: "message:other:m", sessionId: "other", message: { id: "m" } }, () => rejecting);+ assert.equal(await drain(reloaded, rejecting, now), 0);+ const dead = JSON.parse(await readFile(path, "utf8"));+ assert.equal(dead.length, 2);+ // The public codec is also the recovery reader for manual dead-letter replay.+ const { decodeBinaryStorage } = await import("@pi-desktop/host-runtime");+ assert.deepEqual(decodeBinaryStorage(dead[0]).message, message);+ assert.equal(dead[1].message.id, "m");+});++test("corrupt encoded outbox entries reject recovery and preserve the disk file", async () => {+ for (const file of ["session-message-outbox.json", DEAD_LETTER_FILE]) {+ const dir = await mkdtemp(join(tmpdir(), "pi-outbox-corrupt-"));+ const path = join(dir, file);+ const raw = JSON.stringify([{ key: "message:s:m", sessionId: "s", message: { id: "m" }, binaryStorage: { version: 99, data: [], refs: [], texts: [] } }]);+ await writeFile(path, raw);+ const logs = [];+ const outbox = new PersistenceOutbox(dir, (_level, message) => logs.push(message));+ await assert.rejects(outbox.flush(() => null), /binary storage/i);+ await assert.rejects(outbox.enqueue({ key: "message:s:new", sessionId: "s", message: { id: "new" } }, () => null), /binary storage/i);+ assert.equal(await readFile(path, "utf8"), raw);+ assert.ok(logs.some((message) => /load failed/.test(message)));+ }+});++test("mutation waits for active append and refuses a backed-off target without dropping it", async () => {+ const dir = await mkdtemp(join(tmpdir(), "pi-outbox-mutation-flight-"));+ let release;+ let appendStarted;+ const started = new Promise((resolve) => { appendStarted = resolve; });+ const blocked = new Promise((resolve) => { release = resolve; });+ const host = mockHost(async () => { appendStarted(); await blocked; throw new Error("host unavailable"); });+ const outbox = new PersistenceOutbox(dir, silent);+ await outbox.enqueue({ key: "message:s:m", sessionId: "s", message: { id: "m" } }, () => host);+ await started;+ let settled = false;+ const preparing = assert.rejects(outbox.prepareSessionMutation("s", () => host), (error) => error.errorCode === "HOST_UNAVAILABLE").then(() => { settled = true; });+ await Promise.resolve();+ assert.equal(settled, false);+ release();+ await preparing;+ assert.equal(outbox.size(), 1);+ await assert.rejects(outbox.prepareSessionMutation("s", () => host), (error) => error.errorCode === "HOST_UNAVAILABLE");+ const stored = JSON.parse(await readFile(join(dir, "session-message-outbox.json"), "utf8"));+ assert.equal(stored[0].message.id, "m");+});diff --git a/packages/host-runtime/src/binary-storage.test.ts b/packages/host-runtime/src/binary-storage.test.tsnew file mode 100644index 000000000..12c9a65c2--- /dev/null+++ b/packages/host-runtime/src/binary-storage.test.ts@@ -0,0 +1,184 @@+import { describe, expect, it } from "vitest";+import golden from "./fixtures/binary-storage.json";+import { decodeBinaryStorage, encodeBinaryStorage } from "./binary-storage.js";++const image = (data = "A/B=") => ({ type: "image", mimeType: "image/png", data });+const record = () => {+ const toolResult = {+ content: [image()],+ details: { images: [{ mimeType: "image/png", data: "A/B=" }] },+ };+ return { id: "m", content: JSON.stringify(toolResult), toolResult };+};++describe("lossless binary storage", () => {+ it("matches the common v1 golden envelope and preserves exact text spellings", () => {+ expect(encodeBinaryStorage(golden.original)).toEqual(golden.encoded);+ expect(decodeBinaryStorage(golden.encoded)).toEqual(golden.original);+ });++ it("stores four business copies once without mutating the input", () => {+ const original = record();+ const before = structuredClone(original);+ const encoded = encodeBinaryStorage(original);+ expect(JSON.stringify(encoded).split("A/B=").length - 1).toBe(1);+ expect(decodeBinaryStorage(JSON.parse(JSON.stringify(encoded)))).toEqual(original);+ expect(original).toEqual(before);+ expect(decodeBinaryStorage(encoded)).toEqual(before);+ expect(encoded).not.toEqual(before);+ });++ it("leaves legacy records, single images, generic data and non-ASCII data unchanged", () => {+ for (const original of [+ null,+ [1, "ordinary"],+ { content: [image()] },+ { a: { data: "A/B=" }, b: { data: "A/B=" } },+ { content: [image("中文"), image("中文")] },+ ]) {+ expect(encodeBinaryStorage(original)).toEqual(original);+ expect(decodeBinaryStorage(original)).toEqual(original);+ }+ });++ it("encodes resources, images arrays and all unknown metadata losslessly", () => {+ const original = {+ nested: {+ result: {+ content: [+ { type: "resource", resource: { uri: "test:", mimeType: "image/png", blob: "A/B=" } },+ ],+ images: [{ mimeType: "image/png", data: "A/B=", unknown: true }],+ },+ text: "ordinary",+ },+ usage: { unknown: [2, "x"] },+ };+ const encoded = encodeBinaryStorage(original);+ expect(JSON.stringify(encoded).split("A/B=").length - 1).toBe(1);+ expect(decodeBinaryStorage(encoded)).toEqual(original);+ });++ it("does not template JSON that differs from a sibling result", () => {+ const original = {+ content: JSON.stringify({ content: [image()], extra: 1 }),+ toolResult: { content: [image(), image()] },+ text: "A/B=",+ unknown: "A/B=",+ };+ const encoded = encodeBinaryStorage(original) as typeof original;+ expect(encoded.content).toBe(original.content);+ expect(encoded.text).toBe(original.text);+ expect(encoded.unknown).toBe(original.unknown);+ expect(decodeBinaryStorage(encoded)).toEqual(original);+ });++ it("supports text mirrors, multiple images and escaped property names", () => {+ const result = { content: [image("AA=="), image("BB==")] };+ const text = JSON.stringify(result).replace('"data"', '"d\\u0061ta"');+ const original = { messages: [{ result, text, metadata: { source: "unknown" } }] };+ const encoded = encodeBinaryStorage(original);+ expect(JSON.stringify(encoded).split("AA==").length - 1).toBe(1);+ expect(JSON.stringify(encoded).split("BB==").length - 1).toBe(1);+ expect(decodeBinaryStorage(encoded)).toEqual(original);+ });++ it("retains literal duplicate JSON keys while templating only matching image values", () => {+ const result = { content: [image()] };+ const original = {+ result,+ content:+ '{"ignored":0,"ignored":1,"content":[{"type":"image","mimeType":"image/png","data":"A/B="}]}',+ };+ // The extra ignored field prevents mirror equality.+ expect((encodeBinaryStorage(original) as typeof original).content).toBe(original.content);+ });+});++describe("corrupt binary storage is an explicit error", () => {+ const corrupted = (mutate: (value: typeof golden.encoded) => void) => {+ const value = structuredClone(golden.encoded);+ mutate(value);+ return value;+ };++ it.each([+ [+ "unknown version",+ (v: typeof golden.encoded) => {+ v.binaryStorage.version = 2;+ },+ ],+ [+ "missing image",+ (v: typeof golden.encoded) => {+ v.binaryStorage.refs[0].image = 50;+ },+ ],+ [+ "non-base64 table data",+ (v: typeof golden.encoded) => {+ v.binaryStorage.data[0] = "中文";+ },+ ],+ [+ "non-null placeholder",+ (v: typeof golden.encoded) => {+ v.toolResult.content[0].data = "unexpected" as unknown as null;+ },+ ],+ [+ "missing path",+ (v: typeof golden.encoded) => {+ v.binaryStorage.refs[0].path = ["absent"];+ },+ ],+ [+ "illegal binary position",+ (v: typeof golden.encoded) => {+ v.binaryStorage.refs[0].path = ["content"];+ },+ ],+ [+ "duplicate ref",+ (v: typeof golden.encoded) => {+ v.binaryStorage.refs.push(v.binaryStorage.refs[0]);+ },+ ],+ [+ "overlapping path",+ (v: typeof golden.encoded) => {+ v.binaryStorage.refs[1].path = ["toolResult"];+ },+ ],+ [+ "invalid escape offset",+ (v: typeof golden.encoded) => {+ const p = v.binaryStorage.texts[0].parts[1];+ if (typeof p !== "string" && p.escapes) p.escapes[0].at = 99;+ },+ ],+ [+ "invalid escape spelling",+ (v: typeof golden.encoded) => {+ const p = v.binaryStorage.texts[0].parts[1];+ if (typeof p !== "string" && p.escapes) p.escapes[0].raw = "\\u0042";+ },+ ],+ [+ "invalid mirror",+ (v: typeof golden.encoded) => {+ v.binaryStorage.texts[0].parts[0] = "{}";+ },+ ],+ [+ "unproven mirror",+ (v: typeof golden.encoded) => {+ v.binaryStorage.texts[0].path = ["metadata", "unused"];+ Object.assign(v.metadata, { unused: null });+ },+ ],+ ])("rejects %s", (_name, mutate) => {+ expect(() => decodeBinaryStorage(corrupted(mutate))).toThrow(/binary storage/i);+ });+});diff --git a/packages/host-runtime/src/binary-storage.ts b/packages/host-runtime/src/binary-storage.tsnew file mode 100644index 000000000..4cb04c555--- /dev/null+++ b/packages/host-runtime/src/binary-storage.ts@@ -0,0 +1,401 @@+/** Storage-only, reversible image deduplication. Business values never use this envelope. */+type Path = (string | number)[];+type JsonObject = Record<string, unknown>;+type ImageRef = { path: Path; image: number };+type Escape = { at: number; raw: string };+type ImagePart = { image: number; escapes?: Escape[] };+type TextRef = { path: Path; parts: (string | ImagePart)[] };+type Envelope = { version: 1; data: string[]; refs: ImageRef[]; texts: TextRef[] };+type Token = { path: Path; start: number; end: number; value: string };++const isObject = (value: unknown): value is JsonObject =>+ value !== null && typeof value === "object" && !Array.isArray(value);+const isBase64 = (value: unknown): value is string =>+ typeof value === "string" && /^[A-Za-z0-9+/]+={0,2}$/.test(value);+const pathKey = (path: Path) => JSON.stringify(path);+const own = (value: object, key: string | number) => Object.hasOwn(value, key);+function invalid(reason: string): never {+ throw new Error(`Invalid binary storage: ${reason}`);+}++function walk(+ value: unknown,+ visit: (object: JsonObject, path: Path) => void,+ path: Path = [],+): void {+ if (Array.isArray(value)) value.forEach((item, index) => walk(item, visit, [...path, index]));+ else if (isObject(value)) {+ visit(value, path);+ for (const [key, item] of Object.entries(value)) walk(item, visit, [...path, key]);+ }+}++/** Only recognized binary positions are eligible; arbitrary data/text remains literal. */+function imagePositions(value: unknown): Path[] {+ const paths: Path[] = [];+ walk(value, (object, path) => {+ if (object.type === "image" && own(object, "data")) paths.push([...path, "data"]);+ if (object.type === "resource" && isObject(object.resource) && own(object.resource, "blob")) {+ paths.push([...path, "resource", "blob"]);+ }+ if (Array.isArray(object.images))+ object.images.forEach((image, index) => {+ if (isObject(image) && typeof image.mimeType === "string" && own(image, "data")) {+ paths.push([...path, "images", index, "data"]);+ }+ });+ });+ return [...new Map(paths.map((path) => [pathKey(path), path])).values()];+}++function parentAt(+ root: unknown,+ path: Path,+): { parent: JsonObject | unknown[]; key: string | number } {+ if (!path.length) invalid("empty placeholder path");+ let parent = root;+ for (const key of path.slice(0, -1)) parent = childAt(parent, key);+ const key = path[path.length - 1];+ childAt(parent, key);+ return { parent: parent as JsonObject | unknown[], key };+}+function childAt(parent: unknown, key: string | number): unknown {+ if (Array.isArray(parent)) {+ if (typeof key !== "number" || !Number.isSafeInteger(key) || key < 0 || !own(parent, key))+ invalid("invalid array path");+ } else if (!isObject(parent) || typeof key !== "string" || !own(parent, key))+ invalid("missing object path");+ return (parent as JsonObject)[key];+}+function valueAt(root: unknown, path: Path): unknown {+ return path.reduce(childAt, root);+}+function setAt(root: unknown, path: Path, value: unknown): void {+ const { parent, key } = parentAt(root, path);+ (parent as JsonObject)[key] = value;+}++function equal(left: unknown, right: unknown): boolean {+ if (left === right) return true;+ if (Array.isArray(left) && Array.isArray(right))+ return left.length === right.length && left.every((item, index) => equal(item, right[index]));+ if (!isObject(left) || !isObject(right)) return false;+ const keys = Object.keys(left);+ return (+ keys.length === Object.keys(right).length &&+ keys.every((key) => own(right, key) && equal(left[key], right[key]))+ );+}+function parseMirror(text: string): unknown {+ try {+ return JSON.parse(text) as unknown;+ } catch {+ return undefined;+ }+}+function matchesSibling(parent: JsonObject, parsed: unknown): boolean {+ return (+ parsed !== undefined &&+ ["result", "toolResult"].some((key) => own(parent, key) && equal(parent[key], parsed))+ );+}++/** JSON.parse proves validity; this scanner retains token offsets and original spelling. */+function stringTokens(text: string): Token[] {+ const tokens: Token[] = [];+ let offset = 0;+ const whitespace = () => {+ while (offset < text.length && /\s/.test(text[offset])) offset++;+ };+ const string = (): { start: number; end: number; value: string } => {+ const start = offset++;+ while (offset < text.length) {+ const character = text[offset++];+ if (character === "\\") offset++;+ else if (character === '"') break;+ }+ return { start, end: offset, value: JSON.parse(text.slice(start, offset)) as string };+ };+ const value = (path: Path): void => {+ whitespace();+ const character = text[offset];+ if (character === '"') {+ tokens.push({ path, ...string() });+ return;+ }+ if (character === "{" || character === "[") {+ const object = character === "{";+ const close = object ? "}" : "]";+ offset++;+ whitespace();+ let index = 0;+ while (text[offset] !== close) {+ whitespace();+ const key = object ? string().value : index++;+ if (object) {+ whitespace();+ offset++;+ }+ value([...path, key]);+ whitespace();+ if (text[offset] !== ",") break;+ offset++;+ }+ offset++;+ } else {+ while (offset < text.length && !/[\s,\]}]/.test(text[offset])) offset++;+ }+ };+ value([]);+ return tokens;+}+function imageTokens(text: string, parsed: unknown): Token[] {+ const positions = new Set(imagePositions(parsed).map(pathKey));+ return stringTokens(text).filter(+ (token) => positions.has(pathKey(token.path)) && isBase64(token.value),+ );+}+function imagePart(text: string, token: Token, image: number): ImagePart {+ const spelling = text.slice(token.start + 1, token.end - 1);+ const escapes: Escape[] = [];+ for (let rawOffset = 0, at = 0; rawOffset < spelling.length; at++) {+ if (spelling[rawOffset] !== "\\") {+ rawOffset++;+ continue;+ }+ const length = spelling[rawOffset + 1] === "u" ? 6 : 2;+ escapes.push({ at, raw: spelling.slice(rawOffset, rawOffset + length) });+ rawOffset += length;+ }+ return { image, ...(escapes.length ? { escapes } : {}) };+}++export function encodeBinaryStorage(value: unknown): unknown {+ if (!isObject(value)) return value;+ if (own(value, "binaryStorage")) invalid("reserved binaryStorage field already exists");+ const refs: ImageRef[] = [];+ const data: string[] = [];+ const indexes = new Map<string, number>();+ const indexOf = (dataString: string): number => {+ let index = indexes.get(dataString);+ if (index === undefined) {+ index = data.length;+ data.push(dataString);+ indexes.set(dataString, index);+ }+ return index;+ };+ for (const path of imagePositions(value)) {+ const dataString = valueAt(value, path);+ if (isBase64(dataString)) refs.push({ path, image: indexOf(dataString) });+ }+ if (!refs.length) return value;+ const texts: TextRef[] = [];+ walk(value, (parent, path) => {+ for (const key of ["content", "text"]) {+ const text = parent[key];+ if (typeof text !== "string") continue;+ const parsed = parseMirror(text);+ if (!matchesSibling(parent, parsed)) continue;+ const tokens = imageTokens(text, parsed);+ if (!tokens.length) continue;+ const parts: TextRef["parts"] = [];+ let start = 0;+ for (const token of tokens) {+ parts.push(text.slice(start, token.start), imagePart(text, token, indexOf(token.value)));+ start = token.end;+ }+ parts.push(text.slice(start));+ texts.push({ path: [...path, key], parts });+ }+ });+ const occurrences =+ refs.length ++ texts.reduce(+ (count, text) => count + text.parts.filter((part) => typeof part !== "string").length,+ 0,+ );+ if (occurrences === data.length) return value;+ const encoded = structuredClone(value);+ for (const ref of [...refs, ...texts]) setAt(encoded, ref.path, null);+ encoded.binaryStorage = { version: 1, data, refs, texts } satisfies Envelope;+ return encoded;+}++function exactKeys(value: JsonObject, required: string[], optional: string[] = []): void {+ if (+ required.some((key) => !own(value, key)) ||+ Object.keys(value).some((key) => !required.includes(key) && !optional.includes(key))+ )+ invalid("unexpected envelope fields");+}+function parsePath(value: unknown): Path {+ if (+ !Array.isArray(value) ||+ value.length === 0 ||+ value.some(+ (key) =>+ typeof key !== "string" &&+ !(typeof key === "number" && Number.isSafeInteger(key) && key >= 0),+ )+ )+ invalid("invalid placeholder path");+ if (value[0] === "binaryStorage") invalid("placeholder inside envelope");+ return value as Path;+}+function tableIndex(value: unknown, data: string[]): number {+ if (+ typeof value !== "number" ||+ !Number.isSafeInteger(value) ||+ value < 0 ||+ value >= data.length+ )+ invalid("invalid image index");+ return value;+}+function parseEnvelope(value: unknown): Envelope {+ if (!isObject(value)) invalid("envelope must be an object");+ exactKeys(value, ["version", "data", "refs", "texts"]);+ if (value.version !== 1) invalid("unsupported version");+ if (+ !Array.isArray(value.data) ||+ !value.data.length ||+ !value.data.every(isBase64) ||+ new Set(value.data).size !== value.data.length+ )+ invalid("invalid data table");+ if (!Array.isArray(value.refs) || !Array.isArray(value.texts))+ invalid("refs and texts must be arrays");+ for (const ref of value.refs) {+ if (!isObject(ref)) invalid("invalid reference");+ exactKeys(ref, ["path", "image"]);+ parsePath(ref.path);+ tableIndex(ref.image, value.data);+ }+ for (const text of value.texts) {+ if (!isObject(text)) invalid("invalid text reference");+ exactKeys(text, ["path", "parts"]);+ parsePath(text.path);+ if (!Array.isArray(text.parts) || !text.parts.some((part) => typeof part !== "string"))+ invalid("invalid text parts");+ for (const part of text.parts)+ if (typeof part !== "string") {+ if (!isObject(part)) invalid("invalid image part");+ exactKeys(part, ["image"], ["escapes"]);+ tableIndex(part.image, value.data);+ if (part.escapes !== undefined && !Array.isArray(part.escapes)) invalid("invalid escapes");+ }+ }+ return value as unknown as Envelope;+}++/** Reject duplicate and ancestor paths before restoring any placeholder. */+function validatePaths(root: JsonObject, paths: Path[]): void {+ type Trie = { terminal: boolean; children: Map<string | number, Trie> };+ const trie: Trie = { terminal: false, children: new Map() };+ for (const path of paths) {+ if (valueAt(root, path) !== null) invalid("placeholder must be null");+ let node = trie;+ for (const key of path) {+ if (node.terminal) invalid("overlapping placeholder paths");+ let next = node.children.get(key);+ if (!next) {+ next = { terminal: false, children: new Map() };+ node.children.set(key, next);+ }+ node = next;+ }+ if (node.terminal || node.children.size) invalid("duplicate or overlapping placeholder paths");+ node.terminal = true;+ }+}+function renderImage(part: ImagePart, data: string): string {+ const overrides = new Map<number, string>();+ let last = -1;+ for (const escape of part.escapes ?? []) {+ if (!isObject(escape)) invalid("invalid escape");+ exactKeys(escape, ["at", "raw"]);+ if (+ !Number.isSafeInteger(escape.at) ||+ escape.at <= last ||+ escape.at >= data.length ||+ typeof escape.raw !== "string" ||+ !/^(?:\\\/|\\u[0-9a-fA-F]{4})$/.test(escape.raw)+ )+ invalid("invalid escape spelling or offset");+ if (JSON.parse(`"${escape.raw}"`) !== data[escape.at]) invalid("escape changes image data");+ overrides.set(escape.at, escape.raw);+ last = escape.at;+ }+ if (!overrides.size) return `"${data}"`;+ const chunks: string[] = ['"'];+ let start = 0;+ for (const [at, raw] of overrides) {+ chunks.push(data.slice(start, at), raw);+ start = at + 1;+ }+ chunks.push(data.slice(start), '"');+ return chunks.join("");+}+function restoreText(+ text: TextRef,+ data: string[],+): { value: string; spans: { start: number; end: number; image: number }[] } {+ const chunks: string[] = [];+ const spans: { start: number; end: number; image: number }[] = [];+ let length = 0;+ for (const part of text.parts) {+ const chunk = typeof part === "string" ? part : renderImage(part, data[part.image]);+ if (typeof part !== "string")+ spans.push({ start: length, end: length + chunk.length, image: part.image });+ chunks.push(chunk);+ length += chunk.length;+ }+ return { value: chunks.join(""), spans };+}++export function decodeBinaryStorage(value: unknown): unknown {+ if (!isObject(value) || !own(value, "binaryStorage")) return value;+ const envelope = parseEnvelope(value.binaryStorage);+ const decoded = structuredClone(value);+ delete decoded.binaryStorage;+ validatePaths(+ decoded,+ [...envelope.refs, ...envelope.texts].map((ref) => ref.path),+ );+ const positions = new Set(imagePositions(decoded).map(pathKey));+ const used = new Set<number>();+ for (const ref of envelope.refs) {+ if (!positions.has(pathKey(ref.path))) invalid("reference is not a binary field");+ setAt(decoded, ref.path, envelope.data[ref.image]);+ used.add(ref.image);+ }+ // Restore all mirrors before comparing, since nested mirror siblings can reference one another.+ const mirrors = envelope.texts.map((text) => ({ text, ...restoreText(text, envelope.data) }));+ for (const mirror of mirrors) setAt(decoded, mirror.text.path, mirror.value);+ for (const mirror of mirrors) {+ const { parent, key } = parentAt(decoded, mirror.text.path);+ const parsed = parseMirror(mirror.value);+ if (+ !isObject(parent) ||+ (key !== "content" && key !== "text") ||+ !matchesSibling(parent, parsed)+ )+ invalid("text is not an exact result mirror");+ const tokens = imageTokens(mirror.value, parsed);+ for (const span of mirror.spans) {+ if (+ !tokens.some(+ (token) =>+ token.start === span.start &&+ token.end === span.end &&+ token.value === envelope.data[span.image],+ )+ )+ invalid("text reference is not a binary token");+ used.add(span.image);+ }+ }+ if (used.size !== envelope.data.length) invalid("unused data table entry");+ return decoded;+}diff --git a/packages/host-runtime/src/fixtures/binary-storage.json b/packages/host-runtime/src/fixtures/binary-storage.jsonnew file mode 100644index 000000000..705ffea85--- /dev/null+++ b/packages/host-runtime/src/fixtures/binary-storage.json@@ -0,0 +1,113 @@+{+ "original": {+ "id": "golden",+ "content": " { \"details\": {\"images\":[{\"data\":\"\\u0041\\/B=\",\"mimeType\":\"image/png\",\"extra\":\"kept\"}]}, \"content\": [{\"type\":\"image\",\"mimeType\":\"image/png\",\"data\":\"A/B=\"}] }\n",+ "toolResult": {+ "content": [+ {+ "type": "image",+ "mimeType": "image/png",+ "data": "A/B="+ }+ ],+ "details": {+ "images": [+ {+ "mimeType": "image/png",+ "data": "A/B=",+ "extra": "kept"+ }+ ]+ }+ },+ "metadata": {+ "unknown": [+ 1,+ "kept"+ ]+ }+ },+ "encoded": {+ "id": "golden",+ "content": null,+ "toolResult": {+ "content": [+ {+ "type": "image",+ "mimeType": "image/png",+ "data": null+ }+ ],+ "details": {+ "images": [+ {+ "mimeType": "image/png",+ "data": null,+ "extra": "kept"+ }+ ]+ }+ },+ "metadata": {+ "unknown": [+ 1,+ "kept"+ ]+ },+ "binaryStorage": {+ "version": 1,+ "data": [+ "A/B="+ ],+ "refs": [+ {+ "path": [+ "toolResult",+ "content",+ 0,+ "data"+ ],+ "image": 0+ },+ {+ "path": [+ "toolResult",+ "details",+ "images",+ 0,+ "data"+ ],+ "image": 0+ }+ ],+ "texts": [+ {+ "path": [+ "content"+ ],+ "parts": [+ " { \"details\": {\"images\":[{\"data\":",+ {+ "image": 0,+ "escapes": [+ {+ "at": 0,+ "raw": "\\u0041"+ },+ {+ "at": 1,+ "raw": "\\/"+ }+ ]+ },+ ",\"mimeType\":\"image/png\",\"extra\":\"kept\"}]}, \"content\": [{\"type\":\"image\",\"mimeType\":\"image/png\",\"data\":",+ {+ "image": 0+ },+ "}] }\n"+ ]+ }+ ]+ }+ }+}diff --git a/packages/host-runtime/src/index.ts b/packages/host-runtime/src/index.tsindex 7edac2dcb..35b11b7dd 100644--- a/packages/host-runtime/src/index.ts+++ b/packages/host-runtime/src/index.ts@@ -20,3 +20,4 @@ export * from "./live-work/feedback-scheduler.js";export * from "./live-work/result-summary.js";export * from "./fs-index.js";export * from "./chat-ref-resolve.js";+export * from "./binary-storage.js";