The Open Framework for Building Agents
fix(eve): degrade sandbox refs when the session sandbox cannot be resumed (#4836)
roboeve[bot]bc4edd9e07e6
diff --git a/.changeset/hydrate-unavailable-sandbox.md b/.changeset/hydrate-unavailable-sandbox.mdnew file mode 100644index 000000000..50d2001b6--- /dev/null+++ b/.changeset/hydrate-unavailable-sandbox.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Attachments no longer fail a step when the session's sandbox cannot be resumed, for example when a follow-up lands on another replica. Earlier attachments and tool-result files in history reach the model as a "FileNotFound" note, and new inbound attachments and tool-returned files become a "could not be stored" note. Tools that use the sandbox still report the resume error.diff --git a/packages/eve/src/harness/attachment-staging.integration.test.ts b/packages/eve/src/harness/attachment-staging.integration.test.tsindex f59972fa7..85282e4a5 100644--- a/packages/eve/src/harness/attachment-staging.integration.test.ts+++ b/packages/eve/src/harness/attachment-staging.integration.test.ts@@ -1102,8 +1102,7 @@ describe("hydrateSandboxAttachments (integration)", () => {);});- // #4833: hydration rethrows the sandbox resume error and fails the model call.- it.fails("degrades tool-result refs to text when the session sandbox cannot be resumed (#4833)", async () => {+ it("degrades tool-result refs to text when the session sandbox cannot be resumed (#4833)", async () => {const logs = captureLogRecords();const runtime = await createTestRuntime();const staged = await runtime.runAsSession(@@ -1162,7 +1161,12 @@ describe("hydrateSandboxAttachments (integration)", () => {},],});- expect(logs.records).toContainEqual(expect.objectContaining({ level: "warn" }));+ expect(logs.records).toContainEqual(+ expect.objectContaining({+ level: "warn",+ message: "session sandbox unavailable, degrading attachments to text",+ }),+ );});it("does not inline a staged attachment that sandbox code overwrote (#4284)", async () => {diff --git a/packages/eve/src/harness/attachment-staging.test.ts b/packages/eve/src/harness/attachment-staging.test.tsindex 4f0ff4aae..ad24e08ff 100644--- a/packages/eve/src/harness/attachment-staging.test.ts+++ b/packages/eve/src/harness/attachment-staging.test.ts@@ -2,13 +2,16 @@ import type { FilePart, ModelMessage, UserContent } from "ai";import { describe, expect, it } from "vitest";import type { ChannelAdapterContext } from "#channel/adapter.js";-import { ContextContainer } from "#context/container.js";+import { ContextContainer, contextStorage } from "#context/container.js";+import { SandboxKey } from "#context/keys.js";import { decodeSandboxRef, isSandboxRefUrl } from "#internal/attachments/sandbox-refs.js";import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";import {ATTACHMENTS_ROOT,moveToolResultFilesToUserMessages,stageAttachmentsForAdapter,+ stageAttachmentsToSandbox,+ stageToolResultMedia,} from "#harness/attachment-staging.js";const UTF8 = new TextEncoder();@@ -347,6 +350,78 @@ describe("stageAttachmentsForAdapter", () => {});});+function unresumableSandboxContext(): ContextContainer {+ const ctx = new ContextContainer();+ ctx.set(SandboxKey, {+ captureState: async () => ({ session: null }),+ get: async () => {+ throw new Error('microsandbox session "ses_1" is no longer available to resume.');+ },+ stop: async () => {},+ });+ return ctx;+}++describe("stageAttachmentsToSandbox", () => {+ it("replaces an inbound file with a note when the sandbox cannot be resumed", async () => {+ const staged = await contextStorage.run(unresumableSandboxContext(), () =>+ stageAttachmentsToSandbox([+ { text: "see attached", type: "text" },+ {+ data: UTF8.encode("hello"),+ filename: "notes.txt",+ mediaType: "text/plain",+ type: "file",+ },+ ]),+ );++ expect(staged).toEqual([+ { text: "see attached", type: "text" },+ { text: "Attachment notes.txt could not be stored: no sandbox is available.", type: "text" },+ ]);+ });+});++describe("stageToolResultMedia", () => {+ // #4839: a throw here escapes the step after its model call and tools ran,+ // so the step retries and replays them.+ it("replaces a returned file with a note when the sandbox cannot be resumed", async () => {+ const ctx = unresumableSandboxContext();+ const toolResult = (value: unknown) =>+ ({+ content: [+ {+ output: { type: "content", value },+ toolCallId: "call-1",+ toolName: "inspect",+ type: "tool-result",+ },+ ],+ role: "tool",+ }) as ModelMessage;++ const staged = await contextStorage.run(ctx, () =>+ stageToolResultMedia([+ toolResult([+ {+ data: { data: "iVBORw0KGgo=", type: "data" },+ filename: "chart.png",+ mediaType: "image/png",+ type: "file",+ },+ ]),+ ]),+ );++ expect(staged).toEqual([+ toolResult([+ { text: "Returned file chart.png (image/png) could not be stored.", type: "text" },+ ]),+ ]);+ });+});+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 d6c2906ad..a66f49c37 100644--- a/packages/eve/src/harness/attachment-staging.ts+++ b/packages/eve/src/harness/attachment-staging.ts@@ -30,6 +30,7 @@ import {type SandboxRef,} from "#internal/attachments/sandbox-refs.js";import type { SandboxSession } from "#public/definitions/sandbox.js";+import type { SandboxAccess } from "#sandbox/state.js";/*** Sandbox directory where eve stages message attachments and tool-result@@ -109,7 +110,7 @@ export async function stageAttachmentsToSandbox(}const container = loadContext();- const sandbox = (await container.get(SandboxKey)?.get()) ?? null;+ const sandbox = await activeSandbox(container.get(SandboxKey));if (sandbox === null) {return message.map((part) =>part.type === "file" &&@@ -151,7 +152,7 @@ export async function stageToolResultMedia<T extends ModelMessage>(if (!messages.some(hasInlineToolResultFile)) {return [...messages];}- const sandbox = (await contextStorage.getStore()?.get(SandboxKey)?.get()) ?? null;+ const sandbox = await activeSandbox(contextStorage.getStore()?.get(SandboxKey));return Promise.all(messages.map(async (message) => {if (message.role !== "tool" || !hasInlineToolResultFile(message)) {@@ -195,13 +196,7 @@ export async function hydrateSandboxAttachments();}- const sandbox = await sandboxAccess.get();- if (sandbox === null) {- throw new Error(- "Cannot hydrate sandbox-ref FilePart: SandboxKey is bound but no active sandbox session is available.",- );- }-+ const sandbox = await activeSandbox(sandboxAccess);return Promise.all(messages.map(async (message) => {if (!messageContainsSandboxRef(message)) {@@ -213,6 +208,22 @@ export async function hydrateSandboxAttachments();}+/**+ * 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+ * expired provider sandbox). Attachments then degrade to notes and labels so+ * the step survives; tools still see the resume error through `get()`.+ */+async function activeSandbox(access: SandboxAccess | undefined): Promise<SandboxSession | null> {+ if (access === undefined) return null;+ try {+ return await access.get();+ } catch (error) {+ log.warn("session sandbox unavailable, degrading attachments to text", { error });+ return null;+ }+}+/*** History written before eve resolved every attachment can still hold a link* or an `eve-url:` marker that a provider would try to fetch on every call.@@ -339,7 +350,10 @@ function isSandboxRefFilePart(part: unknown): part is FilePart {);}-async function hydrateMessageContent(content: unknown, sandbox: SandboxSession): Promise<unknown> {+async function hydrateMessageContent(+ content: unknown,+ sandbox: SandboxSession | null,+): Promise<unknown> {if (!Array.isArray(content)) {return content;}@@ -368,7 +382,7 @@ async function hydrateMessageContent(content: unknown, sandbox: SandboxSession):async function hydrateToolOutput(output: ToolResultOutput,- sandbox: SandboxSession,+ sandbox: SandboxSession | null,): Promise<ToolResultOutput> {if (output.type !== "content" || !output.value.some(isToolOutputRefFile)) {return output;@@ -392,8 +406,9 @@ async function hydrateToolOutput(async function readSandboxRefBytes(ref: SandboxRef,- sandbox: SandboxSession,+ sandbox: SandboxSession | null,): Promise<Uint8Array | null> {+ if (sandbox === null) return null;const bytes = await sandbox.readBinaryFile({ path: ref.path });if (bytes === null) {// #325: sandbox snapshots can change during a session lifecycle