The Open Framework for Building Agents
fix: stop resuming the sandbox to hydrate attachments that need no bytes (#5289)
Andrew Barba6f551a78c665
diff --git a/.changeset/lazy-attachment-hydration.md b/.changeset/lazy-attachment-hydration.mdnew file mode 100644index 000000000..6e0b60704--- /dev/null+++ b/.changeset/lazy-attachment-hydration.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Model calls no longer resume the session sandbox just to render attachment labels. Images and PDFs that eve staged or already read for the session are served from a bounded in-memory cache, so the sandbox is resumed only when eve needs bytes it doesn't already hold.diff --git a/docs/sandbox/index.mdx b/docs/sandbox/index.mdxindex c5d008ce0..dd731a87c 100644--- a/docs/sandbox/index.mdx+++ b/docs/sandbox/index.mdx@@ -138,7 +138,7 @@ eve writes byte-backed files that reach the agent into the sandbox under `.eve/aFiles that tools return by URL with `toolOutputPart.fileUrl` are not staged: the model provider reads the URL directly. See [Send a file by URL](/docs/tools#send-a-file-by-url).-Before every model call, eve reads the referenced files back from the sandbox. Every file, whether attached to a message or returned by a tool, reaches the model with a label that names its sandbox path, such as `Attached file /workspace/.eve/attachments/<hash>/report.csv (text/csv)`. The agent can open that path with `read_file` or `bash`. The file's bytes follow its label only when every major provider reads the format natively:+Every file, whether attached to a message or returned by a tool, reaches the model on every call with a label that names its sandbox path, such as `Attached file /workspace/.eve/attachments/<hash>/report.csv (text/csv)`. The agent can open that path with `read_file` or `bash`. The file's bytes follow its label only when every major provider reads the format natively:- A PNG, JPEG, GIF, or WebP image up to 3 MiB and at most 8000 pixels per side.- A PDF up to 20 MiB.@@ -147,7 +147,7 @@ Other files, such as CSV, HEIC, audio, and video, reach the model as the label aTo let the agent answer voice notes and other audio, add a tool that transcribes the staged file. See [Voice notes](/docs/patterns/voice-notes).-If a referenced file is missing, or its bytes no longer match what eve staged because something in the sandbox overwrote it, the model receives a `FileNotFound` note in its place.+eve keeps the bytes of recent images and PDFs it staged or read for a session in memory, so a model call resumes the sandbox only when it needs bytes that eve doesn't already hold. If a file read back from the sandbox is missing, or its bytes no longer match what eve staged because something in the sandbox overwrote it, the model receives a `FileNotFound` note in its place.A file that eve can't stage never enters session history. When a channel's `fetchFile` fails, or a file part's `data` is not bytes, base64, a `data:` URL, or a URL, the model receives a note that names the file instead.diff --git a/packages/eve/src/harness/attachment-staging.test.ts b/packages/eve/src/harness/attachment-staging.test.tsindex 173aad403..de542cd3c 100644--- a/packages/eve/src/harness/attachment-staging.test.ts+++ b/packages/eve/src/harness/attachment-staging.test.ts@@ -1,12 +1,14 @@import type { FilePart, ModelMessage, UserContent } from "ai";-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";import type { ChannelAdapterContext } from "#channel/adapter.js";import { ContextContainer, contextStorage } from "#context/container.js";-import { SandboxKey } from "#context/keys.js";+import { SandboxKey, SessionIdKey } from "#context/keys.js";import { decodeSandboxRef, isSandboxRefUrl } from "#internal/attachments/sandbox-refs.js";-import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";+import { pngBytes } from "#internal/testing/media-fixtures.js";+import { type MockSandbox, mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";import {+ hydrateSandboxAttachments,moveToolResultFilesToUserMessages,stageAttachmentsForAdapter,stageAttachmentsToSandbox,@@ -419,6 +421,132 @@ describe("stageToolResultMedia", () => {});});+// Each test hydrates under its own session id, so bytes cached by one test+// never satisfy another.+describe("hydrateSandboxAttachments", () => {+ function sessionContext(sessionId: string, sandbox: MockSandbox): ContextContainer {+ const ctx = new ContextContainer();+ ctx.set(SessionIdKey, sessionId);+ ctx.set(SandboxKey, sandbox.access);+ return ctx;+ }++ function hydrate(ctx: ContextContainer, content: UserContent): Promise<ModelMessage[]> {+ return contextStorage.run(ctx, () => hydrateSandboxAttachments([{ content, role: "user" }]));+ }++ // Staged outside any session, as by another process: nothing is cached.+ async function stageElsewhere(sandbox: MockSandbox, file: FilePart): Promise<FilePart> {+ const [staged] = (await stageAttachmentsForAdapter(+ [file],+ sandbox.session,+ STUB_ADAPTER_CTX,+ )) as FilePart[];+ return staged!;+ }++ async function stageInSession(ctx: ContextContainer, file: FilePart): Promise<FilePart> {+ const [staged] = (await contextStorage.run(ctx, () =>+ stageAttachmentsToSandbox([file]),+ )) as FilePart[];+ return staged!;+ }++ function png(filename: string, bytes: Buffer): FilePart {+ return { data: bytes, filename, mediaType: "image/png", type: "file" };+ }++ function fileNotFound(part: FilePart) {+ return {+ text: `FileNotFound: Current snapshot may be newer and does not contain ${part.filename}.`,+ type: "text",+ };+ }++ it("renders label-only refs without resuming the sandbox", async () => {+ const sandbox = mockSandbox();+ const csv = await stageElsewhere(sandbox, {+ data: Buffer.from("id,name\n1,alpha\n"),+ filename: "report.csv",+ mediaType: "text/csv",+ type: "file",+ });+ const get = vi.spyOn(sandbox.access, "get");++ const hydrated = await hydrate(sessionContext("ses_label_only", sandbox), [csv]);++ expect(hydrated[0]?.content).toEqual([+ { text: `Attached file ${csv.filename} (text/csv)`, type: "text" },+ ]);+ expect(get).not.toHaveBeenCalled();+ });++ it("hydrates an image staged in this session without resuming the sandbox", async () => {+ const sandbox = mockSandbox();+ const ctx = sessionContext("ses_staged_here", sandbox);+ const bytes = pngBytes(32, 32, 64);+ const image = await stageInSession(ctx, png("logo.png", bytes));+ const get = vi.spyOn(sandbox.access, "get");++ const hydrated = await hydrate(ctx, [image]);++ expect(hydrated[0]?.content).toEqual([+ { text: `Attached file ${image.filename} (image/png)`, type: "text" },+ { ...image, data: bytes, mediaType: "image/png" },+ ]);+ expect(get).not.toHaveBeenCalled();+ });++ it("does not serve bytes cached for one session to another", async () => {+ const image = await stageInSession(+ sessionContext("ses_owner", mockSandbox()),+ png("private.png", pngBytes(32, 32, 64)),+ );++ // Bob's sandbox never held the file, so only a cache hit could inline it.+ const hydrated = await hydrate(sessionContext("ses_bob", mockSandbox()), [image]);++ expect(hydrated[0]?.content).toEqual([fileNotFound(image)]);+ });++ it("reads uncached refs through one sandbox resume and serves later calls from memory", async () => {+ const sandbox = mockSandbox();+ const firstBytes = pngBytes(32, 32, 64);+ const secondBytes = pngBytes(16, 16, 64);+ const first = await stageElsewhere(sandbox, png("first.png", firstBytes));+ const second = await stageElsewhere(sandbox, png("second.png", secondBytes));+ const ctx = sessionContext("ses_cold_process", sandbox);+ const get = vi.spyOn(sandbox.access, "get");++ const calls = [await hydrate(ctx, [first, second]), await hydrate(ctx, [first, second])];++ for (const hydrated of calls) {+ expect(hydrated[0]?.content).toEqual([+ { text: `Attached file ${first.filename} (image/png)`, type: "text" },+ { ...first, data: firstBytes, mediaType: "image/png" },+ { text: `Attached file ${second.filename} (image/png)`, type: "text" },+ { ...second, data: secondBytes, mediaType: "image/png" },+ ]);+ }+ expect(get).toHaveBeenCalledTimes(1);+ });++ it("never caches bytes that changed since staging", async () => {+ const sandbox = mockSandbox();+ const bytes = pngBytes(32, 32, 64);+ const image = await stageElsewhere(sandbox, png("logo.png", bytes));+ // Same size, different bytes: only the content address can tell them apart.+ await sandbox.session.writeBinaryFile({+ content: Buffer.alloc(bytes.byteLength, 0x41),+ path: image.filename!,+ });+ const ctx = sessionContext("ses_overwritten", sandbox);++ expect((await hydrate(ctx, [image]))[0]?.content).toEqual([fileNotFound(image)]);+ expect((await hydrate(ctx, [image]))[0]?.content).toEqual([fileNotFound(image)]);+ });+});+describe("moveToolResultFilesToUserMessages", () => {it("moves tool-result files into a user message after the tool results", () => {const file = {diff --git a/packages/eve/src/harness/attachment-staging.ts b/packages/eve/src/harness/attachment-staging.tsindex 7b0a73897..748e71c60 100644--- a/packages/eve/src/harness/attachment-staging.ts+++ b/packages/eve/src/harness/attachment-staging.ts@@ -7,7 +7,7 @@ import type { ChannelAdapterContext, FetchFileResult } from "#channel/adapter.jsimport { getAdapterKind } from "#channel/adapter.js";import { buildSessionHandle } from "#channel/session.js";import { contextStorage, loadContext } from "#context/container.js";-import { SandboxKey } from "#context/keys.js";+import { SandboxKey, SessionIdKey } from "#context/keys.js";import { createFrameworkUserMessage } from "#harness/messages.js";import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";import { isUnresolvedFileData, readFileData } from "#internal/attachments/data.js";@@ -46,6 +46,19 @@ const SHA_PREFIX_LENGTH = 16;const DEFAULT_MEDIA_TYPE = "application/octet-stream";+/**+ * Upper bound on the bytes this process keeps for inline refs, so warm+ * processes hydrate images and PDFs without resuming the sandbox on every+ * model call. Inline files are at most 3 MiB (images) or 20 MiB (PDFs), so+ * 64 MiB holds a typical session's recent attachments without letting one+ * process grow unbounded.+ */+const CACHED_REF_BYTES_LIMIT = 64 * 1024 * 1024;++// Insertion order doubles as LRU order: a hit moves its entry to the end.+const cachedRefBytes = new Map<string, Buffer>();+let cachedRefBytesTotal = 0;+// A staged name keeps or gains the extension its media type implies, so a// nameless file (an MCP image, say) can still be opened by path later.const MEDIA_TYPE_EXTENSIONS: Readonly<Record<string, string>> = {@@ -178,6 +191,9 @@ export async function stageToolResultMedia<T extends ModelMessage>(* decision is pure in the ref, so each message renders identically on every* call and the provider's prompt cache stays valid. The returned messages* must not be written back to session history, which stays ref-only.+ *+ * Resuming a sandbox is slow and can be billed, so it happens only when a+ * ref needs bytes this process does not already hold for the session.*/export async function hydrateSandboxAttachments(input: readonly ModelMessage[],@@ -187,26 +203,81 @@ export async function hydrateSandboxAttachments(return messages;}- const sandboxAccess = loadContext().get(SandboxKey);- if (sandboxAccess === undefined) {- throw new Error(- "Cannot hydrate sandbox-ref FilePart: no SandboxKey is bound on the active eve context. " +- "Hydration must run inside a step scope with the framework sandbox provider installed.",- );- }-- const sandbox = await activeSandbox(sandboxAccess);+ const context = loadContext();+ const read = sandboxRefReader(context.get(SandboxKey), context.get(SessionIdKey));return Promise.all(messages.map(async (message) => {if (!messageContainsSandboxRef(message)) {return message;}- const content = await hydrateMessageContent(message.content, sandbox);+ const content = await hydrateMessageContent(message.content, read);return { ...message, content } as ModelMessage;}),);}+/** Verified bytes for an inline ref, or `null` when they are missing or changed. */+type SandboxRefReader = (ref: SandboxRef) => Promise<Uint8Array | null>;++/**+ * Serves inline refs from the session's cached bytes and opens the sandbox+ * at most once per hydration, on the first miss. Parts hydrate concurrently,+ * so the open is shared as a promise.+ */+function sandboxRefReader(+ access: SandboxAccess | undefined,+ sessionId: string | undefined,+): SandboxRefReader {+ let sandbox: Promise<SandboxSession | null> | undefined;+ return async (ref) => {+ const key = cacheKey(sessionId, ref);+ const cached = key === undefined ? undefined : readCachedRefBytes(key);+ if (cached !== undefined) return cached;+ if (access === undefined) {+ throw new Error(+ `Cannot hydrate attachment ${ref.path}: no SandboxKey is bound on the active eve context. ` ++ "Hydration must run inside a step scope with the framework sandbox provider installed.",+ );+ }+ sandbox ??= activeSandbox(access);+ const bytes = await readSandboxRefBytes(ref, await sandbox);+ if (bytes !== null && key !== undefined) cacheRefBytes(key, bytes);+ return bytes;+ };+}++/**+ * Scoped to the session: a ref in one session's history can never reach bytes+ * eve staged for another, even if a caller crafts one. The path carries the+ * content hash, and the media type is the one eve verified at staging.+ */+function cacheKey(sessionId: string | undefined, ref: SandboxRef): string | undefined {+ if (sessionId === undefined) return undefined;+ return JSON.stringify([sessionId, ref.path, ref.size, ref.mediaType]);+}++function readCachedRefBytes(key: string): Buffer | undefined {+ const bytes = cachedRefBytes.get(key);+ if (bytes !== undefined) {+ cachedRefBytes.delete(key);+ cachedRefBytes.set(key, bytes);+ }+ return bytes;+}++/** Caches bytes eve staged or verified; callers must never pass unverified bytes. */+function cacheRefBytes(key: string, bytes: Uint8Array): void {+ if (bytes.byteLength > CACHED_REF_BYTES_LIMIT || cachedRefBytes.has(key)) return;+ // A copy, so a caller reusing its buffer can't change what later calls send.+ cachedRefBytes.set(key, Buffer.from(bytes));+ cachedRefBytesTotal += bytes.byteLength;+ for (const [oldestKey, oldest] of cachedRefBytes) {+ if (cachedRefBytesTotal <= CACHED_REF_BYTES_LIMIT) break;+ cachedRefBytes.delete(oldestKey);+ cachedRefBytesTotal -= oldest.byteLength;+ }+}+/*** The session's sandbox for attachment staging and hydration, or `null` when* there is none or it can't be resumed (another replica, a restart, an@@ -349,10 +420,7 @@ function isSandboxRefFilePart(part: unknown): part is FilePart {);}-async function hydrateMessageContent(- content: unknown,- sandbox: SandboxSession | null,-): Promise<unknown> {+async function hydrateMessageContent(content: unknown, read: SandboxRefReader): Promise<unknown> {if (!Array.isArray(content)) {return content;}@@ -364,14 +432,14 @@ async function hydrateMessageContent(if (!inlinesSandboxRefAsBytes(ref)) {return [label];}- const bytes = await readSandboxRefBytes(ref, sandbox);+ const bytes = await read(ref);return bytes === null? [renderMissingSandboxRef(ref)]: [label, { ...part, data: bytes, mediaType: ref.mediaType }];}if ((part as { type?: unknown }).type === "tool-result") {const toolResult = part as ToolResultPart;- return [{ ...toolResult, output: await hydrateToolOutput(toolResult.output, sandbox) }];+ return [{ ...toolResult, output: await hydrateToolOutput(toolResult.output, read) }];}return [part];}),@@ -381,7 +449,7 @@ async function hydrateMessageContent(async function hydrateToolOutput(output: ToolResultOutput,- sandbox: SandboxSession | null,+ read: SandboxRefReader,): Promise<ToolResultOutput> {if (output.type !== "content" || !output.value.some(isToolOutputRefFile)) {return output;@@ -392,7 +460,7 @@ async function hydrateToolOutput(const ref = decodeSandboxRef(part.data.url);const label = renderSandboxRefAsTextPart(ref);if (!inlinesSandboxRefAsBytes(ref)) return [label];- const bytes = await readSandboxRefBytes(ref, sandbox);+ const bytes = await read(ref);if (bytes === null) return [renderMissingSandboxRef(ref)];return [label,@@ -590,7 +658,8 @@ async function stageResolvedBytes(/*** Writes content-addressed bytes under {@link ATTACHMENTS_ROOT} and describes- * them as a ref whose media type the bytes confirm.+ * them as a ref whose media type the bytes confirm. Inline bytes are cached+ * for the session so the next model calls need not read them back.*/async function writeSandboxRef(bytes: Buffer,@@ -602,7 +671,10 @@ async function writeSandboxRef(const sha = sha256Prefix(bytes);const authored = `${ATTACHMENTS_ROOT}/${sha}/${safeFilename(filename, sha, mediaType)}`;await sandbox.writeBinaryFile({ content: bytes, path: authored });- return { ...readMediaMetadata(bytes, mediaType), path: sandbox.resolvePath(authored) };+ const ref = { ...readMediaMetadata(bytes, mediaType), path: sandbox.resolvePath(authored) };+ const key = cacheKey(contextStorage.getStore()?.get(SessionIdKey), ref);+ if (key !== undefined && inlinesSandboxRefAsBytes(ref)) cacheRefBytes(key, bytes);+ return ref;}/**