diff --git a/.changeset/state-backend-binary-base64.md b/.changeset/state-backend-binary-base64.md new file mode 100644 index 000000000..cd40d364a --- /dev/null +++ b/.changeset/state-backend-binary-base64.md @@ -0,0 +1,5 @@ +--- +"deepagents": patch +--- + +`StateBackend` stores binary uploads and writes as base64 text with `encoding: "base64"`, so threads with uploaded images or PDFs keep working after a JSON checkpointer round trip. Uploads at text paths whose bytes are not valid UTF-8 are kept byte-for-byte as `application/octet-stream` instead of being lossily decoded. diff --git a/libs/deepagents/src/backends/protocol.ts b/libs/deepagents/src/backends/protocol.ts index 682ad7cbc..6f0795706 100644 --- a/libs/deepagents/src/backends/protocol.ts +++ b/libs/deepagents/src/backends/protocol.ts @@ -139,6 +139,12 @@ export interface FileDataV2 { content: string | Uint8Array; /** MIME type of the file (e.g. "image/png", "text/plain") */ mimeType: string; + /** + * How string `content` is encoded. `"base64"` marks binary bytes stored as + * base64 text so they survive JSON serialization (e.g. a checkpointer). + * Omitted means plain text. + */ + encoding?: "utf-8" | "base64"; /** ISO format timestamp of creation */ created_at: string; /** ISO format timestamp of last modification */ diff --git a/libs/deepagents/src/backends/state.test.ts b/libs/deepagents/src/backends/state.test.ts index 7902e5661..f9b271a9e 100644 --- a/libs/deepagents/src/backends/state.test.ts +++ b/libs/deepagents/src/backends/state.test.ts @@ -3,6 +3,7 @@ import { StateBackend } from "./state.js"; import type { FileData, FileDataV1 } from "./protocol.js"; import { getConfig, Command } from "@langchain/langgraph"; import { ToolMessage } from "@langchain/core/messages"; +import { FileDataSchema } from "../middleware/fs.js"; vi.mock("@langchain/langgraph", async (importOriginal) => { const actual = await importOriginal(); @@ -504,7 +505,7 @@ describe("StateBackend", () => { expect((result as any).filesUpdate["/hello.txt"].content).toBe("Hello"); }); - it("should upload binary (image) files as Uint8Array", () => { + it("should store binary (image) uploads as base64 text", () => { const { state, runtime } = makeConfig(); const backend = new StateBackend(runtime); @@ -515,9 +516,11 @@ describe("StateBackend", () => { expect(result[0].error).toBeNull(); Object.assign(state.files, (result as any).filesUpdate); - const stored = state.files["/image.png"]; - expect(stored.content).toBeInstanceOf(Uint8Array); - expect(stored.content).toEqual(pngBytes); + expect(state.files["/image.png"]).toMatchObject({ + content: Buffer.from(pngBytes).toString("base64"), + encoding: "base64", + mimeType: "image/png", + }); }); }); @@ -650,7 +653,7 @@ describe("StateBackend", () => { const full = backend.read("/img.png"); const withOffsetLimit = backend.read("/img.png", 5, 2); - expect(withOffsetLimit.content).toBe(full.content); + expect(withOffsetLimit.content).toEqual(full.content); }); }); @@ -934,4 +937,140 @@ describe("StateBackend", () => { expect(result.filesUpdate).toBeUndefined(); }); }); + + describe("JSON-serialized state", () => { + const pngBytes = new Uint8Array([ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0xff, + ]); + + /** Serialize state the way a JSON checkpointer does, then reopen it. */ + function roundTrip(state: { files: Record }) { + const restored = JSON.parse(JSON.stringify(state)); + return { + files: restored.files as Record, + backend: new StateBackend({ state: restored, store: undefined }), + }; + } + + function uploadAndRoundTrip(files: Array<[string, Uint8Array]>) { + const { state, runtime } = makeConfig(); + const result = new StateBackend(runtime).uploadFiles(files); + Object.assign(state.files, (result as any).filesUpdate); + return roundTrip(state); + } + + it("keeps binary uploads valid against the files schema", () => { + const { files } = uploadAndRoundTrip([["/image.png", pngBytes]]); + + expect(FileDataSchema.parse(files["/image.png"])).toMatchObject({ + encoding: "base64", + mimeType: "image/png", + }); + }); + + it("reads, downloads, and sizes binary uploads byte-identically", () => { + const { backend } = uploadAndRoundTrip([["/image.png", pngBytes]]); + + expect(backend.read("/image.png")).toEqual({ + content: pngBytes, + mimeType: "image/png", + }); + expect(backend.readRaw("/image.png").data!.content).toEqual(pngBytes); + expect(backend.downloadFiles(["/image.png"])[0].content).toEqual( + pngBytes, + ); + expect(backend.ls("/").files![0].size).toBe(pngBytes.length); + expect(backend.glob("*.png").files![0].size).toBe(pngBytes.length); + }); + + it("returns an image block from read_file", async () => { + const { backend } = uploadAndRoundTrip([["/image.png", pngBytes]]); + const { createFilesystemMiddleware } = + await import("../middleware/fs.js"); + const readFileTool = createFilesystemMiddleware({ backend }).tools!.find( + (tool) => tool.name === "read_file", + ); + + const result = await readFileTool!.invoke({ file_path: "/image.png" }); + + expect(result).toEqual([ + { + type: "image", + mimeType: "image/png", + data: Buffer.from(pngBytes).toString("base64"), + }, + ]); + }); + + it("stores non-UTF-8 bytes at a text path as binary", () => { + const bytes = new Uint8Array([0xff, 0xfe, 0x00, 0x80, 0x41]); + const { files, backend } = uploadAndRoundTrip([["/blob.dat", bytes]]); + + expect(files["/blob.dat"]).toMatchObject({ + encoding: "base64", + mimeType: "application/octet-stream", + }); + expect(backend.downloadFiles(["/blob.dat"])[0].content).toEqual(bytes); + expect(backend.grep("A").matches).toEqual([]); + }); + + it("reads text written over a non-UTF-8 upload as text", () => { + const { state, runtime } = makeConfig(); + const backend = new StateBackend(runtime); + const upload = backend.uploadFiles([ + ["/blob.dat", new Uint8Array([0xff, 0xfe])], + ]); + Object.assign(state.files, (upload as any).filesUpdate); + + const result = backend.write("/blob.dat", "hello"); + Object.assign(state.files, result.filesUpdate); + + expect(backend.read("/blob.dat")).toMatchObject({ + content: "hello", + mimeType: "text/plain", + }); + }); + + it("keeps UTF-8 uploads at text paths as plain text", () => { + const { files } = uploadAndRoundTrip([ + ["/notes.txt", new TextEncoder().encode("h\u00e9llo")], + ]); + + expect(files["/notes.txt"].content).toBe("h\u00e9llo"); + expect(files["/notes.txt"]).not.toHaveProperty("encoding"); + }); + + it("stores binary-path writes as base64 text", () => { + const { state, runtime } = makeConfig(); + const result = new StateBackend(runtime).write( + "/image.png", + Buffer.from(pngBytes).toString("base64"), + ); + Object.assign(state.files, result.filesUpdate); + + const { files, backend } = roundTrip(state); + + expect(files["/image.png"]).toMatchObject({ encoding: "base64" }); + expect(backend.downloadFiles(["/image.png"])[0].content).toEqual( + pngBytes, + ); + }); + + it("still reads Uint8Array entries stored before base64 encoding", () => { + const { runtime } = makeConfig({ + "/old.png": { + content: pngBytes, + mimeType: "image/png", + created_at: "2024-01-01T00:00:00.000Z", + modified_at: "2024-01-01T00:00:00.000Z", + }, + }); + const backend = new StateBackend(runtime); + + expect(backend.read("/old.png").content).toEqual(pngBytes); + expect(backend.readRaw("/old.png").data!.content).toEqual(pngBytes); + expect(backend.downloadFiles(["/old.png"])[0].content).toEqual(pngBytes); + expect(backend.ls("/").files![0].size).toBe(pngBytes.length); + }); + }); }); diff --git a/libs/deepagents/src/backends/state.ts b/libs/deepagents/src/backends/state.ts index fa04e5ddd..519601566 100644 --- a/libs/deepagents/src/backends/state.ts +++ b/libs/deepagents/src/backends/state.ts @@ -6,6 +6,7 @@ import type { DeleteResult, EditResult, FileData, + FileDataV2, FileDownloadResponse, FileInfo, FileUploadResponse, @@ -46,6 +47,66 @@ function trimTrailingSlashes(path: string): string { const PREGEL_SEND_KEY = "__pregel_send"; const PREGEL_READ_KEY = "__pregel_read"; +function isBase64Encoded( + data: FileData, +): data is FileDataV2 & { content: string; encoding: "base64" } { + return ( + !isFileDataV1(data) && + data.encoding === "base64" && + typeof data.content === "string" + ); +} + +/** + * Store binary content as base64 text. State is checkpointed as JSON, which + * turns a Uint8Array into an object of numeric keys that fails the files + * schema on the next run. + */ +function toStoredFileData(data: FileData): FileData { + if (!isFileDataBinary(data)) { + return data; + } + return { + ...data, + content: Buffer.from(data.content).toString("base64"), + encoding: "base64", + }; +} + +/** Decode base64-stored content so readers keep getting Uint8Array bytes. */ +function fromStoredFileData(data: FileData): FileData { + if (!isBase64Encoded(data)) { + return data; + } + return { + content: new Uint8Array(Buffer.from(data.content, "base64")), + mimeType: data.mimeType, + created_at: data.created_at, + modified_at: data.modified_at, + }; +} + +function fileSize(data: FileData): number { + if (isFileDataV1(data)) { + return data.content.join("\n").length; + } + if (typeof data.content !== "string") { + return data.content.byteLength; + } + return data.encoding === "base64" + ? Buffer.byteLength(data.content, "base64") + : data.content.length; +} + +/** Strict UTF-8 decode; undefined when the bytes are not valid UTF-8. */ +function decodeUtf8(bytes: Uint8Array): string | undefined { + try { + return new TextDecoder("utf-8", { fatal: true }).decode(bytes); + } catch { + return undefined; + } +} + /** * Backend that stores files in agent state (ephemeral). * @@ -189,15 +250,10 @@ export class StateBackend implements BackendProtocolV2 { } // This is a file directly in the current directory - const size = isFileDataV1(fd) - ? fd.content.join("\n").length - : isFileDataBinary(fd) - ? fd.content.byteLength - : fd.content.length; infos.push({ path: k, is_dir: false, - size: size, + size: fileSize(fd), modified_at: fd.modified_at, }); } @@ -235,7 +291,10 @@ export class StateBackend implements BackendProtocolV2 { return { error: `File '${filePath}' not found` }; } - const fileDataV2 = migrateToFileDataV2(fileData, filePath); + const fileDataV2 = migrateToFileDataV2( + fromStoredFileData(fileData), + filePath, + ); // ignore pagination for binary data, return full content if (!isTextMimeType(fileDataV2.mimeType)) { @@ -288,7 +347,7 @@ export class StateBackend implements BackendProtocolV2 { if (!fileData) { return { error: `File '${filePath}' not found` }; } - return { data: fileData }; + return { data: fromStoredFileData(fileData) }; } /** @@ -297,13 +356,16 @@ export class StateBackend implements BackendProtocolV2 { */ write(filePath: string, content: string): WriteResult { const files = this.files; - const existing = files[filePath]; - - const newFileData = createWriteFileData( - filePath, - content, - this.fileFormat, - existing, + const stored = files[filePath]; + // A text path holding a non-UTF-8 upload is typed application/octet-stream; + // text written over it must read back as the path's own type. + const existing = + stored && isBase64Encoded(stored) + ? { ...stored, mimeType: getMimeType(filePath) } + : stored; + + const newFileData = toStoredFileData( + createWriteFileData(filePath, content, this.fileFormat, existing), ); const update = { [filePath]: newFileData }; @@ -365,7 +427,7 @@ export class StateBackend implements BackendProtocolV2 { return { error: `Error: File '${filePath}' not found` }; } - const content = fileDataToString(fileData); + const content = fileDataToString(fromStoredFileData(fileData)); const result = performStringReplacement( content, oldString, @@ -423,17 +485,10 @@ export class StateBackend implements BackendProtocolV2 { const infos: FileInfo[] = []; for (const p of paths) { const fd = files[p]; - const size = fd - ? isFileDataV1(fd) - ? fd.content.join("\n").length - : isFileDataBinary(fd) - ? fd.content.byteLength - : fd.content.length - : 0; infos.push({ path: p, is_dir: false, - size: size, + size: fd ? fileSize(fd) : 0, modified_at: fd?.modified_at || "", }); } @@ -457,20 +512,9 @@ export class StateBackend implements BackendProtocolV2 { for (const [path, content] of files) { try { - const mimeType = getMimeType(path); - - if (this.fileFormat === "v2" && !isTextMimeType(mimeType)) { - updates[path] = createFileData(content, undefined, "v2", mimeType); - } else { - const contentStr = new TextDecoder().decode(content); - updates[path] = createFileData( - contentStr, - undefined, - this.fileFormat, - mimeType, - ); - } - + updates[path] = toStoredFileData( + this.createUploadFileData(path, content), + ); responses.push({ path, error: null }); } catch { responses.push({ path, error: "invalid_path" }); @@ -495,6 +539,28 @@ export class StateBackend implements BackendProtocolV2 { return result; } + /** + * Build FileData for an uploaded file. + * + * In v2, bytes at a binary MIME type stay binary, and bytes at a text MIME + * type that are not valid UTF-8 are kept as application/octet-stream rather + * than lossily decoded. v1 cannot hold binary, so it always decodes as text. + */ + private createUploadFileData(path: string, content: Uint8Array): FileData { + const mimeType = getMimeType(path); + if (this.fileFormat === "v1") { + const text = new TextDecoder().decode(content); + return createFileData(text, undefined, "v1", mimeType); + } + if (!isTextMimeType(mimeType)) { + return createFileData(content, undefined, "v2", mimeType); + } + const text = decodeUtf8(content); + return text === undefined + ? createFileData(content, undefined, "v2", "application/octet-stream") + : createFileData(text, undefined, "v2", mimeType); + } + /** * Download multiple files. * @@ -512,7 +578,10 @@ export class StateBackend implements BackendProtocolV2 { continue; } - const fileDataV2 = migrateToFileDataV2(fileData, path); + const fileDataV2 = migrateToFileDataV2( + fromStoredFileData(fileData), + path, + ); if (typeof fileDataV2.content === "string") { const content = new TextEncoder().encode(fileDataV2.content); diff --git a/libs/deepagents/src/middleware/fs.ts b/libs/deepagents/src/middleware/fs.ts index ce039e39e..40c677025 100644 --- a/libs/deepagents/src/middleware/fs.ts +++ b/libs/deepagents/src/middleware/fs.ts @@ -593,6 +593,7 @@ export const FileDataV1Schema = z.object({ export const FileDataV2Schema = z.object({ content: z.union([z.string(), z.instanceof(Uint8Array)]), mimeType: z.string(), + encoding: z.enum(["utf-8", "base64"]).optional(), created_at: z.string(), modified_at: z.string(), });