Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): stop all sandboxes on server shutdown (#510)

JJ Kasper6f9364a9eb0f
diff --git a/.changeset/sandbox-server-shutdown-cleanup.md b/.changeset/sandbox-server-shutdown-cleanup.md
new file mode 100644
index 000000000..d3b7afe26
--- /dev/null
+++ b/.changeset/sandbox-server-shutdown-cleanup.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+Sandboxes are now stopped when the eve server shuts down. Self-hosted production servers stop every open sandbox (microsandbox VMs, Docker containers, Vercel sandboxes, just-bash interpreters) on `SIGTERM`/`SIGINT`, matching the cleanup `eve dev` already performs, and sessions reattach from persisted state on the next start. Breaking change for custom sandbox backends: `SandboxBackendHandle` gains a required `shutdown()` and the unused `dispose()` is removed.
diff --git a/docs/sandbox.mdx b/docs/sandbox.mdx
index 239d5d248..544ab702e 100644
--- a/docs/sandbox.mdx
+++ b/docs/sandbox.mdx
@@ -157,7 +157,7 @@ export default defineSandbox({
`justbash()` needs no daemon or VM, but commands run in a simulated bash with a virtual filesystem under `.eve/sandbox-cache/`, with no real binaries (`git`, `node`, package managers) and no network isolation. The `just-bash` package is an optional peer dependency, so `eve dev` installs it into your application automatically when missing (disable with `autoInstall: false`); production processes fail with an actionable install error instead.
-You can also write your own backend. A `SandboxBackend` is an adapter object with a `name`, a `create`, and an optional `prewarm`. It can point at your own container runner, VM pool, internal sandbox service, or another isolation layer, as long as it returns the `SandboxSession` operations eve needs. See the `SandboxBackend*` types on `eve/sandbox`.
+You can also write your own backend. A `SandboxBackend` is an adapter object with a `name`, a `create`, and an optional `prewarm`. It can point at your own container runner, VM pool, internal sandbox service, or another isolation layer, as long as it returns the `SandboxSession` operations eve needs. Handles returned by `create` implement `shutdown()`, which stops the underlying compute at server shutdown. See the `SandboxBackend*` types on `eve/sandbox`.
## Lifecycle
@@ -185,6 +185,8 @@ export default defineSandbox({
Sessions are persistent, and how the underlying runtime idles out depends on the backend. On the Vercel backend, the VM times out after a period of inactivity (default 30 minutes); eve preserves the filesystem and resumes the sandbox on the next message as if nothing happened, even days later. The Docker backend keeps a long-lived container per durable session and persists `/workspace` across turns without that timeout, and the just-bash backend stores its virtual filesystem under `.eve/sandbox-cache/`. In every case, `/workspace` survives between turns for the same session.
+When the eve server stops, no sandbox compute outlives it. `eve dev` stops the sandboxes it started when the dev server closes, and a self-hosted production server stops every open sandbox on shutdown (`SIGTERM`/`SIGINT`). Session state persists across the stop — the next server start reattaches each durable session from its stopped container, VM, or snapshot. Custom `SandboxBackend` adapters participate through the handle's `shutdown()` method: stop the underlying compute, keeping the session reattachable from persisted state where the backend supports it.
+
## Network policy
Egress rules go on the backend factory or in `onSession`'s `use()`. There are three forms:
diff --git a/packages/eve/src/context/providers/sandbox.test.ts b/packages/eve/src/context/providers/sandbox.test.ts
index 9e4642bc0..79c6bbd7e 100644
--- a/packages/eve/src/context/providers/sandbox.test.ts
+++ b/packages/eve/src/context/providers/sandbox.test.ts
@@ -59,7 +59,6 @@ describe("sandboxProvider", () => {
beforeEach(() => {
vi.mocked(ensureSandboxAccess).mockResolvedValue({
captureState: vi.fn().mockResolvedValue({ initialized: false, session: null }),
- dispose: vi.fn(),
get: vi.fn().mockResolvedValue(null),
});
});
diff --git a/packages/eve/src/execution/context.test.ts b/packages/eve/src/execution/context.test.ts
index 12b17d2d0..b664ff1fa 100644
--- a/packages/eve/src/execution/context.test.ts
+++ b/packages/eve/src/execution/context.test.ts
@@ -21,7 +21,6 @@ import type { HarnessSession } from "#harness/types.js";
vi.mock("./sandbox/ensure.js", () => ({
ensureSandboxAccess: vi.fn().mockResolvedValue({
captureState: vi.fn().mockResolvedValue({ initialized: false, session: null }),
- dispose: vi.fn(),
get: vi.fn().mockResolvedValue(null),
}),
}));
diff --git a/packages/eve/src/execution/sandbox/active-handles.test.ts b/packages/eve/src/execution/sandbox/active-handles.test.ts
new file mode 100644
index 000000000..8aca73bb8
--- /dev/null
+++ b/packages/eve/src/execution/sandbox/active-handles.test.ts
@@ -0,0 +1,69 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import {
+ clearActiveSandboxHandlesForTest,
+ countActiveSandboxHandles,
+ shutdownActiveSandboxHandles,
+ trackActiveSandboxHandle,
+} from "#execution/sandbox/active-handles.js";
+
+afterEach(() => {
+ clearActiveSandboxHandlesForTest();
+});
+
+describe("shutdownActiveSandboxHandles", () => {
+ it("shuts down every tracked handle and clears the registry", async () => {
+ const first = { shutdown: vi.fn(async () => {}) };
+ const second = { shutdown: vi.fn(async () => {}) };
+ trackActiveSandboxHandle({ backendName: "docker", handle: first, sessionKey: "session-1" });
+ trackActiveSandboxHandle({ backendName: "docker", handle: second, sessionKey: "session-2" });
+
+ await shutdownActiveSandboxHandles();
+
+ expect(first.shutdown).toHaveBeenCalledTimes(1);
+ expect(second.shutdown).toHaveBeenCalledTimes(1);
+ expect(countActiveSandboxHandles()).toBe(0);
+ });
+
+ it("replaces the tracked handle when the same session is reopened", async () => {
+ const stale = { shutdown: vi.fn(async () => {}) };
+ const fresh = { shutdown: vi.fn(async () => {}) };
+ trackActiveSandboxHandle({ backendName: "docker", handle: stale, sessionKey: "session-1" });
+ trackActiveSandboxHandle({ backendName: "docker", handle: fresh, sessionKey: "session-1" });
+
+ expect(countActiveSandboxHandles()).toBe(1);
+ await shutdownActiveSandboxHandles();
+
+ expect(stale.shutdown).not.toHaveBeenCalled();
+ expect(fresh.shutdown).toHaveBeenCalledTimes(1);
+ });
+
+ it("tracks the same session key on different backends separately", async () => {
+ const docker = { shutdown: vi.fn(async () => {}) };
+ const vercel = { shutdown: vi.fn(async () => {}) };
+ trackActiveSandboxHandle({ backendName: "docker", handle: docker, sessionKey: "session-1" });
+ trackActiveSandboxHandle({ backendName: "vercel", handle: vercel, sessionKey: "session-1" });
+
+ await shutdownActiveSandboxHandles();
+
+ expect(docker.shutdown).toHaveBeenCalledTimes(1);
+ expect(vercel.shutdown).toHaveBeenCalledTimes(1);
+ });
+
+ it("logs a failed shutdown and still shuts down the remaining handles", async () => {
+ const failing = {
+ shutdown: vi.fn(async () => {
+ throw new Error("provider unreachable");
+ }),
+ };
+ const healthy = { shutdown: vi.fn(async () => {}) };
+ trackActiveSandboxHandle({ backendName: "docker", handle: failing, sessionKey: "session-1" });
+ trackActiveSandboxHandle({ backendName: "docker", handle: healthy, sessionKey: "session-2" });
+ const log = vi.fn();
+
+ await expect(shutdownActiveSandboxHandles({ log })).resolves.toBeUndefined();
+
+ expect(healthy.shutdown).toHaveBeenCalledTimes(1);
+ expect(log).toHaveBeenCalledWith(expect.stringContaining("provider unreachable"));
+ });
+});
diff --git a/packages/eve/src/execution/sandbox/active-handles.ts b/packages/eve/src/execution/sandbox/active-handles.ts
new file mode 100644
index 000000000..79f8f1bcc
--- /dev/null
+++ b/packages/eve/src/execution/sandbox/active-handles.ts
@@ -0,0 +1,73 @@
+import { toErrorMessage } from "#shared/errors.js";
+
+/**
+ * The slice of `SandboxBackendHandle` the shutdown registry needs.
+ * Structural so handles of any session-options generic register without
+ * variance friction.
+ */
+export interface ShutdownCapableSandboxHandle {
+ shutdown(): Promise<void>;
+}
+
+/**
+ * Process-level registry of live sandbox backend handles, keyed by
+ * backend name and session key so repeated `create` calls for the same
+ * session replace rather than accumulate entries.
+ *
+ * `ensureSandboxAccess` registers every handle it opens; the server
+ * shutdown path drains the registry so no sandbox compute outlives the
+ * eve server process.
+ */
+const activeSandboxHandles = new Map<string, ShutdownCapableSandboxHandle>();
+
+function createActiveSandboxHandleKey(backendName: string, sessionKey: string): string {
+ return `${backendName}\0${sessionKey}`;
+}
+
+/**
+ * Registers a live sandbox handle for shutdown tracking. A handle
+ * created later for the same backend and session key replaces the
+ * previous entry.
+ */
+export function trackActiveSandboxHandle(input: {
+ readonly backendName: string;
+ readonly handle: ShutdownCapableSandboxHandle;
+ readonly sessionKey: string;
+}): void {
+ activeSandboxHandles.set(
+ createActiveSandboxHandleKey(input.backendName, input.sessionKey),
+ input.handle,
+ );
+}
+
+/**
+ * Stops every tracked sandbox by calling `shutdown()` on each handle in
+ * parallel, then clears the registry. Failures are logged and never
+ * thrown so one misbehaving sandbox cannot block server shutdown.
+ */
+export async function shutdownActiveSandboxHandles(input?: {
+ readonly log?: (message: string) => void;
+}): Promise<void> {
+ const entries = [...activeSandboxHandles.entries()];
+ activeSandboxHandles.clear();
+
+ const results = await Promise.allSettled(entries.map(([, handle]) => handle.shutdown()));
+
+ for (const [index, result] of results.entries()) {
+ if (result.status === "rejected") {
+ const entry = entries[index];
+ input?.log?.(
+ `failed to shut down sandbox "${entry?.[0] ?? "unknown"}": ${toErrorMessage(result.reason)}`,
+ );
+ }
+ }
+}
+
+/** Returns the number of tracked handles. Exposed for tests and logging. */
+export function countActiveSandboxHandles(): number {
+ return activeSandboxHandles.size;
+}
+
+export function clearActiveSandboxHandlesForTest(): void {
+ activeSandboxHandles.clear();
+}
diff --git a/packages/eve/src/execution/sandbox/bindings/docker.integration.test.ts b/packages/eve/src/execution/sandbox/bindings/docker.integration.test.ts
index a297259e4..182498fb1 100644
--- a/packages/eve/src/execution/sandbox/bindings/docker.integration.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/docker.integration.test.ts
@@ -324,9 +324,15 @@ describe("createDockerSandboxBackend create", () => {
sessionKey: SESSION_KEY,
});
- // Dispose leaves the container running for instant reattach.
- await handle.dispose();
- expect(findCall(calls, (args) => args[0] === "stop")).toBeUndefined();
+ // Server shutdown stops the container; filesystem state survives
+ // for the next `create` to restart from.
+ await handle.shutdown();
+ expect(findCall(calls, (args) => args[0] === "stop")?.args).toEqual([
+ "stop",
+ "-t",
+ "0",
+ SESSION_KEY,
+ ]);
} finally {
if (previousRunId === undefined) {
delete process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV];
diff --git a/packages/eve/src/execution/sandbox/bindings/docker.scenario.test.ts b/packages/eve/src/execution/sandbox/bindings/docker.scenario.test.ts
index 224010bd4..09e9eebde 100644
--- a/packages/eve/src/execution/sandbox/bindings/docker.scenario.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/docker.scenario.test.ts
@@ -247,7 +247,7 @@ describe.runIf(runDockerScenarios)("docker sandbox engine against a real daemon"
);
it(
- "persists session state across dispose and reattach",
+ "persists session state across shutdown and reattach",
async () => {
const appRoot = await createScratchDirectory("eve-docker-scenario-");
const engine = createEngine();
@@ -264,11 +264,9 @@ describe.runIf(runDockerScenarios)("docker sandbox engine against a real daemon"
});
const state = await firstHandle.captureState();
expect(state.metadata).toEqual({ containerName: sessionKey });
- await firstHandle.dispose();
-
- // Simulate the runtime stopping between steps; reattach must
- // restart the container transparently.
- await cleanupCli.run(["stop", "-t", "0", sessionKey]);
+ // Server shutdown stops the container; reattach must restart it
+ // transparently.
+ await firstHandle.shutdown();
const reconnected = await engine.create({
existingMetadata: state.metadata,
diff --git a/packages/eve/src/execution/sandbox/bindings/docker.ts b/packages/eve/src/execution/sandbox/bindings/docker.ts
index 0c11220d5..e382eb6b1 100644
--- a/packages/eve/src/execution/sandbox/bindings/docker.ts
+++ b/packages/eve/src/execution/sandbox/bindings/docker.ts
@@ -4,6 +4,7 @@ import {
DOCKER_SANDBOX_LABEL,
runDockerBaseSetup,
startDockerContainer,
+ stopDockerContainerIfRunning,
} from "#execution/sandbox/bindings/docker-container.js";
import {
assertDockerDaemonAvailable,
@@ -70,8 +71,8 @@ export interface CreateDockerSandboxBackendInput {
* container into a reusable template image.
* - `create` starts (or restarts) one long-lived container per session
* key from the template image. The container's filesystem carries
- * session state across reconnects; `dispose` intentionally leaves it
- * running so reattach is instant, mirroring the Vercel backend.
+ * session state across reconnects, so `shutdown` only stops the
+ * container and the next `create` restarts it with state intact.
*/
export function createDockerSandboxBackend(
input: CreateDockerSandboxBackendInput = {},
@@ -277,10 +278,11 @@ export function createDockerSandboxBackend(
sessionKey: createInput.sessionKey,
};
},
- // Sessions stay warm across steps like the Vercel backend: the
- // container idles on a sleeping `/bin/sh`, so reattach is
- // instant and any author-started background work survives.
- async dispose() {},
+ // Session state lives in the container filesystem, so a stopped
+ // container restarts with state intact on the next `create`.
+ async shutdown() {
+ await stopDockerContainerIfRunning(cli, containerName);
+ },
};
},
};
diff --git a/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.ts b/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.ts
index e36c79742..6d7205d72 100644
--- a/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.ts
+++ b/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.ts
@@ -206,7 +206,9 @@ export function createJustBashHandle(
sessionKey: sandbox.sessionKey,
};
},
- async dispose() {
+ // The interpreter lives in this process, so stopping it is all the
+ // shutdown a just-bash sandbox needs.
+ async shutdown() {
await sandbox.dispose();
},
};
diff --git a/packages/eve/src/execution/sandbox/bindings/just-bash.scenario.test.ts b/packages/eve/src/execution/sandbox/bindings/just-bash.scenario.test.ts
index a08ab5236..5a895edac 100644
--- a/packages/eve/src/execution/sandbox/bindings/just-bash.scenario.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/just-bash.scenario.test.ts
@@ -489,7 +489,7 @@ describe("createLocalSandboxBackend with the just-bash engine", () => {
});
const initialState = await initialHandle.captureState();
- await initialHandle.dispose();
+ await initialHandle.shutdown();
await backend.prewarm({
runtimeContext: { appRoot },
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.test.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.test.ts
index cd9be1c97..f1f5a5b3b 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.test.ts
@@ -148,6 +148,36 @@ describe("createMicrosandboxHandle", () => {
});
});
+ it("stops the VM and evicts the active-session cache on shutdown", async () => {
+ const vm = createFakeMicrosandboxVm("session-key");
+ runtimeMocks.createPreparedMicrosandbox.mockResolvedValue(vm);
+ const options = resolveMicrosandboxOptions({ image: MICROSANDBOX_DEFAULT_IMAGE });
+ const createInput = {
+ runtimeContext: { appRoot: "/tmp/eve-app" },
+ sessionKey: "session-key",
+ templateKey: "template-key",
+ };
+
+ const handle = await createMicrosandboxHandle({
+ backendName: "microsandbox",
+ createInput,
+ options,
+ optionsHash: "options-hash",
+ });
+ await handle.shutdown();
+
+ expect(vm.shutdown).toHaveBeenCalledTimes(1);
+
+ const nextHandle = await createMicrosandboxHandle({
+ backendName: "microsandbox",
+ createInput,
+ options,
+ optionsHash: "options-hash",
+ });
+ expect(nextHandle).not.toBe(handle);
+ expect(runtimeMocks.createPreparedMicrosandbox).toHaveBeenCalledTimes(2);
+ });
+
it("reports a missing template snapshot race as not provisioned", async () => {
runtimeMocks.createPreparedMicrosandbox.mockRejectedValueOnce(
new Error("snapshot template-snapshot not found"),
@@ -229,6 +259,7 @@ function createFakeMicrosandboxVm(sessionKey: string) {
};
},
async detach() {},
+ shutdown: vi.fn(async () => {}),
async readFileBytes(path: string) {
return files.get(path) ?? null;
},
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.ts
index 1ece7163d..691167297 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.ts
@@ -282,7 +282,7 @@ function createHandle(
sandbox: MicrosandboxVm,
backendName: string,
optionsHash: string,
- onDispose?: () => void,
+ onShutdown?: () => void,
): SandboxBackendHandle<MicrosandboxSessionUseOptions> {
const session = buildSandboxSession(
createMicrosandboxInternalSession(sandbox),
@@ -308,9 +308,9 @@ function createHandle(
sessionKey: sandbox.id,
};
},
- async dispose() {
- onDispose?.();
- await sandbox.detach();
+ async shutdown() {
+ onShutdown?.();
+ await sandbox.shutdown();
},
};
}
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-provider-state.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-provider-state.ts
new file mode 100644
index 000000000..46694499b
--- /dev/null
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-provider-state.ts
@@ -0,0 +1,66 @@
+import type { MicrosandboxModule } from "#execution/sandbox/bindings/microsandbox-runtime.js";
+
+/**
+ * Classifies provider errors by message because the microsandbox SDK
+ * exposes no structured error codes for these conditions.
+ */
+export function isMicrosandboxNotFoundError(error: unknown): boolean {
+ if (!(error instanceof Error)) {
+ return false;
+ }
+ return /not found|not exist|no such/i.test(error.message);
+}
+
+export function isMicrosandboxStillRunningError(error: unknown): boolean {
+ if (!(error instanceof Error)) {
+ return false;
+ }
+ return /still running/i.test(error.message);
+}
+
+export function isMicrosandboxSnapshotSourceRunningError(error: unknown): boolean {
+ if (!(error instanceof Error)) {
+ return false;
+ }
+ return /snapshot source sandbox .*not stopped|SnapshotSandboxRunning/i.test(error.message);
+}
+
+export async function snapshotExists(
+ module: MicrosandboxModule,
+ snapshotName: string,
+): Promise<boolean> {
+ try {
+ await module.Snapshot.get(snapshotName);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export async function sandboxExists(
+ module: MicrosandboxModule,
+ sandboxName: string,
+): Promise<boolean> {
+ try {
+ await module.Sandbox.get(sandboxName);
+ return true;
+ } catch (error) {
+ if (isMicrosandboxNotFoundError(error)) {
+ return false;
+ }
+ throw error;
+ }
+}
+
+export async function removeSnapshotIfExists(
+ module: MicrosandboxModule,
+ snapshotName: string,
+): Promise<void> {
+ try {
+ await module.Snapshot.remove(snapshotName, { force: true });
+ } catch (error) {
+ if (!isMicrosandboxNotFoundError(error)) {
+ 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.ts
index 07819c9ee..46b2cb46d 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.test.ts
@@ -193,6 +193,56 @@ describe.skipIf(process.platform === "win32")("connectMicrosandbox", () => {
});
describe.skipIf(process.platform === "win32")("MicrosandboxVm", () => {
+ it("stops the VM before detaching the SDK client on shutdown", async () => {
+ const sandbox = {
+ detach: vi.fn(async () => {}),
+ stop: vi.fn(async () => {}),
+ };
+ const vm = new MicrosandboxVm(
+ {
+ module: {} as never,
+ options: resolveMicrosandboxOptions({ image: MICROSANDBOX_DEFAULT_IMAGE }),
+ sessionKey: "session-key",
+ },
+ sandbox as never,
+ "sandbox-name",
+ undefined,
+ );
+
+ await vm.shutdown();
+
+ expect(sandbox.stop).toHaveBeenCalledTimes(1);
+ expect(sandbox.detach).toHaveBeenCalledTimes(1);
+ const stopOrder = sandbox.stop.mock.invocationCallOrder[0];
+ const detachOrder = sandbox.detach.mock.invocationCallOrder[0];
+ if (stopOrder === undefined || detachOrder === undefined) {
+ throw new Error("Expected stop and detach to be called.");
+ }
+ expect(stopOrder).toBeLessThan(detachOrder);
+ });
+
+ it("detaches even when stopping the VM fails on shutdown", async () => {
+ const sandbox = {
+ detach: vi.fn(async () => {}),
+ stop: vi.fn(async () => {
+ throw new Error("stop failed");
+ }),
+ };
+ const vm = new MicrosandboxVm(
+ {
+ module: {} as never,
+ options: resolveMicrosandboxOptions({ image: MICROSANDBOX_DEFAULT_IMAGE }),
+ sessionKey: "session-key",
+ },
+ sandbox as never,
+ "sandbox-name",
+ undefined,
+ );
+
+ await expect(vm.shutdown()).resolves.toBeUndefined();
+ expect(sandbox.detach).toHaveBeenCalledTimes(1);
+ });
+
it("finishes streamed commands when the exec handle emits an exit event", async () => {
const sandbox = {
async execStreamWith() {
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.ts
index 549eb283b..5c3142279 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.ts
@@ -36,8 +36,22 @@ import type {
SandboxRemovePathOptions,
SandboxSpawnOptions,
} from "#shared/sandbox-session.js";
+import {
+ isMicrosandboxNotFoundError,
+ isMicrosandboxSnapshotSourceRunningError,
+ isMicrosandboxStillRunningError,
+ removeSnapshotIfExists,
+ snapshotExists,
+} from "#execution/sandbox/bindings/microsandbox-provider-state.js";
import type { Sandbox as MicrosandboxSandbox } from "microsandbox";
+export {
+ isMicrosandboxNotFoundError,
+ removeSnapshotIfExists,
+ sandboxExists,
+ snapshotExists,
+} from "#execution/sandbox/bindings/microsandbox-provider-state.js";
+
export type MicrosandboxModule = typeof import("microsandbox");
const MICROSANDBOX_PACKAGE_NAME = "microsandbox";
@@ -127,6 +141,16 @@ export class MicrosandboxVm {
await this.#sandbox.detach().catch(() => {});
}
+ /**
+ * Stops the VM and releases the SDK client for server shutdown. The
+ * stopped sandbox persists on disk, so a later `connect` restarts it
+ * (dev) or restores from the last captured snapshot (production).
+ */
+ async shutdown(): Promise<void> {
+ await this.#sandbox.stop().catch(() => {});
+ await this.detach();
+ }
+
async readFileBytes(path: string): Promise<Buffer | null> {
try {
const fs = this.#sandbox.fs();
@@ -532,46 +556,6 @@ export async function stopAndSnapshotMicrosandboxSandbox(
}
}
-export async function snapshotExists(
- module: MicrosandboxModule,
- snapshotName: string,
-): Promise<boolean> {
- try {
- await module.Snapshot.get(snapshotName);
- return true;
- } catch {
- return false;
- }
-}
-
-export async function sandboxExists(
- module: MicrosandboxModule,
- sandboxName: string,
-): Promise<boolean> {
- try {
- await module.Sandbox.get(sandboxName);
- return true;
- } catch (error) {
- if (isMicrosandboxNotFoundError(error)) {
- return false;
- }
- throw error;
- }
-}
-
-export async function removeSnapshotIfExists(
- module: MicrosandboxModule,
- snapshotName: string,
-): Promise<void> {
- try {
- await module.Snapshot.remove(snapshotName, { force: true });
- } catch (error) {
- if (!isMicrosandboxNotFoundError(error)) {
- throw error;
- }
- }
-}
-
export function createProviderName(prefix: string, key: string, extra = ""): string {
const hash = createStableHash(`${key}:${extra}`).slice(0, 32);
return `${prefix}-${hash}`;
@@ -662,27 +646,6 @@ async function removeSandboxIfExists(
}
}
-export function isMicrosandboxNotFoundError(error: unknown): boolean {
- if (!(error instanceof Error)) {
- return false;
- }
- return /not found|not exist|no such/i.test(error.message);
-}
-
-function isMicrosandboxStillRunningError(error: unknown): boolean {
- if (!(error instanceof Error)) {
- return false;
- }
- return /still running/i.test(error.message);
-}
-
-function isMicrosandboxSnapshotSourceRunningError(error: unknown): boolean {
- if (!(error instanceof Error)) {
- return false;
- }
- return /snapshot source sandbox .*not stopped|SnapshotSandboxRunning/i.test(error.message);
-}
-
function resolveMicrosandboxLabels(tags: SandboxBackendTags | undefined): Record<string, string> {
return {
"eve.backend": "microsandbox",
diff --git a/packages/eve/src/execution/sandbox/bindings/vercel.test.ts b/packages/eve/src/execution/sandbox/bindings/vercel.test.ts
index f551fe27f..fc177ca1b 100644
--- a/packages/eve/src/execution/sandbox/bindings/vercel.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/vercel.test.ts
@@ -51,6 +51,7 @@ function createMockSandbox(input: {
runCommand: vi.fn().mockResolvedValue(createMockCommandResult()),
snapshot: vi.fn().mockResolvedValue({ snapshotId: `${input.name}-snapshot` }),
status: input.status ?? "running",
+ stop: vi.fn().mockResolvedValue(undefined),
get tags() {
return tags;
},
@@ -929,6 +930,45 @@ describe("createVercelSandbox", () => {
expect(state.metadata).toEqual({ sandboxName: "persisted-sandbox-name" });
});
+ it("stops the session sandbox on shutdown so no VM outlives the server", async () => {
+ const { handle, sessionSandbox } = await createTestVercelSession();
+
+ await handle.shutdown();
+
+ expect(sessionSandbox.stop).toHaveBeenCalledTimes(1);
+ });
+
+ it("skips the stop call on shutdown when the sandbox is not running", async () => {
+ const templateSandbox = createMockSandbox({ name: "template" });
+ const sessionSandbox = createMockSandbox({ name: "session", status: "stopped" });
+ const sandboxModule = {
+ Sandbox: {
+ create: vi
+ .fn()
+ .mockResolvedValueOnce(templateSandbox)
+ .mockResolvedValueOnce(sessionSandbox),
+ get: vi.fn().mockResolvedValue(null),
+ },
+ };
+ const backend = createTestVercelSandbox({
+ loadSandboxModule: async () => sandboxModule as never,
+ });
+ await backend.prewarm({
+ runtimeContext: { appRoot: "/tmp/test-app-root" },
+ seedFiles: [],
+ templateKey: "template-key",
+ });
+ const handle = await backend.create({
+ runtimeContext: { appRoot: "/tmp/test-app-root" },
+ sessionKey: "session-key",
+ templateKey: "template-key",
+ });
+
+ await handle.shutdown();
+
+ expect(sessionSandbox.stop).not.toHaveBeenCalled();
+ });
+
it("falls back to creating a new session when the persisted sandbox no longer exists", async () => {
const templateSandbox = createMockSandbox({
name: "template-key",
diff --git a/packages/eve/src/execution/sandbox/bindings/vercel.ts b/packages/eve/src/execution/sandbox/bindings/vercel.ts
index 20e360b35..afb1b0d07 100644
--- a/packages/eve/src/execution/sandbox/bindings/vercel.ts
+++ b/packages/eve/src/execution/sandbox/bindings/vercel.ts
@@ -460,10 +460,26 @@ function createHandle(
sessionKey,
};
},
- async dispose() {},
+ // Session sandboxes are persistent, so the SDK resumes a stopped
+ // sandbox on the next command after reattach.
+ async shutdown() {
+ await stopVercelSandbox(sandbox);
+ },
};
}
+async function stopVercelSandbox(sandbox: VercelSandbox): Promise<void> {
+ if (sandbox.status !== "running" && sandbox.status !== "pending") {
+ return;
+ }
+ try {
+ await sandbox.stop();
+ } catch {
+ // Best-effort: an unreachable or already-stopped sandbox must not
+ // block server shutdown; the provider-side timeout is the backstop.
+ }
+}
+
function createVercelNetworkPolicySetter(
sandbox: VercelSandbox,
): (policy: SandboxNetworkPolicy) => Promise<void> {
diff --git a/packages/eve/src/execution/sandbox/ensure.test.ts b/packages/eve/src/execution/sandbox/ensure.test.ts
index 423ec7c0c..544ceeb22 100644
--- a/packages/eve/src/execution/sandbox/ensure.test.ts
+++ b/packages/eve/src/execution/sandbox/ensure.test.ts
@@ -16,6 +16,11 @@ import type { ResolvedSandboxDefinition } from "#runtime/types.js";
import { ContextContainer, contextStorage, loadContext } from "#context/container.js";
import { SessionKey } from "#context/keys.js";
import type { Session } from "#context/keys.js";
+import {
+ clearActiveSandboxHandlesForTest,
+ countActiveSandboxHandles,
+ shutdownActiveSandboxHandles,
+} from "#execution/sandbox/active-handles.js";
import {
clearInitializedDevelopmentSandboxBackendNames,
EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV,
@@ -70,7 +75,7 @@ function createBackend(): SandboxBackend {
sessionKey: input.sessionKey,
}),
useSessionFn: async () => sandbox.session,
- dispose: async () => {},
+ shutdown: async () => {},
session: sandbox.session,
};
});
@@ -322,6 +327,19 @@ describe("ensureSandboxAccess", () => {
);
});
+ it("tracks created handles for server shutdown", async () => {
+ clearActiveSandboxHandlesForTest();
+ const backend = createBackend();
+ const registry = createTestRegistry({}, backend);
+
+ const access = await ensure({ registry });
+ await access.get();
+
+ expect(countActiveSandboxHandles()).toBe(1);
+ await shutdownActiveSandboxHandles();
+ expect(countActiveSandboxHandles()).toBe(0);
+ });
+
it("records the backend after a development sandbox is initialized", async () => {
process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV] = "dev-run-test";
const backend = createBackend();
diff --git a/packages/eve/src/execution/sandbox/ensure.ts b/packages/eve/src/execution/sandbox/ensure.ts
index b44fd29c1..30f84387f 100644
--- a/packages/eve/src/execution/sandbox/ensure.ts
+++ b/packages/eve/src/execution/sandbox/ensure.ts
@@ -11,6 +11,7 @@ import {
getRuntimeCompiledArtifactsSandboxAppRoot,
type RuntimeCompiledArtifactsSource,
} from "#runtime/compiled-artifacts-source.js";
+import { trackActiveSandboxHandle } from "#execution/sandbox/active-handles.js";
import { waitForDevelopmentSandboxPrewarm } from "#execution/sandbox/development-prewarm.js";
import { markDevelopmentSandboxBackendInitialized } from "#execution/sandbox/development-run.js";
import { prewarmAppSandboxes } from "#execution/sandbox/prewarm.js";
@@ -128,6 +129,11 @@ export async function ensureSandboxAccess(input: EnsureSandboxAccessInput): Prom
}),
);
markDevelopmentSandboxBackendInitialized(backend.name);
+ trackActiveSandboxHandle({
+ backendName: backend.name,
+ handle,
+ sessionKey: keys.sessionKey,
+ });
if (!initialized) {
await runOnSession(async () => {
@@ -161,12 +167,6 @@ export async function ensureSandboxAccess(input: EnsureSandboxAccessInput): Prom
session: persistedSession,
};
},
- async dispose() {
- if (handlePromise !== undefined) {
- const handle = await handlePromise;
- await handle?.dispose();
- }
- },
async get(): Promise<SandboxSession | null> {
const handle = await getHandle();
return handle?.session ?? null;
diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts
index ba4b2c3c2..604a1b116 100644
--- a/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts
+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts
@@ -578,6 +578,29 @@ describe("createApplicationNitro", () => {
);
});
+ it("includes the sandbox shutdown plugin only for production builds", async () => {
+ const productionNitroStub = createNitroStub();
+ const devNitroStub = createNitroStub();
+ createNitroMock.mockResolvedValueOnce(productionNitroStub.nitro);
+ createNitroMock.mockResolvedValueOnce(devNitroStub.nitro);
+
+ const { createApplicationNitro } =
+ await import("#internal/nitro/host/create-application-nitro.js");
+
+ await createApplicationNitro(createPreparedHost(), false);
+ await createApplicationNitro(createPreparedHost(), true);
+
+ const productionPlugins = createNitroMock.mock.calls[0]?.[0].plugins as string[];
+ const devPlugins = createNitroMock.mock.calls[1]?.[0].plugins as string[];
+
+ expect(productionPlugins).toEqual(
+ expect.arrayContaining([expect.stringContaining("sandbox-shutdown-plugin.ts")]),
+ );
+ expect(devPlugins).not.toEqual(
+ expect.arrayContaining([expect.stringContaining("sandbox-shutdown-plugin.ts")]),
+ );
+ });
+
it("deduplicates defaults when the app also lists them", async () => {
const nitroStub = createNitroStub();
createNitroMock.mockResolvedValueOnce(nitroStub.nitro);
diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.ts
index 67f8d57e7..1fbd73707 100644
--- a/packages/eve/src/internal/nitro/host/create-application-nitro.ts
+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.ts
@@ -675,6 +675,14 @@ export async function createApplicationNitro(
includesApplicationSurface(surface) &&
(dev || manifestHasWebSocketChannel(preparedHost.compileResult.manifest));
const nitroPlugins: string[] = [];
+ if (!dev) {
+ // Stops all tracked sandboxes when the production server shuts
+ // down. Dev servers are excluded: the dev CLI parent already stops
+ // dev-tagged sandboxes when the dev server closes.
+ nitroPlugins.push(
+ resolvePackageSourceFilePath("src/internal/nitro/host/sandbox-shutdown-plugin.ts"),
+ );
+ }
if (manifestEnablesWorkflow(preparedHost.compileResult.manifest)) {
nitroPlugins.push(
resolvePackageSourceFilePath("src/internal/nitro/host/workflow-sandbox-runtime-plugin.ts"),
diff --git a/packages/eve/src/internal/nitro/host/sandbox-shutdown-plugin.test.ts b/packages/eve/src/internal/nitro/host/sandbox-shutdown-plugin.test.ts
new file mode 100644
index 000000000..6ebcd7332
--- /dev/null
+++ b/packages/eve/src/internal/nitro/host/sandbox-shutdown-plugin.test.ts
@@ -0,0 +1,136 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import {
+ clearActiveSandboxHandlesForTest,
+ trackActiveSandboxHandle,
+} from "#execution/sandbox/active-handles.js";
+import {
+ installSandboxShutdownHandlers,
+ runSandboxShutdown,
+ shouldInstallSandboxShutdown,
+} from "#internal/nitro/host/sandbox-shutdown-plugin.js";
+
+type SignalListener = () => void;
+
+function createFakeProcess(env: Record<string, string | undefined> = {}) {
+ const listeners = new Map<string, SignalListener>();
+ const exit = vi.fn<(code?: number) => void>();
+ return {
+ emit(event: string): void {
+ listeners.get(event)?.();
+ },
+ env,
+ exit,
+ listeners,
+ once(event: "SIGINT" | "SIGTERM", listener: SignalListener): unknown {
+ listeners.set(event, listener);
+ return this;
+ },
+ };
+}
+
+afterEach(() => {
+ clearActiveSandboxHandlesForTest();
+ vi.unstubAllEnvs();
+});
+
+describe("shouldInstallSandboxShutdown", () => {
+ it("installs on a plain production server", () => {
+ expect(shouldInstallSandboxShutdown({})).toBe(true);
+ });
+
+ it("skips eve dev processes", () => {
+ vi.stubEnv("EVE_DEV", "1");
+ expect(shouldInstallSandboxShutdown({})).toBe(false);
+ });
+
+ it("skips dev sandbox run workers", () => {
+ expect(shouldInstallSandboxShutdown({ EVE_DEVELOPMENT_SANDBOX_RUN_ID: "dev-run" })).toBe(false);
+ });
+
+ it("skips Vercel serverless instances", () => {
+ expect(shouldInstallSandboxShutdown({ VERCEL: "1" })).toBe(false);
+ });
+});
+
+describe("installSandboxShutdownHandlers", () => {
+ it("registers no handlers when shutdown ownership is elsewhere", () => {
+ const fakeProcess = createFakeProcess({ VERCEL: "1" });
+
+ installSandboxShutdownHandlers({ log: () => {}, process: fakeProcess });
+
+ expect(fakeProcess.listeners.size).toBe(0);
+ });
+
+ it("stops tracked sandboxes and exits 143 on SIGTERM", async () => {
+ const handle = { shutdown: vi.fn(async () => {}) };
+ trackActiveSandboxHandle({ backendName: "docker", handle, sessionKey: "session-1" });
+ const fakeProcess = createFakeProcess();
+
+ installSandboxShutdownHandlers({ log: () => {}, process: fakeProcess });
+ fakeProcess.emit("SIGTERM");
+
+ await vi.waitFor(() => {
+ expect(fakeProcess.exit).toHaveBeenCalledWith(143);
+ });
+ expect(handle.shutdown).toHaveBeenCalledTimes(1);
+ });
+
+ it("stops tracked sandboxes and exits 130 on SIGINT", async () => {
+ const handle = { shutdown: vi.fn(async () => {}) };
+ trackActiveSandboxHandle({ backendName: "docker", handle, sessionKey: "session-1" });
+ const fakeProcess = createFakeProcess();
+
+ installSandboxShutdownHandlers({ log: () => {}, process: fakeProcess });
+ fakeProcess.emit("SIGINT");
+
+ await vi.waitFor(() => {
+ expect(fakeProcess.exit).toHaveBeenCalledWith(130);
+ });
+ expect(handle.shutdown).toHaveBeenCalledTimes(1);
+ });
+
+ it("stops tracked sandboxes through the nitro close hook", async () => {
+ const handle = { shutdown: vi.fn(async () => {}) };
+ trackActiveSandboxHandle({ backendName: "docker", handle, sessionKey: "session-1" });
+ let closeHandler: (() => Promise<void>) | undefined;
+ const nitroApp = {
+ hooks: {
+ hook(name: "close", handler: () => Promise<void>) {
+ if (name === "close") {
+ closeHandler = handler;
+ }
+ return undefined;
+ },
+ },
+ };
+
+ installSandboxShutdownHandlers({
+ log: () => {},
+ nitroApp,
+ process: createFakeProcess(),
+ });
+ await closeHandler?.();
+
+ expect(handle.shutdown).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("runSandboxShutdown", () => {
+ it("exits even when a handle shutdown never settles", async () => {
+ vi.useFakeTimers();
+ try {
+ const handle = { shutdown: vi.fn(() => new Promise<void>(() => {})) };
+ trackActiveSandboxHandle({ backendName: "docker", handle, sessionKey: "session-1" });
+ const log = vi.fn();
+
+ const shutdown = runSandboxShutdown(log);
+ await vi.advanceTimersByTimeAsync(15_000);
+ await shutdown;
+
+ expect(log).toHaveBeenCalledWith(expect.stringContaining("timed out"));
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/packages/eve/src/internal/nitro/host/sandbox-shutdown-plugin.ts b/packages/eve/src/internal/nitro/host/sandbox-shutdown-plugin.ts
new file mode 100644
index 000000000..716a33743
--- /dev/null
+++ b/packages/eve/src/internal/nitro/host/sandbox-shutdown-plugin.ts
@@ -0,0 +1,113 @@
+import { shutdownActiveSandboxHandles } from "#execution/sandbox/active-handles.js";
+import { isEveDevEnvironment } from "#internal/application/optional-package-install.js";
+
+const SHUTDOWN_SIGNALS = ["SIGINT", "SIGTERM"] as const;
+type ShutdownSignal = (typeof SHUTDOWN_SIGNALS)[number];
+
+/**
+ * Bounds sandbox shutdown so a wedged provider cannot keep the server
+ * process alive past the supervisor's kill grace (`eve start` waits
+ * 20s before SIGKILL).
+ */
+const SANDBOX_SHUTDOWN_TIMEOUT_MS = 15_000;
+
+let installed = false;
+
+interface SandboxShutdownProcess {
+ readonly env: Record<string, string | undefined>;
+ exit(code?: number): void;
+ once(event: ShutdownSignal, listener: () => void): unknown;
+}
+
+interface NitroAppLike {
+ readonly hooks?: {
+ hook(name: "close", handler: () => Promise<void>): unknown;
+ };
+}
+
+/**
+ * Reports whether this server process owns sandbox shutdown.
+ *
+ * - `eve dev` workers are excluded: the dev CLI parent already stops
+ * dev-tagged sandboxes when the dev server closes.
+ * - Vercel serverless instances are excluded: instance recycling is not
+ * a server stop, and persistent session sandboxes must keep serving
+ * later invocations.
+ */
+export function shouldInstallSandboxShutdown(env: Record<string, string | undefined>): boolean {
+ if (isEveDevEnvironment()) {
+ return false;
+ }
+ if (env.EVE_DEVELOPMENT_SANDBOX_RUN_ID !== undefined) {
+ return false;
+ }
+ if (env.VERCEL !== undefined) {
+ return false;
+ }
+ return true;
+}
+
+/**
+ * Stops all tracked sandboxes, bounded by
+ * {@link SANDBOX_SHUTDOWN_TIMEOUT_MS}. Never throws.
+ */
+export async function runSandboxShutdown(log: (message: string) => void): Promise<void> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const deadline = new Promise<void>((resolve) => {
+ timer = setTimeout(() => {
+ log("eve: sandbox shutdown timed out; continuing exit");
+ resolve();
+ }, SANDBOX_SHUTDOWN_TIMEOUT_MS);
+ timer.unref?.();
+ });
+
+ try {
+ await Promise.race([shutdownActiveSandboxHandles({ log }), deadline]);
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+function exitCodeForSignal(signal: ShutdownSignal): number {
+ return signal === "SIGINT" ? 130 : 143;
+}
+
+/**
+ * Wires sandbox shutdown into the server lifecycle: the nitro `close`
+ * hook plus SIGINT/SIGTERM, since the node-server preset installs no
+ * signal handling of its own. Exposed for tests; the plugin default
+ * export applies it to the real `process`.
+ */
+export function installSandboxShutdownHandlers(input: {
+ readonly log: (message: string) => void;
+ readonly nitroApp?: NitroAppLike;
+ readonly process: SandboxShutdownProcess;
+}): void {
+ if (!shouldInstallSandboxShutdown(input.process.env)) {
+ return;
+ }
+
+ input.nitroApp?.hooks?.hook("close", async () => {
+ await runSandboxShutdown(input.log);
+ });
+
+ for (const signal of SHUTDOWN_SIGNALS) {
+ input.process.once(signal, () => {
+ void runSandboxShutdown(input.log).finally(() => {
+ input.process.exit(exitCodeForSignal(signal));
+ });
+ });
+ }
+}
+
+export default function sandboxShutdownPlugin(nitroApp?: NitroAppLike): void {
+ if (installed) {
+ return;
+ }
+ installed = true;
+ installSandboxShutdownHandlers({
+ log: (message) => console.error(message),
+ nitroApp,
+ process,
+ });
+}
diff --git a/packages/eve/src/internal/nitro/host/start-production-server.ts b/packages/eve/src/internal/nitro/host/start-production-server.ts
index 3c847b2fd..4522ab7a5 100644
--- a/packages/eve/src/internal/nitro/host/start-production-server.ts
+++ b/packages/eve/src/internal/nitro/host/start-production-server.ts
@@ -14,7 +14,10 @@ const DEFAULT_PRODUCTION_SERVER_PORT = 3000;
const HEALTH_POLL_INTERVAL_MS = 250;
const HEALTH_TIMEOUT_MS = 60_000;
const LOCAL_SERVER_URL_PATTERN = /https?:\/\/(?:\[[^\]\s]+\]|[^\s/:[\]]+)(?::\d+)?/;
-const TERMINATE_GRACE_MS = 5_000;
+// Must exceed the server's bounded sandbox shutdown (15s in
+// sandbox-shutdown-plugin.ts) so stopping sandboxes on SIGTERM is not
+// cut short by SIGKILL.
+const TERMINATE_GRACE_MS = 20_000;
const WILDCARD_LISTEN_HOSTNAMES: ReadonlySet<string> = new Set(["[::]", "::", "0.0.0.0"]);
function isRecord(value: unknown): value is Record<string, unknown> {
diff --git a/packages/eve/src/internal/testing/mocks/mock-sandbox.ts b/packages/eve/src/internal/testing/mocks/mock-sandbox.ts
index e8b09c4bc..aba6060a1 100644
--- a/packages/eve/src/internal/testing/mocks/mock-sandbox.ts
+++ b/packages/eve/src/internal/testing/mocks/mock-sandbox.ts
@@ -249,9 +249,6 @@ export function mockSandbox(input: MockSandboxInput = {}): MockSandbox {
session: null,
};
},
- async dispose(): Promise<void> {
- // No-op: nothing to release in memory.
- },
async get(): Promise<SandboxSession> {
return session;
},
diff --git a/packages/eve/src/sandbox/state.ts b/packages/eve/src/sandbox/state.ts
index 7e4d08c99..5b9fb3e4f 100644
--- a/packages/eve/src/sandbox/state.ts
+++ b/packages/eve/src/sandbox/state.ts
@@ -31,6 +31,5 @@ export interface SandboxState {
*/
export interface SandboxAccess {
captureState(): Promise<SandboxState>;
- dispose(): Promise<void>;
get(): Promise<SandboxSession | null>;
}
diff --git a/packages/eve/src/shared/sandbox-backend.ts b/packages/eve/src/shared/sandbox-backend.ts
index ef146073d..2898e58ef 100644
--- a/packages/eve/src/shared/sandbox-backend.ts
+++ b/packages/eve/src/shared/sandbox-backend.ts
@@ -12,7 +12,13 @@ export interface SandboxBackendHandle<SO = Record<string, never>> {
readonly session: SandboxSession;
readonly useSessionFn: SandboxSessionUseFn<SO>;
captureState(): Promise<SandboxBackendSessionState>;
- dispose(): Promise<void>;
+ /**
+ * Stops the underlying compute because the eve server is shutting
+ * down; nothing may be left running afterwards. The session must
+ * remain reattachable from persisted state on the next server start
+ * when the backend supports durable sessions.
+ */
+ shutdown(): Promise<void>;
}
/**
diff --git a/packages/eve/test/define-bash-tool.test.ts b/packages/eve/test/define-bash-tool.test.ts
index 40d704f8e..9fd212f1d 100644
--- a/packages/eve/test/define-bash-tool.test.ts
+++ b/packages/eve/test/define-bash-tool.test.ts
@@ -41,7 +41,6 @@ describe("defineBashTool", () => {
session: null,
};
},
- async dispose() {},
async get() {
return {
@@ -99,7 +98,6 @@ describe("defineBashTool", () => {
session: null,
};
},
- async dispose() {},
async get() {
return null;
@@ -133,7 +131,6 @@ describe("defineBashTool", () => {
async captureState() {
return { initialized: false, session: null };
},
- async dispose() {},
async get() {
return {
diff --git a/packages/eve/test/define-glob-tool.test.ts b/packages/eve/test/define-glob-tool.test.ts
index d64611280..5c56b4162 100644
--- a/packages/eve/test/define-glob-tool.test.ts
+++ b/packages/eve/test/define-glob-tool.test.ts
@@ -14,7 +14,6 @@ function createFakeAccess(
async captureState() {
return { initialized: false, session: null };
},
- async dispose() {},
async get() {
const callHandler = handler;
@@ -103,7 +102,6 @@ describe("defineGlobTool", () => {
async captureState() {
return { initialized: false, session: null };
},
- async dispose() {},
async get() {
return null;
diff --git a/packages/eve/test/define-grep-tool.test.ts b/packages/eve/test/define-grep-tool.test.ts
index 4d819c606..4ad00d8f5 100644
--- a/packages/eve/test/define-grep-tool.test.ts
+++ b/packages/eve/test/define-grep-tool.test.ts
@@ -14,7 +14,6 @@ function createFakeAccess(
async captureState() {
return { initialized: false, session: null };
},
- async dispose() {},
async get() {
const callHandler = handler;
@@ -103,7 +102,6 @@ describe("defineGrepTool", () => {
async captureState() {
return { initialized: false, session: null };
},
- async dispose() {},
async get() {
return null;
diff --git a/packages/eve/test/define-read-file-tool.test.ts b/packages/eve/test/define-read-file-tool.test.ts
index 2437815e7..8952c5471 100644
--- a/packages/eve/test/define-read-file-tool.test.ts
+++ b/packages/eve/test/define-read-file-tool.test.ts
@@ -13,7 +13,6 @@ function createFakeAccess(files: Record<string, string>): SandboxAccess {
async captureState() {
return { initialized: false, session: null };
},
- async dispose() {},
async get() {
return {
@@ -99,7 +98,6 @@ describe("defineReadFileTool", () => {
async captureState() {
return { initialized: false, session: null };
},
- async dispose() {},
async get() {
return null;
diff --git a/packages/eve/test/define-write-file-tool.test.ts b/packages/eve/test/define-write-file-tool.test.ts
index 06f20d358..a974419d1 100644
--- a/packages/eve/test/define-write-file-tool.test.ts
+++ b/packages/eve/test/define-write-file-tool.test.ts
@@ -16,7 +16,6 @@ function createFakeAccess(files: Record<string, string>): SandboxAccess {
async captureState() {
return { initialized: false, session: null };
},
- async dispose() {},
async get() {
return {
@@ -109,7 +108,6 @@ describe("defineWriteFileTool", () => {
async captureState() {
return { initialized: false, session: null };
},
- async dispose() {},
async get() {
return null;
diff --git a/packages/eve/test/file-tool-compaction.test.ts b/packages/eve/test/file-tool-compaction.test.ts
index b75447857..bca03b30c 100644
--- a/packages/eve/test/file-tool-compaction.test.ts
+++ b/packages/eve/test/file-tool-compaction.test.ts
@@ -56,7 +56,6 @@ function createFakeAccess(files: Record<string, string>): {
async captureState() {
return { initialized: false, session: null };
},
- async dispose() {},
async get() {
return session;
},
diff --git a/packages/eve/test/glob-tool.test.ts b/packages/eve/test/glob-tool.test.ts
index 43d0b9e08..2d6baad67 100644
--- a/packages/eve/test/glob-tool.test.ts
+++ b/packages/eve/test/glob-tool.test.ts
@@ -34,7 +34,6 @@ function createFakeAccess(
async captureState() {
return { initialized: false, session: null };
},
- async dispose() {},
async get() {
return {
diff --git a/packages/eve/test/grep-tool.test.ts b/packages/eve/test/grep-tool.test.ts
index 62323858e..f2abad1ad 100644
--- a/packages/eve/test/grep-tool.test.ts
+++ b/packages/eve/test/grep-tool.test.ts
@@ -34,7 +34,6 @@ function createFakeAccess(
async captureState() {
return { initialized: false, session: null };
},
- async dispose() {},
async get() {
return {
diff --git a/packages/eve/test/read-file-tool.test.ts b/packages/eve/test/read-file-tool.test.ts
index b9d9daa76..f5bb52f0b 100644
--- a/packages/eve/test/read-file-tool.test.ts
+++ b/packages/eve/test/read-file-tool.test.ts
@@ -19,7 +19,6 @@ function createFakeAccess(files: Record<string, string | null>): SandboxAccess {
async captureState() {
return { initialized: false, session: null };
},
- async dispose() {},
async get() {
return {
diff --git a/packages/eve/test/scenarios/sandbox-workspace-folders.scenario.test.ts b/packages/eve/test/scenarios/sandbox-workspace-folders.scenario.test.ts
index 29733133b..4d9c36492 100644
--- a/packages/eve/test/scenarios/sandbox-workspace-folders.scenario.test.ts
+++ b/packages/eve/test/scenarios/sandbox-workspace-folders.scenario.test.ts
@@ -67,7 +67,7 @@ describe("sandbox workspace folder convention", () => {
const roundTrip = await handle.session.readTextFile({ path: "/workspace/authored.txt" });
expect(roundTrip).toBe("round-trip");
- await handle.dispose();
+ await handle.shutdown();
});
it("opens an empty prewarmed template when the sandbox has no authored workspace files", async () => {
@@ -95,7 +95,7 @@ describe("sandbox workspace folder convention", () => {
expect(result.exitCode).toBe(0);
expect(Number(result.stdout.trim())).toBe(0);
- await handle.dispose();
+ await handle.shutdown();
});
it("materializes a fixture default workspace folder into a deterministic file list", async () => {
diff --git a/packages/eve/test/write-file-tool.test.ts b/packages/eve/test/write-file-tool.test.ts
index 6cf24e446..2c66917b5 100644
--- a/packages/eve/test/write-file-tool.test.ts
+++ b/packages/eve/test/write-file-tool.test.ts
@@ -60,7 +60,6 @@ function createFakeAccess(files: Record<string, string>): {
async captureState() {
return { initialized: false, session: null };
},
- async dispose() {},
async get() {
return session;
},