The Open Framework for Building Agents
fix(eve): start a fresh sandbox when a session's sandbox is gone (#5117)
roboeve[bot]39a8b4ca4c38
diff --git a/.changeset/fresh-sandbox-when-gone.md b/.changeset/fresh-sandbox-when-gone.mdnew file mode 100644index 000000000..393443759--- /dev/null+++ b/.changeset/fresh-sandbox-when-gone.md@@ -0,0 +1,5 @@+---+"eve": patch+---++A session whose sandbox is gone (for example after a microsandbox daemon restart, a removed Docker container, a deleted Vercel Sandbox, or a deleted just-bash session directory) now starts a fresh sandbox on its next `ctx.getSandbox()`. Previously every sandbox call in that session failed with the same resume error until the session ended. Thanks @bradhallett for reporting this in #5113 and @moinulmoin for the just-bash case in #4440.diff --git a/docs/sandbox/index.mdx b/docs/sandbox/index.mdxindex e88fd4acd..b4fcfd23c 100644--- a/docs/sandbox/index.mdx+++ b/docs/sandbox/index.mdx@@ -238,7 +238,7 @@ export const AcmeSandbox = defineSandboxProvider<Provider handles implement `onSandboxStop()`, `onRuntimeShutdown()`, and `onSandboxDelete()`. These handle-level methods cover authored stop or delete calls and process shutdown; `onSessionEnd()` is the single provider hook for durable terminal session cleanup. eve does not delete a sandbox whose initialization failed: the next access runs the selector against it again, and session end removes it.-Open options belong to `start()` and are not serialized or passed to `resume()`. A provider must put any immutable option-derived data needed for reconnection in its session state. With the current immutable-state contract, `resume()` reconnects existing native state and fails if it is gone rather than recreating callback side effects. A custom provider may define start-only callback fields, but built-in providers initialize the sandbox in `defineSandbox()` after `open()`.+Open options belong to `start()` and are not serialized or passed to `resume()`. A provider must put any immutable option-derived data needed for reconnection in its session state. With the current immutable-state contract, `resume()` reconnects existing native state and fails if it is gone rather than recreating callback side effects. When a built-in provider reports that the native sandbox is gone, eve clears the session's provider state and reruns the selector. A custom provider may define start-only callback fields, but built-in providers initialize the sandbox in `defineSandbox()` after `open()`.Preparation discovers authored files through `ctx.files`; core keeps project layout and artifact storage keys private. Keep provider SDK values behind the provider. `environment.open()` preserves the provider's sandbox capability type, while the heterogeneous runtime registry erases it to eve's common session surface.@@ -254,7 +254,7 @@ Preparation discovers authored files through `ctx.files`; core keeps project lay## Lifecycle-Session-owned sandboxes persist across turns and deployments while their provider state remains available. `sandbox.stop()` stops compute without deleting persisted state; a later access resumes that state directly. `sandbox.delete()` deletes the sandbox and clears provider state, so the next `ctx.getSandbox()` reruns the selector, and the provider starts a fresh sandbox under the same session key from the current environment. When the durable session reaches a terminal outcome, eve calls the provider's `onSessionEnd()` hook to delete what remains under the session's key.+Session-owned sandboxes persist across turns and deployments while their provider state remains available. `sandbox.stop()` stops compute without deleting persisted state; a later access resumes that state directly. `sandbox.delete()` deletes the sandbox and clears provider state, so the next `ctx.getSandbox()` reruns the selector, and the provider starts a fresh sandbox under the same session key from the current environment. If the native sandbox is gone when a session resumes, for example after a local daemon restart, a removed container, or a deleted just-bash session directory, eve does the same: the session continues in a fresh sandbox, without the lost sandbox's files. When the durable session reaches a terminal outcome, eve calls the provider's `onSessionEnd()` hook to delete what remains under the session's key.Before that cleanup, session end ends the session's task runs, and each run resets the subagent sessions it opened. eve does not wait for those subagents to stop. A subagent step that is still running at that moment can open the sandbox again after cleanup, and eve does not remove a sandbox created that late.diff --git a/docs/sandbox/vercel.mdx b/docs/sandbox/vercel.mdxindex 48906dc1d..8197c098c 100644--- a/docs/sandbox/vercel.mdx+++ b/docs/sandbox/vercel.mdx@@ -156,7 +156,7 @@ Vercel allows up to four non-overlapping, absolute Drive mount paths per sandboxConfigure project credentials and custom fetch behavior on the environment, not in `open()`, because resume does not reconstruct start-only options.-Initialize the returned sandbox directly in `defineSandbox()`. If initialization fails, eve keeps the sandbox and runs the selector against it again on the next access, so make initialization safe to repeat; session end deletes the sandbox. After initialization succeeds, the provider persists only immutable JSON-compatible state. If the named Vercel Sandbox later disappears, resume fails rather than recreating initialization side effects.+Initialize the returned sandbox directly in `defineSandbox()`. If initialization fails, eve keeps the sandbox and runs the selector against it again on the next access, so make initialization safe to repeat; session end deletes the sandbox. After initialization succeeds, the provider persists only immutable JSON-compatible state. If the named Vercel Sandbox later disappears, resume does not recreate it; eve reruns the selector to start a fresh sandbox instead.eve owns the persistent sandbox identity and prepared snapshot source.diff --git a/packages/eve/src/execution/sandbox/bindings/docker.integration.test.ts b/packages/eve/src/execution/sandbox/bindings/docker.integration.test.tsindex d2c661425..de50b619a 100644--- a/packages/eve/src/execution/sandbox/bindings/docker.integration.test.ts+++ b/packages/eve/src/execution/sandbox/bindings/docker.integration.test.ts@@ -24,6 +24,7 @@ import type {DockerSandboxEnvironmentOptions,DockerSandboxRuntimeOptions,} from "#public/sandbox/docker-sandbox.js";+import { SandboxSessionGoneError } from "#shared/sandbox-session-gone-error.js";import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";import { createSandboxProviderHarness } from "#internal/testing/sandbox-provider-harness.js";import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";@@ -520,12 +521,31 @@ describe("Docker provider create", () => {expect(findCall(calls, (args) => args[0] === "run")).toBeUndefined();});+ it("reports a session as gone only when Docker has no such container", async () => {+ const appRoot = await createScratchDirectory("eve-docker-sandbox-");+ let inspect: FakeResponse = { exitCode: 0, stdout: "true\n" };+ const { cli } = createFakeDockerCli((args) => (isContainerInspect(args) ? inspect : undefined));+ const engine = createEngine({ cli });+ const { state } = await engine.start({ appRoot, sandboxName: SESSION_KEY });+ const resume = () => engine.openSession({ existing: state, appRoot, sandboxName: SESSION_KEY });++ inspect = { exitCode: 1, stderr: "Cannot connect to the Docker daemon. Is it running?" };+ const unavailable = resume();+ await expect(unavailable).rejects.toThrow("Cannot connect to the Docker daemon");+ await expect(unavailable).rejects.not.toBeInstanceOf(SandboxSessionGoneError);++ inspect = { exitCode: 1, stderr: "Error: No such container: eve-session" };+ await expect(resume()).rejects.toBeInstanceOf(SandboxSessionGoneError);+ });+it("attaches to the peer container when another process wins the create race", async () => {const appRoot = await createScratchDirectory("eve-docker-sandbox-");let peerCreated = false;const { calls, cli } = createFakeDockerCli((args) => {if (isContainerInspect(args)) {- return peerCreated ? { exitCode: 0, stdout: "true\n" } : { exitCode: 1 };+ return peerCreated+ ? { exitCode: 0, stdout: "true\n" }+ : { exitCode: 1, stderr: "Error: No such container" };}if (args[0] === "run") {peerCreated = true;diff --git a/packages/eve/src/execution/sandbox/bindings/docker.ts b/packages/eve/src/execution/sandbox/bindings/docker.tsindex 51d732802..681ab7f11 100644--- a/packages/eve/src/execution/sandbox/bindings/docker.ts+++ b/packages/eve/src/execution/sandbox/bindings/docker.ts@@ -51,6 +51,7 @@ import {type SandboxProviderSessionContext,} from "#shared/sandbox-provider.js";import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";+import { SandboxSessionGoneError } from "#shared/sandbox-session-gone-error.js";import type {DockerSandboxEnvironmentOptions,DockerSandboxRuntimeOptions,@@ -118,7 +119,13 @@ export function createDockerSandboxProvider("{{.State.Running}}",containerName,]);- return inspect.exitCode === 0 ? inspect.stdout.trim() === "true" : undefined;+ if (inspect.exitCode === 0) return inspect.stdout.trim() === "true";+ if (/no such (?:container|object)/iu.test(inspect.stderr)) return undefined;+ // Any other failure, such as a daemon that stopped after the cached check, must not+ // read as a missing container: resume would discard the session's sandbox.+ daemonCheck = undefined;+ expectDockerSuccess(inspect, `inspect sandbox session container "${containerName}"`);+ return undefined;}async function openDockerSession(@@ -132,7 +139,9 @@ export function createDockerSandboxProvider(let running = await inspectContainerRunning(containerName);if (running === undefined) {if (!createIfMissing) {- throw new Error(`Docker sandbox session container "${containerName}" no longer exists.`);+ throw new SandboxSessionGoneError(+ `Docker sandbox session container "${containerName}" no longer exists.`,+ );}const artifact = requirePreparedDockerArtifact(artifactValue);if (!(await dockerImageExists(cli, artifact.imageReference))) {diff --git a/packages/eve/src/execution/sandbox/bindings/just-bash.ts b/packages/eve/src/execution/sandbox/bindings/just-bash.tsindex d4f6f85db..34635c1c4 100644--- a/packages/eve/src/execution/sandbox/bindings/just-bash.ts+++ b/packages/eve/src/execution/sandbox/bindings/just-bash.ts@@ -38,6 +38,7 @@ import {type SandboxProviderSessionContext,} from "#shared/sandbox-provider.js";import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";+import { SandboxSessionGoneError } from "#shared/sandbox-session-gone-error.js";const JUST_BASH_CACHE_DIRECTORY_NAME = "just-bash";export const JUST_BASH_PROVIDER_NAME = "just-bash";@@ -122,7 +123,7 @@ export function createJustBashSandboxProvider(async resume(context, _artifact, stateValue) {const { rootPath } = requireJustBashSessionState(stateValue);if (!(await pathExists(rootPath))) {- throw new Error(`just-bash session root "${rootPath}" no longer exists.`);+ throw new SandboxSessionGoneError(`just-bash session root "${rootPath}" no longer exists.`);}return await openHandle(context, rootPath, options);},diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.tsindex 9f55c6469..256f72707 100644--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.ts+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.ts@@ -69,6 +69,7 @@ import {type SandboxProviderPrepareContext,} from "#shared/sandbox-provider.js";import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";+import { SandboxSessionGoneError } from "#shared/sandbox-session-gone-error.js";import type { InternalSandboxSession } from "#shared/sandbox-session.js";type LiveMicrosandboxOptions = ResolvedMicrosandboxOptions & MicrosandboxSandboxRuntimeOptions;@@ -297,7 +298,9 @@ async function openMicrosandboxHandle(input: {}if (!input.createIfMissing) {- throw new Error(`microsandbox session "${sessionIdentity}" is no longer available to resume.`);+ throw new SandboxSessionGoneError(+ `microsandbox session "${sessionIdentity}" is no longer available to resume.`,+ );}if (diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-provider-state.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-provider-state.tsindex 46694499b..1f589f665 100644--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-provider-state.ts+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-provider-state.ts@@ -32,8 +32,11 @@ export async function snapshotExists(try {await module.Snapshot.get(snapshotName);return true;- } catch {- return false;+ } catch (error) {+ if (isMicrosandboxNotFoundError(error)) {+ return false;+ }+ throw error;}}diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.test.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.test.tsindex 629d7a965..f6ba75ccd 100644--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.test.ts+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.test.ts@@ -679,7 +679,7 @@ function createMockMicrosandboxModule(Snapshot: {async get(snapshotName: string) {if (!snapshots.has(snapshotName)) {- throw new Error(`snapshot store unavailable for ${snapshotName}`);+ throw new Error(`snapshot not found: ${snapshotName}`);}return {};},diff --git a/packages/eve/src/execution/sandbox/bindings/vercel.ts b/packages/eve/src/execution/sandbox/bindings/vercel.tsindex 633bac131..c9ca3e7cd 100644--- a/packages/eve/src/execution/sandbox/bindings/vercel.ts+++ b/packages/eve/src/execution/sandbox/bindings/vercel.ts@@ -27,6 +27,7 @@ import {type SandboxProviderSessionContext,} from "#shared/sandbox-provider.js";import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";+import { SandboxSessionGoneError } from "#shared/sandbox-session-gone-error.js";import type {VercelSandboxMountOptions,VercelSandboxRuntimeOptions,@@ -265,7 +266,9 @@ export function createVercelSandbox(sandboxName: state.sandboxName,});if (sandbox === null) {- throw new Error(`Vercel sandbox session "${state.sandboxName}" no longer exists.`);+ throw new SandboxSessionGoneError(+ `Vercel sandbox session "${state.sandboxName}" no longer exists.`,+ );}await ensureVercelSandboxBaseRuntime(sandbox);return createHandle({ createOptions, loadDeleteSandboxModule, sandbox });diff --git a/packages/eve/src/execution/sandbox/ensure.test.ts b/packages/eve/src/execution/sandbox/ensure.test.tsindex d4feaa2ae..8b109d50f 100644--- a/packages/eve/src/execution/sandbox/ensure.test.ts+++ b/packages/eve/src/execution/sandbox/ensure.test.ts@@ -11,6 +11,7 @@ import {defineSandboxProvider,type SandboxProviderSessionContext,} from "#shared/sandbox-provider.js";+import { SandboxSessionGoneError } from "#shared/sandbox-session-gone-error.js";import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";import { loadSandboxPreparedArtifact } from "#runtime/sandbox/prepared-artifacts.js";@@ -199,6 +200,42 @@ describe("ensureSandboxAccess", () => {expect(value.create).toHaveBeenCalledOnce();});+ // https://github.com/vercel/eve/issues/5113+ it("starts a fresh sandbox when the persisted one is gone", async () => {+ const setup = vi.fn();+ const value = fixture(setup);+ value.create.mockRejectedValueOnce(+ new SandboxSessionGoneError('microsandbox session "ses_1" is no longer available to resume.'),+ );+ const { access, sandbox } = await open(value.registry, "session-1", {+ session: { providerName: "test", state: null, stateProtocolVersion: 1 },+ });+ expect(sandbox).toBeTruthy();+ expect(setup).toHaveBeenCalledOnce();+ expect(value.start).toHaveBeenCalledOnce();+ await expect(access.captureState()).resolves.toEqual({+ session: { providerName: "test", state: { key: "session-1" }, stateProtocolVersion: 1 },+ });+ });++ it("keeps the persisted sandbox when resume fails for another reason", async () => {+ const value = fixture();+ value.create.mockRejectedValueOnce(new Error("daemon unavailable"));+ const state = {+ session: { providerName: "test", state: { key: "old" }, stateProtocolVersion: 1 },+ };+ const access = await ensureSandboxAccess({+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),+ nodeId: "__root__",+ registry: value.registry,+ sessionId: "session-1",+ state,+ });+ await expect(access.get()).rejects.toThrow("daemon unavailable");+ expect(value.start).not.toHaveBeenCalled();+ await expect(access.captureState()).resolves.toEqual(state);+ });+it("starts a fresh sandbox for a session imported from eve 0.54", async () => {const setup = vi.fn();const value = fixture(setup);diff --git a/packages/eve/src/execution/sandbox/ensure.ts b/packages/eve/src/execution/sandbox/ensure.tsindex 4170f4459..f5318419f 100644--- a/packages/eve/src/execution/sandbox/ensure.ts+++ b/packages/eve/src/execution/sandbox/ensure.ts@@ -1,5 +1,6 @@import { ensureDevelopmentSandboxesPrepared } from "#execution/sandbox/development-lazy-prewarm.js";import { isEveDevEnvironment } from "#internal/application/dev-environment.js";+import { createLogger } from "#internal/logging.js";import { contextStorage } from "#context/container.js";import {buildCallbackContext,@@ -35,6 +36,7 @@ import {type SandboxProviderSessionContext,} from "#shared/sandbox-provider.js";import type { RuntimeSandboxSession } from "#shared/sandbox-session.js";+import { SandboxSessionGoneError } from "#shared/sandbox-session-gone-error.js";import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";interface EnsureSandboxAccessInput {@@ -77,6 +79,8 @@ interface OpenedSandbox {// the selector again.const pendingSandboxStarts = new Map<string, Promise<SandboxSessionState | null>>();+const log = createLogger("execution.sandbox");+export async function ensureSandboxAccess(input: EnsureSandboxAccessInput,): Promise<EnsuredSandboxAccess> {@@ -242,7 +246,17 @@ export async function ensureSandboxAccess(const context = providerContext("sandbox-initialization");if (persisted !== null) {- return await resumePersisted(context);+ try {+ return await resumePersisted(context);+ } catch (error) {+ if (!(error instanceof SandboxSessionGoneError)) throw error;+ log.warn("session sandbox is gone, starting a fresh one", {+ error,+ providerName: persisted.providerName,+ sessionId: input.sessionId,+ });+ persisted = null;+ }}// Apps hosted in one process can reuse a node id and a tool session id.diff --git a/packages/eve/src/shared/sandbox-session-gone-error.ts b/packages/eve/src/shared/sandbox-session-gone-error.tsnew file mode 100644index 000000000..e972b09b0--- /dev/null+++ b/packages/eve/src/shared/sandbox-session-gone-error.ts@@ -0,0 +1,11 @@+/**+ * Thrown by a provider's `resume()` when the session's native sandbox no+ * longer exists. Core then clears the session's sandbox state and starts a+ * fresh sandbox, as it would after `sandbox.delete()`.+ */+export class SandboxSessionGoneError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "SandboxSessionGoneError";+ }+}diff --git a/research/sandbox-environments-open.md b/research/sandbox-environments-open.mdindex 26b6ebd63..1feeea582 100644--- a/research/sandbox-environments-open.md+++ b/research/sandbox-environments-open.md@@ -1,7 +1,7 @@---issue: TBDstatus: draft-last_updated: "2026-09-16"+last_updated: "2026-10-21"---# Sandbox environments and provider sessions@@ -113,7 +113,7 @@ Core evaluates `defineSandbox()` and calls `start()` when no serialized provider`start()` receives provider-owned open options and the exact artifact. `resume()` receives only the current session context, the target deployment's exact artifact, and persisted provider state. Open options and callbacks are never serialized or reconstructed by core. Credentials, clients, fetch implementations, and signals needed for lookup belong to environment/provider configuration rather than start-only open options. A provider must include any immutable option-derived data needed for reconnection in its own JSON-compatible state.-Provider state is immutable after `start()` in this contract. `resume()` reconnects or restarts persisted native state but does not recreate missing native compute from unavailable callbacks. If native state is gone, resume fails. Deletion clears provider state; the next access evaluates the selector and starts again.+Provider state is immutable after `start()` in this contract. `resume()` reconnects or restarts persisted native state but does not recreate missing native compute from unavailable callbacks. If native state is gone, resume reports it and core treats it like deletion: it clears provider state and evaluates the selector to start again.During deployment handoff, the target provider validates state against its current implementation and artifact. Incompatibility rejects activation, leaving the existing owner on its current deployment. Core does not persist old artifacts or migrate provider state.