The Open Framework for Building Agents
feat(sandbox)!: make DefaultSandbox choose its provider once at build (#5232)
Andrew Barba12a1e90627ae
diff --git a/.changeset/default-sandbox-build-choice.md b/.changeset/default-sandbox-build-choice.mdnew file mode 100644index 000000000..333919dcc--- /dev/null+++ b/.changeset/default-sandbox-build-choice.md@@ -0,0 +1,11 @@+---+"eve": minor+---++`DefaultSandbox` now selects its provider once, when eve prepares the sandbox, and records the choice in the build: Vercel Sandbox on Vercel, then Docker when a daemon is reachable, then just-bash only in `eve dev` and `eve eval`. The runtime uses the recorded provider instead of probing the host again, so a build and its server can no longer select different providers. A production `eve build` with neither Vercel nor Docker no longer falls back to just-bash: the build succeeds, and opening the sandbox fails with an error that asks you to start Docker and rebuild, deploy to Vercel, or select a provider explicitly.++`DefaultSandbox.environment().open()` now accepts `networkPolicy`, and its sessions expose `setNetworkPolicy()`. eve forwards the policy to the selected provider. Docker rejects any policy other than `"allow-all"` or `"deny-all"` when it opens the sandbox, instead of starting the container with open network access, and just-bash rejects any policy other than `"allow-all"`.++Sessions now record their sandbox under the provider name `"default"` instead of `vercel`, `docker`, or `just-bash`. Sessions saved by an earlier eve under the provider that `DefaultSandbox` selected resume the same sandbox. When a session's recorded state belongs to another provider or state protocol, for example after you change providers, eve now starts a fresh sandbox instead of failing; the old sandbox is not deleted. This upgrade is one-way: if you roll back to an earlier eve release, sessions created on this release fail to open their sandbox, because earlier releases reject state recorded under `"default"`.++`VercelSandbox.environment()` no longer captures a snapshot when the environment has no `prepare` callback, no managed workspace or skill files, and no `source`. Session sandboxes start from the image and install the base runtime themselves, as `DefaultSandbox` already did on Vercel. Such sessions now apply a `networkPolicy` set on the environment after base setup; before, only a policy passed to `open()` applied, so `VercelSandbox.environment({ networkPolicy })` and `DefaultSandbox.environment({ vercel: { networkPolicy } })` could leave a session with open network access.diff --git a/docs/guides/deployment/self-hosting.md b/docs/guides/deployment/self-hosting.mdindex 194f16da8..4ce7d5938 100644--- a/docs/guides/deployment/self-hosting.md+++ b/docs/guides/deployment/self-hosting.md@@ -90,7 +90,9 @@ This adds conversation text as context to the replacement session.## Select a sandbox provider-The default sandbox environment selects Docker when a Docker daemon is reachable and falls back to just-bash otherwise. You can select one explicitly or implement a custom provider with `defineSandboxProvider()` for your container, virtual machine, or isolation service.+The default sandbox environment selects Docker when `eve build` can reach a Docker daemon and records that choice in the build. A production build never falls back to just-bash: when Docker is unreachable during the build, the build succeeds, but each session fails when it opens the sandbox. Run `eve build` where Docker is reachable, select a provider explicitly, or implement a custom provider with `defineSandboxProvider()` for your container, virtual machine, or isolation service.++A `RUN eve build` step in a Dockerfile usually has no Docker daemon, so the build records no provider even when the running container later mounts `/var/run/docker.sock`. In that setup, select `DockerSandbox.environment()` from `eve/sandbox/docker` explicitly in your sandbox module, or run `eve build` in an environment where Docker is reachable and copy the output into the image.Don’t select `VercelSandbox.environment()` unless the self-hosted process should create hosted Vercel sandboxes. See [Sandbox](../../sandbox) for provider configuration and selection order.diff --git a/docs/sandbox/default.mdx b/docs/sandbox/default.mdxindex d4dcf258f..771ef5780 100644--- a/docs/sandbox/default.mdx+++ b/docs/sandbox/default.mdx@@ -1,9 +1,9 @@---title: "Default Sandbox"-description: "Let eve select the sandbox provider for the current environment."+description: "Let eve select the sandbox provider when it prepares the sandbox."----`DefaultSandbox.environment()` selects a sandbox provider for the host that loads your sandbox file. Its `open()` method takes no options.+`DefaultSandbox.environment()` selects a sandbox provider when eve prepares the sandbox, records the choice, and uses that provider for every session the build serves.```tsimport { DefaultSandbox, defineSandbox } from "eve/sandbox";@@ -12,21 +12,31 @@ export const environment = DefaultSandbox.environment();export default defineSandbox(() => environment.open());```-On Vercel, it selects [Vercel Sandbox](/docs/sandbox/vercel). Elsewhere, it selects [Docker](/docs/sandbox/docker) when a Docker daemon is reachable and falls back to [just-bash](/docs/sandbox/just-bash) otherwise.--Use a provider directly when you need options for `open()`, such as a per-sandbox `networkPolicy` or Vercel Drive `mounts`, or a provider-specific session such as one with `setNetworkPolicy()`.+On Vercel, it selects [Vercel Sandbox](/docs/sandbox/vercel). Elsewhere, it selects [Docker](/docs/sandbox/docker) when a Docker daemon is reachable, and [just-bash](/docs/sandbox/just-bash) only during `eve dev` and `eve eval`.## How eve selects the provider-`DefaultSandbox.environment()` selects the provider when it runs, which is when your sandbox module loads:+eve selects the provider when it prepares the sandbox: during `eve build`, or during `eve dev` the first time a session opens the sandbox. It checks in this order:1. If the `VERCEL` environment variable is set, it selects Vercel.-2. Otherwise, if `docker version` reports a running Linux Docker daemon within five seconds, it selects Docker. eve checks once per process and reuses the answer.-3. Otherwise, it selects just-bash.+2. Otherwise, if `docker version` reports a running Linux Docker daemon within five seconds, it selects Docker.+3. Otherwise, during `eve dev` and `eve eval`, it selects just-bash.+4. Otherwise, in a production `eve build`, it selects no provider.++| Where eve prepares the sandbox | Selected provider |+| ------------------------------------------------- | --------------------------------------------- |+| On Vercel (`vercel build` or a Vercel deploy) | [Vercel Sandbox](/docs/sandbox/vercel) |+| Anywhere a Linux Docker daemon is reachable | [Docker](/docs/sandbox/docker) |+| `eve dev` or `eve eval` without Docker | [just-bash](/docs/sandbox/just-bash) |+| A production `eve build` without Vercel or Docker | None: opening the sandbox fails with an error |++Production builds never fall back to just-bash, because just-bash runs no native processes and provides no network isolation. When no provider is available, `eve build` still succeeds and logs that no provider is available. The first session that opens the sandbox fails with an error that asks you to start Docker and rebuild, deploy to Vercel, or select a provider explicitly in your sandbox file. See [Sandbox troubleshooting](/docs/sandbox/troubleshooting).++## The build records the choice-`eve build`, `eve dev`, and each production server process load the sandbox module separately, so each one selects a provider for its own host. If the build host and the runtime host differ, they can select different providers. For example, a build on a CI machine without Docker prepares a different provider's environment than a server with Docker selects, and the server fails with a provider mismatch error. Run `eve build` where the runtime's provider is available, or select that provider explicitly with `DockerSandbox` or `VercelSandbox`. See [Sandbox troubleshooting](/docs/sandbox/troubleshooting) for the exact errors.+`eve build` stores the selected provider in the build's prepared sandbox artifact. At runtime, `DefaultSandbox` reads the recorded provider and does not check for Vercel or Docker again, so the build and the server it produces always use the same provider, even when the server runs on a different host. To change the provider, rebuild where the provider you want is available.-A running session keeps the provider that created its sandbox. If a later process selects a different provider, for example because Docker stopped, that session cannot resume its sandbox.+Each session also records the provider that created its sandbox. If a later build selects a different provider, a session that resumes on the new build starts a fresh sandbox from the new provider, without the old sandbox's files. eve does not delete the old sandbox: a Vercel Sandbox stays in your Vercel project, and a Docker container stays on the Docker host until you remove it.## Environment options@@ -54,6 +64,21 @@ export default defineSandbox(() => environment.open());| `vercel` | Vercel is selected | The options of [`VercelSandbox.environment()`](/docs/sandbox/vercel), such as `region`, `resources`, and credentials. || `justBash` | just-bash is selected | The options of [`JustBashSandbox.environment()`](/docs/sandbox/just-bash), such as `autoInstall` and `customCommands`. |-Keep a shared `prepare` callback portable, because it runs on whichever provider eve selects. just-bash runs no native binaries, so commands such as `apt-get` fail there.+Keep a shared `prepare` callback portable, because it runs on whichever provider eve selects. just-bash runs no native binaries, so commands such as `apt-get` fail there during `eve dev`.++On Vercel, when the environment has no `prepare` callback, workspace seed, skill files, or `source`, eve skips the snapshot and creates each session sandbox directly from the configured `image`, or from eve's base image when none is set. See [Vercel Sandbox](/docs/sandbox/vercel#snapshot-preparation).++## Network policy++Pass `networkPolicy` to `open()`, or call `setNetworkPolicy()` on the session from `ctx.getSandbox(environment)`. eve forwards the policy to the selected provider:++```ts+import { DefaultSandbox, defineSandbox } from "eve/sandbox";++export const environment = DefaultSandbox.environment();+export default defineSandbox(() => environment.open({ networkPolicy: "deny-all" }));+```++Vercel Sandbox accepts every network policy, including domain allow-lists and credential transforms. Docker accepts only `"allow-all"` and `"deny-all"` and rejects any other policy with an error. just-bash always allows network access, so it accepts only `"allow-all"` and rejects any other policy with an error. Use [Vercel Sandbox](/docs/sandbox/vercel) directly when you need domain-level policies in every environment.-On Vercel, when the environment has no `prepare` callback, workspace seed, or skill files, `DefaultSandbox` skips the snapshot and creates each session sandbox directly from the configured `image` or `source`, or from eve's base image when neither is set.+Use a provider directly when you need its other `open()` options, such as Vercel compute resources or Drive `mounts`.diff --git a/docs/sandbox/index.mdx b/docs/sandbox/index.mdxindex bdfa7f7f3..5a9292831 100644--- a/docs/sandbox/index.mdx+++ b/docs/sandbox/index.mdx@@ -245,16 +245,16 @@ Preparation discovers authored files through `ctx.files`; core keeps project lay## Providers-| Provider | Use it for |-| ------------------------------------ | --------------------------------------------------------------------------------------- |-| [Default](/docs/sandbox/default) | Automatic provider selection with eve's standard behavior. |-| [Vercel](/docs/sandbox/vercel) | Snapshot-backed persistent Vercel Sandboxes, domain network policies, and Drive mounts. |-| [Docker](/docs/sandbox/docker) | Local containers from the default image, an existing OCI image, or a Dockerfile. |-| [just-bash](/docs/sandbox/just-bash) | A pure-JavaScript shell and virtual filesystem without native process isolation. |+| Provider | Use it for |+| ------------------------------------ | ------------------------------------------------------------------------------------------- |+| [Default](/docs/sandbox/default) | Vercel Sandbox on Vercel, Docker when reachable, and just-bash in development. |+| [Vercel](/docs/sandbox/vercel) | Persistent Vercel Sandboxes, prepared snapshots, domain network policies, and Drive mounts. |+| [Docker](/docs/sandbox/docker) | Local containers from the default image, an existing OCI image, or a Dockerfile. |+| [just-bash](/docs/sandbox/just-bash) | A pure-JavaScript shell and virtual filesystem without native process isolation. |## 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. 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.+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. eve also starts a fresh sandbox when the recorded state belongs to another provider or state protocol than the current environment, for example after you change providers; the old sandbox is not deleted. 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/troubleshooting.mdx b/docs/sandbox/troubleshooting.mdxindex 45cc9f1bb..3a616655b 100644--- a/docs/sandbox/troubleshooting.mdx+++ b/docs/sandbox/troubleshooting.mdx@@ -69,10 +69,18 @@ The deployed build output has no prepared artifact for this agent. This usually### `The prepared sandbox artifact ... was created with provider````text-The prepared sandbox artifact for agent node "..." was created with provider "just-bash", but this process selects provider "docker".+The prepared sandbox artifact for agent node "..." was created with provider "vercel", but this process selects provider "docker".```-The process that prepared the sandbox and the process that uses it selected different providers. `DefaultSandbox.environment()` [selects a provider in each process](/docs/sandbox/default#how-eve-selects-the-provider), so a build on a machine without Docker and a server with Docker disagree. Prepare the sandbox where the using process's provider is available: run `eve build` on that host, or restart `eve dev` locally. To make every process use the same provider, select it explicitly, for example with `DockerSandbox.environment()`.+The sandbox file selected one provider when eve prepared the sandbox and a different one in the process that uses it. This happens when the sandbox file chooses a provider by reading the host, for example with `process.env.VERCEL ? VercelSandbox.environment() : DockerSandbox.environment()`, and the build and runtime hosts differ. `DefaultSandbox.environment()` does not cause this, because it [records its choice when it prepares the sandbox](/docs/sandbox/default#the-build-records-the-choice). Select one provider explicitly, or use `DefaultSandbox.environment()`, then rebuild with `eve build`, or restart `eve dev` locally.++### `DefaultSandbox has no sandbox provider for this build`++```text+DefaultSandbox has no sandbox provider for this build: it did not run on Vercel, no Docker daemon was reachable, and production builds do not fall back to just-bash.+```++The production `eve build` ran outside Vercel without a reachable Docker daemon, so `DefaultSandbox` recorded no provider, and the first session that opens the sandbox fails. A `RUN eve build` step in a Dockerfile usually has no Docker daemon, even when the running container later mounts `/var/run/docker.sock`. Start Docker and run `eve build` again, deploy to Vercel, or select a provider explicitly in the sandbox file, for example `DockerSandbox.environment()` from `eve/sandbox/docker`. See [How eve selects the provider](/docs/sandbox/default#how-eve-selects-the-provider).### `Sandbox template ... is not available to this runtime`@@ -108,7 +116,15 @@ A session records which provider created its sandbox, and later turns resume thaThis session's sandbox was created by provider "just-bash", but the agent now selects provider "docker".```-The agent selects a different provider than the one that created this session's sandbox. With `DefaultSandbox`, this happens when Docker starts or stops between processes. eve cannot move a sandbox between providers. Start a new session, or restore the previous provider, for example by starting Docker again. In the `eve dev` terminal, `/new` starts a new session.+eve logs this warning when a session resumes on a build whose sandbox file selects a different provider than the one that created the session's sandbox, for example after you change providers or `DefaultSandbox` records a different choice in a new build. eve cannot move a sandbox between providers, so the session continues in a fresh sandbox from the current provider, without the old sandbox's files. eve does not delete the old sandbox. Remove it with the old provider's tooling, for example `docker rm` for a Docker container. To keep the session's files instead, restore the previous provider before the session resumes.++### `DefaultSandbox selected just-bash, which always allows network access`++```text+DefaultSandbox selected just-bash, which always allows network access and accepts only the "allow-all" network policy.+```++The sandbox passed a `networkPolicy` other than `"allow-all"` to `open()`, or called `setNetworkPolicy()`, while `DefaultSandbox` uses just-bash during `eve dev` or `eve eval` because Docker is not reachable. just-bash cannot restrict network access. Start Docker and restart `eve dev` so `DefaultSandbox` selects Docker, or select `VercelSandbox.environment()` or `DockerSandbox.environment()` explicitly.### `Invalid ... session state`@@ -139,7 +155,7 @@ The Docker sandbox provider requires Docker, but the `docker` CLI was not found.The Docker sandbox provider requires a running Docker daemon, but it is not reachable.```-Install and start Docker Desktop, OrbStack, Colima, or another runtime with a Docker-compatible `docker` CLI. To use another compatible CLI, such as Podman, set `EVE_DOCKER_PATH` to its path. If you do not need Docker specifically, use `DefaultSandbox.environment()` so eve selects a provider that the host supports.+Install and start Docker Desktop, OrbStack, Colima, or another runtime with a Docker-compatible `docker` CLI. To use another compatible CLI, such as Podman, set `EVE_DOCKER_PATH` to its path. If you do not need Docker specifically, use `DefaultSandbox.environment()`, which falls back to just-bash during `eve dev` and `eve eval`.### The just-bash package is missingdiff --git a/docs/sandbox/vercel.mdx b/docs/sandbox/vercel.mdxindex 9077782a9..e1d443a4e 100644--- a/docs/sandbox/vercel.mdx+++ b/docs/sandbox/vercel.mdx@@ -1,9 +1,9 @@---title: "Vercel Sandbox"-description: "Create snapshot-backed persistent sandboxes on Vercel."+description: "Create persistent sandboxes on Vercel, from a prepared snapshot when the environment has build-time setup."----`VercelSandbox.environment()` prepares a reusable Vercel Sandbox snapshot and creates persistent session sandboxes from its recorded snapshot ID.+`VercelSandbox.environment()` prepares a reusable Vercel Sandbox snapshot when the environment has build-time setup, and creates persistent session sandboxes from its recorded snapshot ID.```tsimport { defineSandbox } from "eve/sandbox";@@ -57,6 +57,8 @@ eve creates a temporary persistent Vercel Sandbox during build, installs the basWhen a live session sandbox does not exist, eve creates it directly from that snapshot ID. Runtime does not need to look up the temporary template Sandbox.+When the environment has no `prepare` callback, no managed workspace or skill files, and no `source`, a snapshot would contain only the base runtime. eve skips it: the build records no snapshot ID, and each new session sandbox starts from the image and installs the base runtime itself. A `source` always produces a snapshot, so sessions start from what the build captured instead of fetching the source again.+## Initialize after openInitialize session-specific state after `open()` and before returning the sandbox. This selector writes a configuration file into the persistent `/workspace` filesystem:diff --git a/e2e/fixtures/agent-tools-sandbox/agent/subagents/deny-all/sandbox.ts b/e2e/fixtures/agent-tools-sandbox/agent/subagents/deny-all/sandbox.tsindex 54aad554b..76126b896 100644--- a/e2e/fixtures/agent-tools-sandbox/agent/subagents/deny-all/sandbox.ts+++ b/e2e/fixtures/agent-tools-sandbox/agent/subagents/deny-all/sandbox.ts@@ -1,9 +1,5 @@-import { defineSandbox } from "eve/sandbox";-import { DockerSandbox } from "eve/sandbox/docker";-import { VercelSandbox } from "eve/sandbox/vercel";+import { DefaultSandbox, defineSandbox } from "eve/sandbox";-export const environment = process.env.VERCEL- ? VercelSandbox.environment()- : DockerSandbox.environment();+export const environment = DefaultSandbox.environment();export default defineSandbox(() => environment.open({ networkPolicy: "deny-all" }));diff --git a/packages/eve/src/execution/sandbox/bindings/docker-network.ts b/packages/eve/src/execution/sandbox/bindings/docker-network.tsindex 9cea272b1..091afe1bd 100644--- a/packages/eve/src/execution/sandbox/bindings/docker-network.ts+++ b/packages/eve/src/execution/sandbox/bindings/docker-network.ts@@ -3,15 +3,12 @@ import { expectDockerSuccess } from "#execution/sandbox/bindings/docker-utils.jsimport type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";/**- * Applies a coarse-grained run-time network policy by attaching or- * detaching the container's networks. Domain-level policies and- * credential brokering require the firewall on the Vercel provider.+ * Rejects a policy Docker cannot enforce, so a restrictive one never runs+ * with open egress instead.*/-export async function setDockerNetworkPolicy(- cli: DockerCli,- containerName: string,+export function assertDockerNetworkPolicy(policy: SandboxNetworkPolicy,-): Promise<void> {+): asserts policy is "allow-all" | "deny-all" {if (policy !== "allow-all" && policy !== "deny-all") {throw new Error('The local Docker sandbox provider supports only the "allow-all" and "deny-all" network ' +@@ -19,6 +16,19 @@ export async function setDockerNetworkPolicy("(VercelSandbox).",);}+}++/**+ * Applies a coarse-grained run-time network policy by attaching or+ * detaching the container's networks. Domain-level policies and+ * credential brokering require the firewall on the Vercel provider.+ */+export async function setDockerNetworkPolicy(+ cli: DockerCli,+ containerName: string,+ policy: SandboxNetworkPolicy,+): Promise<void> {+ assertDockerNetworkPolicy(policy);const inspect = await cli.run(["container",diff --git a/packages/eve/src/execution/sandbox/bindings/docker.test.ts b/packages/eve/src/execution/sandbox/bindings/docker.test.tsindex 973ba827f..af23d70c7 100644--- a/packages/eve/src/execution/sandbox/bindings/docker.test.ts+++ b/packages/eve/src/execution/sandbox/bindings/docker.test.ts@@ -137,3 +137,29 @@ describe("Docker sandbox session identity", () => {]);});});++describe("Docker sandbox network policy", () => {+ it("rejects a domain allow-list at open before creating a container", async () => {+ const run = vi.fn<DockerCli["run"]>();+ const provider = createSandboxProviderHarness(+ createDockerSandboxProvider(undefined, {+ run,+ stream() {+ throw new Error("stream is not used by this test");+ },+ }),+ {},+ { preparedArtifact: () => ({ imageReference: "image-a" }) },+ );++ await expect(+ provider.start({+ appRoot: "/tmp/eve-app",+ // DefaultSandbox forwards the shared network policy type unchanged.+ options: { networkPolicy: { allow: ["example.com"] } } as never,+ sandboxName: "session-key",+ }),+ ).rejects.toThrow(/supports only the "allow-all" and "deny-all"/);+ expect(run).not.toHaveBeenCalled();+ });+});diff --git a/packages/eve/src/execution/sandbox/bindings/docker.ts b/packages/eve/src/execution/sandbox/bindings/docker.tsindex d66237cdc..724041d83 100644--- a/packages/eve/src/execution/sandbox/bindings/docker.ts+++ b/packages/eve/src/execution/sandbox/bindings/docker.ts@@ -16,7 +16,10 @@ import {createDockerCli,type DockerCli,} from "#execution/sandbox/bindings/docker-cli.js";-import { setDockerNetworkPolicy } from "#execution/sandbox/bindings/docker-network.js";+import {+ assertDockerNetworkPolicy,+ setDockerNetworkPolicy,+} from "#execution/sandbox/bindings/docker-network.js";import {createDockerSandboxOptionsHash,resolveDockerSandboxOptions,@@ -342,6 +345,10 @@ export function createDockerSandboxProvider(return await openDockerSession(context, undefined, artifactValue, state.containerName, false);},async start(context, openOptions, artifactValue) {+ // Callers that widen the option type, such as DefaultSandbox, reach here unchecked.+ if (openOptions?.networkPolicy !== undefined) {+ assertDockerNetworkPolicy(openOptions.networkPolicy);+ }const containerName = dockerSessionName(context);return {handle: await openDockerSession(context, openOptions, artifactValue, containerName, true),diff --git a/packages/eve/src/execution/sandbox/bindings/vercel.test.ts b/packages/eve/src/execution/sandbox/bindings/vercel.test.tsindex b188e70bb..e929bdde2 100644--- a/packages/eve/src/execution/sandbox/bindings/vercel.test.ts+++ b/packages/eve/src/execution/sandbox/bindings/vercel.test.ts@@ -208,8 +208,12 @@ async function templateKeyOf(build: (module: object) => Promise<unknown>): Promireturn name;}+/** An environment with preparation, which Vercel captures in a template snapshot. */function createVercelSandbox(input: Parameters<typeof createVercelImplementation>[0] = {}) {- return createSandboxProviderHarness(createVercelImplementation(input), {});+ return createSandboxProviderHarness(+ createVercelImplementation({ prepare: async () => {}, ...input }),+ {},+ );}function createTestVercelSandbox(input: Parameters<typeof createVercelImplementation>[0] = {}) {@@ -859,11 +863,13 @@ describe("createVercelSandbox", () => {});describe("shared templates", () => {- const buildWith = (prepare?: () => Promise<void> | void) => async (sandboxModule: object) =>- await createTestVercelSandbox({- loadSandboxModule: async () => sandboxModule as never,- prepare,- }).prepare({ appRoot: "/tmp/test-app-root" });+ const buildWith =+ (prepare: () => Promise<void> | void = async () => {}) =>+ async (sandboxModule: object) =>+ await createTestVercelSandbox({+ loadSandboxModule: async () => sandboxModule as never,+ prepare,+ }).prepare({ appRoot: "/tmp/test-app-root" });/** The build-private sandboxes: everything a build created except the template pointer. */const privateSandboxes = (fake: ReturnType<typeof createFakeVercelProvider>) =>@@ -1156,6 +1162,40 @@ describe("createVercelSandbox", () => {});});+ it("captures a template only when preparation, managed files, or an authored source need one", async () => {+ const prepareWith = async (+ input: Parameters<typeof createVercelImplementation>[0],+ workspace: { content: string; relativePath: string }[] = [],+ ) => {+ const create = vi.fn(async (options: { name: string }) => createMockSandbox(options));+ const provider = createSandboxProviderHarness(+ createVercelImplementation({+ ...input,+ createSandbox: async ({ createOptions }) => (await create(createOptions)) as never,+ loadSandboxModule: async () =>+ ({ Sandbox: { create, get: vi.fn().mockResolvedValue(null) } }) as never,+ }),+ {},+ );+ return {+ artifact: await provider.prepare({ appRoot: "/tmp/test-app-root", workspace }),+ create,+ };+ };++ const empty = await prepareWith({ createOptions: { image: "example.test/agent:1" } });+ expect(empty.artifact).toEqual({});+ expect(empty.create).not.toHaveBeenCalled();++ const sourced = await prepareWith({+ createOptions: { source: { snapshotId: "author-snap", type: "snapshot" } },+ });+ const seeded = await prepareWith({}, [{ content: "notes", relativePath: "notes.md" }]);+ for (const { artifact } of [sourced, seeded]) {+ expect(artifact).toEqual({ snapshotId: expect.any(String) });+ }+ });+it("reports an unavailable prepared snapshot without mutating the build template", async () => {const snapshotExpiredError = Object.assign(new Error("Vercel sandbox create API returned 410"),@@ -1293,11 +1333,15 @@ describe("createVercelSandbox", () => {await expect(handle.onSandboxStop()).rejects.toThrow("provider unreachable");});- it("applies the open-time policy after template-less base setup", async () => {+ it.each([+ ["open()", {}, { networkPolicy: "deny-all" as const }],+ ["the environment", { networkPolicy: "deny-all" as const }, {}],+ ])("applies the policy from %s after template-less base setup", async (_, environment, open) => {const sessionSandbox = createMockSandbox({ name: "session" });const create = vi.fn().mockResolvedValue(sessionSandbox);const provider = createSandboxProviderHarness(createVercelImplementation({+ createOptions: environment,createSandbox: async ({ createOptions }) => {await create(createOptions);return sessionSandbox as never;@@ -1305,7 +1349,7 @@ describe("createVercelSandbox", () => {loadSandboxModule: async () =>({ Sandbox: { create, get: vi.fn().mockResolvedValue(null) } }) as never,}),- { networkPolicy: "deny-all" },+ open,{ preparedArtifact: () => ({}) },);diff --git a/packages/eve/src/execution/sandbox/bindings/vercel.ts b/packages/eve/src/execution/sandbox/bindings/vercel.tsindex 653ae5788..28116f40e 100644--- a/packages/eve/src/execution/sandbox/bindings/vercel.ts+++ b/packages/eve/src/execution/sandbox/bindings/vercel.ts@@ -111,7 +111,6 @@ interface CreateVercelSandboxInput {readonly loadDeleteSandboxModule?: () => Promise<VercelModule>;readonly loadSandboxModule?: () => Promise<VercelModule>;readonly prepare?: (sandbox: SandboxSession) => Promise<void> | void;- readonly skipEmptyPreparation?: boolean;}export function createVercelSandbox(@@ -174,13 +173,12 @@ export function createVercelSandbox(loadDeleteSandboxModule,session,});- if (- session.created &&- artifact.snapshotId === undefined &&- runtimeOptions.networkPolicy !== undefined- ) {+ // Template-less sessions run base setup with open egress, so the policy+ // from open() or else the environment applies only once it finishes.+ const networkPolicy = runtimeOptions.networkPolicy ?? createOptions.networkPolicy;+ if (session.created && artifact.snapshotId === undefined && networkPolicy !== undefined) {try {- await applyInitialVercelNetworkPolicy(session.sandbox, runtimeOptions.networkPolicy);+ await applyInitialVercelNetworkPolicy(session.sandbox, networkPolicy);} catch (error) {try {await deleteVercelSandbox({@@ -229,10 +227,13 @@ export function createVercelSandbox(},async prepare(context) {const seedFiles = providerResourceTargetFiles(context.resources);+ // Without inputs a snapshot only repeats the base setup every session+ // runs anyway. An authored `source` keeps one, so sessions start from+ // the build's capture instead of fetching the source again.if (- input.skipEmptyPreparation === true &&input.prepare === undefined &&- seedFiles.length === 0+ seedFiles.length === 0 &&+ createOptions.source === undefined)return {};const templateKey = `eve-sbx-tpl-vercel-${createSandboxProviderIdentity({diff --git a/packages/eve/src/execution/sandbox/ensure.test.ts b/packages/eve/src/execution/sandbox/ensure.test.tsindex 3f9c626c6..8dbd814cd 100644--- a/packages/eve/src/execution/sandbox/ensure.test.ts+++ b/packages/eve/src/execution/sandbox/ensure.test.ts@@ -244,6 +244,27 @@ describe("ensureSandboxAccess", () => {});});+ it.each([+ ["another provider", { providerName: "other", stateProtocolVersion: 1 }],+ ["another state protocol", { providerName: "test", stateProtocolVersion: 2 }],+ ])("starts a fresh sandbox for state %s recorded", async (_, record) => {+ const setup = vi.fn();+ const value = fixture(setup);+ const { access } = await open(value.registry, "session-1", {+ session: { ...record, state: { key: "old" } },+ });+ expect(setup).toHaveBeenCalledOnce();+ expect(value.start).toHaveBeenCalledOnce();+ await expect(access.captureState()).resolves.toEqual({+ session: {+ generation: expect.any(String),+ 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"));diff --git a/packages/eve/src/execution/sandbox/ensure.ts b/packages/eve/src/execution/sandbox/ensure.tsindex 5929b33a6..9b73fec82 100644--- a/packages/eve/src/execution/sandbox/ensure.ts+++ b/packages/eve/src/execution/sandbox/ensure.ts@@ -21,7 +21,8 @@ import {import { loadSandboxPreparedArtifact } from "#runtime/sandbox/prepared-artifacts.js";import { owningSandboxDefinition, type RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";import {- isRetiredSandboxSessionState,+ getSessionEndWithArtifact,+ resolvePersistedSandboxSessionState,type SandboxAccess,type SandboxSessionEndReason,type SandboxSessionState,@@ -94,10 +95,16 @@ const log = createLogger("execution.sandbox");export async function ensureSandboxAccess(input: EnsureSandboxAccessInput,): Promise<EnsuredSandboxAccess> {+ // Production always registers a sandbox; test runtimes without one cast a null registry.+ const registered = input.registry.sandbox;+ const persistedOwner = registered === null ? undefined : owningSandboxDefinition(registered);// A retired record cannot resume, so let the selector start a fresh sandbox.- const session = input.state?.session ?? null;- let persisted: SandboxSessionState | null =- session === null || isRetiredSandboxSessionState(session) ? null : session;+ let persisted = resolvePersistedSandboxSessionState(+ input.state?.session,+ persistedOwner?.kind === "independent"+ ? getSandboxEnvironmentRuntime(persistedOwner.environment)+ : undefined,+ );let opened: OpenedSandbox | undefined;let opening: Promise<SandboxProviderHandle> | undefined;let requiring: Promise<SandboxProviderHandle> | undefined;@@ -110,8 +117,6 @@ export async function ensureSandboxAccess(const appRoot =getRuntimeCompiledArtifactsSandboxAppRoot(input.compiledArtifactsSource) ?? process.cwd();const captured = (): SandboxState => ({ session: persisted });- const registered = input.registry.sandbox;- // Production always registers a sandbox; test runtimes without one cast a null registry.if (registered === null) {return {async captureState() {@@ -236,15 +241,16 @@ export async function ensureSandboxAccess(async function resumePersisted(context: SandboxProviderSessionContext) {if (persisted === null) throw new Error("Sandbox session state is missing.");const provider = getSandboxEnvironmentRuntime(activeDefinition().environment);+ // State another provider or protocol recorded cannot resume here, for example+ // after the app switches providers or rolls back eve, so start a fresh sandbox.if (persisted.providerName !== provider.providerName) {- throw new Error(+ throw new SandboxSessionGoneError(`This session's sandbox was created by provider "${persisted.providerName}", but the agent now selects provider "${provider.providerName}". ` +- "eve cannot move a sandbox between providers. Start a new session, or restore the previous provider. " +- "With DefaultSandbox, the provider can change when Docker starts or stops between processes.",+ "eve cannot move a sandbox between providers, so the session continues in a fresh sandbox without the old sandbox's files.",);}if (persisted.stateProtocolVersion !== provider.stateProtocolVersion) {- throw new Error(+ throw new SandboxSessionGoneError(`Sandbox session state protocol ${persisted.stateProtocolVersion} is incompatible with provider "${provider.providerName}" protocol ${provider.stateProtocolVersion}.`,);}@@ -405,9 +411,18 @@ export async function ensureSandboxAccess(persisted.stateProtocolVersion === provider.stateProtocolVersion? persisted.state: null;- await provider.implementation.onSessionEnd(providerContext("sandbox-cleanup"), state, {- reason,- });+ const context = providerContext("sandbox-cleanup");+ const endWithArtifact = getSessionEndWithArtifact(provider.implementation);+ if (endWithArtifact === undefined) {+ await provider.implementation.onSessionEnd(context, state, { reason });+ } else {+ const artifact = await loadSandboxPreparedArtifact({+ compiledArtifactsSource: input.compiledArtifactsSource,+ nodeId: registered.inheritance?.nodeId ?? input.nodeId,+ providerName: provider.providerName,+ });+ await endWithArtifact(context, state, { artifact, reason });+ }forgetHandle();persisted = null;},diff --git a/packages/eve/src/execution/session/handoff-steps.test.ts b/packages/eve/src/execution/session/handoff-steps.test.tsindex 75042c6b9..a38375c4e 100644--- a/packages/eve/src/execution/session/handoff-steps.test.ts+++ b/packages/eve/src/execution/session/handoff-steps.test.ts@@ -14,6 +14,7 @@ import {import { positionState } from "#internal/testing/session-machine.js";import { captureLogRecords } from "#internal/testing/log-records.js";import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";+import { DefaultSandbox } from "#sandbox/providers/default.js";import { sessionInboxHookToken } from "#execution/session-inbox/address.js";const deserializeContextMock = vi.fn();@@ -114,6 +115,31 @@ describe("prepareSuccessorStep", () => {await expect(validate(createCheckpoint())).resolves.toEqual({ kind: "valid" });});+ it("accepts a sandbox record DefaultSandbox saved under the provider it picked", async () => {+ const environment = DefaultSandbox.environment();+ deserializeContextMock.mockResolvedValue({+ require: () => ({+ graph: {+ root: {+ sandboxRegistry: { sandbox: { definition: { environment, kind: "independent" } } },+ },+ },+ nodeId: "__root__",+ }),+ });+ readDurableSessionMock.mockReturnValue({+ sandboxState: {+ session: {+ providerName: "vercel",+ state: { sandboxName: "eve-sbx-vercel-old", version: 3 },+ stateProtocolVersion: 1,+ },+ },+ });++ await expect(validate(createCheckpoint())).resolves.toEqual({ kind: "valid" });+ });+it("rejects an incompatible workflow tool run with the current checkpoint version", async () => {deserializeContextMock.mockResolvedValue({ require: vi.fn() });readDurableSessionMock.mockReturnValue({diff --git a/packages/eve/src/execution/session/handoff-steps.ts b/packages/eve/src/execution/session/handoff-steps.tsindex 130d5d310..df1319789 100644--- a/packages/eve/src/execution/session/handoff-steps.ts+++ b/packages/eve/src/execution/session/handoff-steps.ts@@ -42,7 +42,10 @@ import {} from "#execution/eve-workflow-attributes.js";import { getResolvedRuntimeAgentNode } from "#runtime/graph.js";import { owningSandboxDefinition } from "#runtime/sandbox/registry.js";-import { isRetiredSandboxSessionState } from "#sandbox/state.js";+import {+ isRetiredSandboxSessionState,+ resolvePersistedSandboxSessionState,+} from "#sandbox/state.js";import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";import { getSandboxEnvironmentRuntime } from "#shared/sandbox-environment.js";import { walkCauseChain } from "#shared/errors.js";@@ -206,9 +209,10 @@ export async function prepareSuccessorStep(input: {throw new Error("Session checkpoint sandbox has no resolved provider.");}const provider = getSandboxEnvironmentRuntime(definition.environment);+ const resolved = resolvePersistedSandboxSessionState(sandboxState, provider);if (- sandboxState.providerName !== provider.providerName ||- sandboxState.stateProtocolVersion !== provider.stateProtocolVersion+ resolved?.providerName !== provider.providerName ||+ resolved.stateProtocolVersion !== provider.stateProtocolVersion) {throw new Error("Session checkpoint sandbox provider state is incompatible.");}diff --git a/packages/eve/src/execution/tool-session/sandbox.ts b/packages/eve/src/execution/tool-session/sandbox.tsindex 36c56bcbd..e398973ee 100644--- a/packages/eve/src/execution/tool-session/sandbox.ts+++ b/packages/eve/src/execution/tool-session/sandbox.ts@@ -36,6 +36,13 @@ export function withToolSessionSandboxes<Implementation extends object>(return implementation;}+/** What a binding marked with `withToolSessionSandboxes` supports, or `undefined` when unmarked. */+export function getToolSessionSandboxSupport(+ implementation: object,+): ToolSessionSandboxSupport | undefined {+ return supported.get(implementation);+}+/** Raised when a keyed tool session opens a sandbox on a provider that cannot keep it. */export class ToolSessionSandboxUnsupportedError extends Error {constructor(providerName: string) {diff --git a/packages/eve/src/internal/nitro/host/compiled-sandbox-provider-prune-plugin.test.ts b/packages/eve/src/internal/nitro/host/compiled-sandbox-provider-prune-plugin.test.tsindex 90e9001f6..dc230253b 100644--- a/packages/eve/src/internal/nitro/host/compiled-sandbox-provider-prune-plugin.test.ts+++ b/packages/eve/src/internal/nitro/host/compiled-sandbox-provider-prune-plugin.test.ts@@ -3,15 +3,6 @@ import { describe, expect, it } from "vitest";import { createCompiledSandboxProviderPrunePlugin } from "./compiled-sandbox-provider-prune-plugin.js";describe("createCompiledSandboxProviderPrunePlugin", () => {- it("replaces framework default selection with the hosted Vercel provider", () => {- const plugin = createCompiledSandboxProviderPrunePlugin();- const source = plugin.load?.("/repo/packages/eve/src/sandbox/providers/default.ts");-- expect(source).toContain('DefaultSandbox = { name: "default", environment }');- expect(source).toContain("options.vercel");- expect(source).toContain("prepare: options.prepare");- });-it("replaces local provider constructors with hosted stubs", () => {const plugin = createCompiledSandboxProviderPrunePlugin();const source = plugin.load?.("/repo/packages/eve/src/sandbox/providers/docker.ts");diff --git a/packages/eve/src/internal/nitro/host/compiled-sandbox-provider-prune-plugin.ts b/packages/eve/src/internal/nitro/host/compiled-sandbox-provider-prune-plugin.tsindex 51230c4a0..1b440d0f6 100644--- a/packages/eve/src/internal/nitro/host/compiled-sandbox-provider-prune-plugin.ts+++ b/packages/eve/src/internal/nitro/host/compiled-sandbox-provider-prune-plugin.ts@@ -1,8 +1,6 @@-const PRUNED_DEFAULT_SANDBOX_MODULE_ID = "\0eve-pruned-default-sandbox-provider";const PRUNED_LOCAL_SANDBOX_MODULE_ID = "\0eve-pruned-local-sandbox-providers";const PRUNED_LOCAL_SANDBOX_PROVIDER_MODULE_ID = "\0eve-pruned-local-sandbox-provider-constructors";const PRUNED_OPTIONAL_ENGINE_INSTALL_MODULE_ID = "\0eve-pruned-optional-engine-install";-const DEFAULT_PROVIDER_SOURCE_RE = /(?:^|[/\\#])sandbox[/\\]providers[/\\]default\.(?:js|ts)$/;const LOCAL_BINDING_SOURCE_RE = /[/\\]bindings[/\\](?:docker|just-bash|local)\.(?:js|ts)$/;const LOCAL_PROVIDER_SOURCE_RE =/(?:^|[/\\#])sandbox[/\\]providers[/\\](?:docker|just-bash)\.(?:js|ts)$/;@@ -24,6 +22,8 @@ interface BundlerPluginShape {* (Docker, just-bash) from hosted Nitro server bundles.* Stubs both the aggregate local facade and individual provider bindings so* framework default selection cannot retain local engine implementations.+ * `DefaultSandbox` stays real: on Vercel its build records Vercel Sandbox, so+ * it never constructs a stubbed local provider.*/export function createCompiledSandboxProviderPrunePlugin(): BundlerPluginShape {return {@@ -31,18 +31,6 @@ export function createCompiledSandboxProviderPrunePlugin(): BundlerPluginShape {name: "eve-hosted-sandbox-provider-prune",load(id) {const sourcePath = id.split(/[?#]/u, 1)[0] ?? id;- if (id === PRUNED_DEFAULT_SANDBOX_MODULE_ID || DEFAULT_PROVIDER_SOURCE_RE.test(sourcePath)) {- return [- 'import { createDefaultVercelEnvironment } from "#sandbox/providers/vercel.js";',- "function environment(options = {}) {",- " const vercelOptions = Object.assign({}, options.vercel, options.prepare === undefined ? {} : { prepare: options.prepare });",- " return createDefaultVercelEnvironment(vercelOptions);",- "}",- 'export const DefaultSandbox = { name: "default", environment };',- 'export function defineDefaultSandboxProvider() { return { name: "default", environment }; }',- "",- ].join("\n");- }if (id === PRUNED_OPTIONAL_ENGINE_INSTALL_MODULE_ID ||OPTIONAL_ENGINE_INSTALL_SOURCE_RE.test(sourcePath)@@ -95,7 +83,6 @@ export function createCompiledSandboxProviderPrunePlugin(): BundlerPluginShape {},resolveId(source) {const sourcePath = source.split(/[?#]/u, 1)[0] ?? source;- if (DEFAULT_PROVIDER_SOURCE_RE.test(sourcePath)) return PRUNED_DEFAULT_SANDBOX_MODULE_ID;if (LOCAL_PROVIDER_SOURCE_RE.test(sourcePath)) {return PRUNED_LOCAL_SANDBOX_PROVIDER_MODULE_ID;}diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.tsindex 999c941df..c9b4dfada 100644--- a/packages/eve/src/internal/nitro/host/create-application-nitro.ts+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.ts@@ -169,9 +169,8 @@ function collectConfiguredSandboxProviderNames(manifest: CompiledAgentManifest):/*** Hosted Vercel builds can prune local sandbox providers only when the- * app did not explicitly configure one. Omitted backends resolve through- * `DefaultSandbox.environment()`, which selects Vercel on hosted Vercel and never- * needs local runtime code there.+ * app did not explicitly configure one. `DefaultSandbox.environment()` records+ * Vercel Sandbox when built on Vercel, so it never needs local runtime code there.*/export function shouldPruneLocalSandboxProviders(input: {readonly configuredBackendNames: ReadonlySet<string>;diff --git a/packages/eve/src/public/sandbox/index.ts b/packages/eve/src/public/sandbox/index.tsindex 19a8ce546..8d7fa1c0a 100644--- a/packages/eve/src/public/sandbox/index.ts+++ b/packages/eve/src/public/sandbox/index.ts@@ -20,7 +20,11 @@ export {type SandboxWriteTextFileOptions,} from "#public/definitions/sandbox.js";export { DefaultSandbox } from "#sandbox/providers/default.js";-export type { DefaultSandboxEnvironmentOptions } from "#sandbox/providers/default.js";+export type {+ DefaultSandboxEnvironmentOptions,+ DefaultSandboxRuntimeOptions,+ DefaultSandboxSession,+} from "#sandbox/providers/default.js";export type {SandboxNetworkOptions,SandboxNetworkPolicy,diff --git a/packages/eve/src/runtime/sandbox/prepared-artifacts.ts b/packages/eve/src/runtime/sandbox/prepared-artifacts.tsindex 8fccb92b3..cf0d04bee 100644--- a/packages/eve/src/runtime/sandbox/prepared-artifacts.ts+++ b/packages/eve/src/runtime/sandbox/prepared-artifacts.ts@@ -51,8 +51,8 @@ export async function loadSandboxPreparedArtifact(input: {if (entry !== undefined && entry.providerName !== input.providerName) {throw new Error(`The prepared sandbox artifact for agent node "${input.nodeId}" was created with provider "${entry.providerName}", but this process selects provider "${input.providerName}". ` +- "DefaultSandbox selects a provider separately in each process, so processes on hosts with different Docker availability can disagree. " +- "Prepare the sandbox where this process's provider is available (run `eve build` on that host, or restart `eve dev`), or select a provider explicitly in the sandbox file.",+ "The sandbox file must select the same provider during the build and at runtime, so a selection that reads the host, such as `process.env` or Docker availability, can disagree. " ++ "Select one provider explicitly, or use DefaultSandbox, which records its choice when the sandbox is prepared. Then rebuild with `eve build`, or restart `eve dev`.",);}return entry?.artifact;diff --git a/packages/eve/src/sandbox/providers.test.ts b/packages/eve/src/sandbox/providers.test.tsindex 5caad8804..c019993f5 100644--- a/packages/eve/src/sandbox/providers.test.ts+++ b/packages/eve/src/sandbox/providers.test.ts@@ -1,18 +1,10 @@import type { DockerSandboxSession } from "#public/sandbox/docker.js";import { describe, expect, expectTypeOf, it } from "vitest";-import { defineDefaultSandboxProvider } from "#sandbox/providers/default.js";import { DockerSandbox, VercelSandbox } from "#sandbox/providers.js";import type { RuntimeSandboxSessionFor } from "#shared/sandbox-session.js";describe("sandbox providers", () => {- it("implements default selection through the provider contract", () => {- const environment = defineDefaultSandboxProvider({- isDeployedOnVercel: () => true,- isDockerAvailable: () => false,- }).environment();- expect(environment.provider).toBe("vercel");- });it("exposes image and Dockerfile constructors only for local image providers", () => {expect(DockerSandbox.image("example.test/agent@sha256:abc").provider).toBe("docker");expect(DockerSandbox.dockerfile().provider).toBe("docker");diff --git a/packages/eve/src/sandbox/providers/default.integration.test.ts b/packages/eve/src/sandbox/providers/default.integration.test.tsnew file mode 100644index 000000000..ec6569fe9--- /dev/null+++ b/packages/eve/src/sandbox/providers/default.integration.test.ts@@ -0,0 +1,265 @@+import { mkdir } from "node:fs/promises";++import { afterEach, describe, expect, it, vi } from "vitest";++import { shutdownActiveSandboxHandles } from "#execution/sandbox/active-handles.js";+import { isLinuxDockerDaemonAvailableSync } from "#execution/sandbox/bindings/local.js";+import { ensureSandboxAccess } from "#execution/sandbox/ensure.js";+import { createSandboxProviderFiles } from "#execution/sandbox/provider-files.js";+import { createSandboxProviderHost } from "#execution/sandbox/provider-host.js";+import { resolveSandboxCacheDirectory } from "#internal/application/paths.js";+import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";+import { defineSandbox } from "#public/definitions/sandbox.js";+import { createDiskRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";+import { resolveRuntimeCompilerArtifactPaths } from "#runtime/loaders/artifact-paths.js";+import { writeSandboxPreparedArtifactsManifest } from "#runtime/sandbox/prepared-artifacts.js";+import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";+import { DefaultSandbox, type DefaultSandboxSession } from "#sandbox/providers/default.js";+import type { SandboxState } from "#sandbox/state.js";+import { getSandboxEnvironmentRuntime, type SandboxSelector } from "#shared/sandbox-environment.js";+import { createSandboxProviderResources } from "#shared/sandbox-provider.js";++vi.mock("#execution/sandbox/bindings/local.js", async (importOriginal) => ({+ ...(await importOriginal<typeof import("#execution/sandbox/bindings/local.js")>()),+ isLinuxDockerDaemonAvailableSync: vi.fn(() => false),+}));++const createScratchDirectory = useTemporaryDirectories();++afterEach(async () => {+ await shutdownActiveSandboxHandles();+ vi.unstubAllEnvs();+ vi.mocked(isLinuxDockerDaemonAvailableSync).mockClear();+});++/** Prepares the environment the way the build does and records the artifact. */+async function build(environment: ReturnType<typeof DefaultSandbox.environment>, dev: boolean) {+ const appRoot = await createScratchDirectory("eve-default-sandbox-");+ const log = vi.fn();+ vi.stubEnv("VERCEL", "");+ vi.stubEnv("EVE_DEV", dev ? "1" : "");+ const artifact = await getSandboxEnvironmentRuntime(environment).implementation.prepare({+ files: createSandboxProviderFiles(`${appRoot}/agent/sandbox`),+ host: createSandboxProviderHost(appRoot),+ log,+ resources: createSandboxProviderResources({}),+ sourceRevision: "revision",+ storagePath: resolveSandboxCacheDirectory(appRoot),+ });+ const { compileDirectoryPath } = resolveRuntimeCompilerArtifactPaths(appRoot);+ await mkdir(compileDirectoryPath, { recursive: true });+ await writeSandboxPreparedArtifactsManifest({+ compileDirectoryPath,+ entries: [{ artifact, nodeId: "__root__", providerName: "default" }],+ });+ vi.unstubAllEnvs();+ return { appRoot, artifact, log };+}++async function access(input: {+ readonly appRoot: string;+ readonly environment: ReturnType<typeof DefaultSandbox.environment>;+ readonly selector: SandboxSelector;+ readonly state?: SandboxState;+}) {+ const registry: RuntimeSandboxRegistry = {+ sandbox: {+ definition: {+ environment: input.environment,+ kind: "independent",+ logicalPath: "sandbox.ts",+ revisionHash: "revision",+ selector: input.selector,+ sourceId: "sandbox",+ sourceKind: "module",+ },+ workspaceResourceRoot: { logicalPath: "", rootEntries: [] },+ },+ };+ return await ensureSandboxAccess({+ compiledArtifactsSource: createDiskRuntimeCompiledArtifactsSource(input.appRoot),+ nodeId: "__root__",+ registry,+ sessionId: "session-1",+ state: input.state ?? null,+ });+}++describe("DefaultSandbox", () => {+ it("uses the provider its build recorded without probing the runtime host", async () => {+ const environment = DefaultSandbox.environment();+ const { appRoot, artifact } = await build(environment, true);+ expect(artifact).toMatchObject({ provider: "just-bash" });+ vi.mocked(isLinuxDockerDaemonAvailableSync).mockClear();++ // A runtime that probed the host would now select Vercel Sandbox.+ vi.stubEnv("VERCEL", "1");+ const sandbox = await access({+ appRoot,+ environment,+ selector: defineSandbox(() => environment.open()),+ });+ await expect((await sandbox.get())?.run({ command: "echo ready" })).resolves.toMatchObject({+ exitCode: 0,+ stdout: "ready\n",+ });+ await expect(sandbox.captureState()).resolves.toMatchObject({+ session: { providerName: "default", state: { provider: "just-bash" } },+ });+ expect(isLinuxDockerDaemonAvailableSync).not.toHaveBeenCalled();+ });++ it("builds for production without Vercel or Docker and fails at open with guidance", async () => {+ const environment = DefaultSandbox.environment();+ const { appRoot, artifact, log } = await build(environment, false);+ expect(artifact).toEqual({ provider: null });+ expect(log).toHaveBeenCalledWith(expect.stringContaining("do not fall back to just-bash"));++ const sandbox = await access({+ appRoot,+ environment,+ selector: defineSandbox(() => environment.open()),+ });+ await expect(sandbox.get()).rejects.toThrow(+ /Start Docker and rebuild, deploy to Vercel, or select a provider explicitly/,+ );+ });++ it("rejects network policies that just-bash cannot apply", async () => {+ const environment = DefaultSandbox.environment();+ const { appRoot } = await build(environment, true);++ const denied = await access({+ appRoot,+ environment,+ selector: defineSandbox(() => environment.open({ networkPolicy: "deny-all" })),+ });+ await expect(denied.get()).rejects.toThrow(/just-bash, which always allows network access/);++ let opened: DefaultSandboxSession | undefined;+ const allowed = await access({+ appRoot,+ environment,+ selector: defineSandbox(async () => (opened = await environment.open())),+ });+ await allowed.get();+ await expect(opened?.setNetworkPolicy("allow-all")).resolves.toBeUndefined();+ await expect(opened?.setNetworkPolicy("deny-all")).rejects.toThrow(/just-bash/);+ });++ it("ends a sandbox no checkpoint recorded through the provider its build selected", async () => {+ const environment = DefaultSandbox.environment();+ const { appRoot } = await build(environment, true);+ const selector = defineSandbox(() => environment.open());+ const opened = await access({ appRoot, environment, selector });+ await (await opened.get())?.writeTextFile({ content: "kept", path: "marker.txt" });+ await opened.stop();++ await (await access({ appRoot, environment, selector })).end("completed");++ const reopened = await access({ appRoot, environment, selector });+ await expect(+ (await reopened.get())?.run({ command: "test -f marker.txt" }),+ ).resolves.toMatchObject({ exitCode: 1 });+ });++ describe("sessions saved before DefaultSandbox recorded its own state", () => {+ it("resumes the sandbox of the provider it picked", async () => {+ const environment = DefaultSandbox.environment();+ const { appRoot } = await build(environment, true);+ const first = await access({+ appRoot,+ environment,+ selector: defineSandbox(() => environment.open()),+ });+ await (await first.get())?.writeTextFile({ content: "kept", path: "marker.txt" });+ const recorded = (await first.captureState()).session?.state;+ await first.stop();+ if (typeof recorded !== "object" || recorded === null || !("state" in recorded)) {+ throw new Error("Expected DefaultSandbox session state.");+ }++ const selector = vi.fn(() => environment.open());+ const resumed = await access({+ appRoot,+ environment,+ selector: defineSandbox(selector),+ state: {+ session: {+ generation: "generation-1",+ providerName: "just-bash",+ state: recorded.state,+ stateProtocolVersion: 1,+ },+ },+ });++ await expect((await resumed.get())?.readTextFile({ path: "marker.txt" })).resolves.toBe(+ "kept",+ );+ expect(selector).not.toHaveBeenCalled();+ await expect(resumed.captureState()).resolves.toEqual({+ session: {+ generation: "generation-1",+ providerName: "default",+ state: recorded,+ stateProtocolVersion: 1,+ },+ });+ });++ it("starts a fresh sandbox when its provider no longer speaks the recorded protocol", async () => {+ const environment = DefaultSandbox.environment();+ const { appRoot } = await build(environment, true);+ const first = await access({+ appRoot,+ environment,+ selector: defineSandbox(() => environment.open()),+ });+ await first.get();+ const recorded = (await first.captureState()).session?.state;+ await first.stop();+ if (typeof recorded !== "object" || recorded === null || !("state" in recorded)) {+ throw new Error("Expected DefaultSandbox session state.");+ }++ const selector = vi.fn(() => environment.open());+ const sandbox = await access({+ appRoot,+ environment,+ selector: defineSandbox(selector),+ state: {+ session: { providerName: "just-bash", state: recorded.state, stateProtocolVersion: 2 },+ },+ });++ await expect(sandbox.get()).resolves.toBeTruthy();+ expect(selector).toHaveBeenCalledOnce();+ });++ it("starts a fresh sandbox when the build selected another provider", async () => {+ const environment = DefaultSandbox.environment();+ const { appRoot } = await build(environment, true);+ const selector = vi.fn(() => environment.open());++ const sandbox = await access({+ appRoot,+ environment,+ selector: defineSandbox(selector),+ state: {+ session: {+ providerName: "docker",+ state: { containerName: "eve-sbx-old", version: 2 },+ stateProtocolVersion: 1,+ },+ },+ });++ await expect(sandbox.get()).resolves.toBeTruthy();+ expect(selector).toHaveBeenCalledOnce();+ await expect(sandbox.captureState()).resolves.toMatchObject({+ session: { providerName: "default", state: { provider: "just-bash" } },+ });+ });+ });+});diff --git a/packages/eve/src/sandbox/providers/default.ts b/packages/eve/src/sandbox/providers/default.tsindex e25555964..53455e36a 100644--- a/packages/eve/src/sandbox/providers/default.ts+++ b/packages/eve/src/sandbox/providers/default.ts@@ -1,11 +1,36 @@import { isLinuxDockerDaemonAvailableSync } from "#execution/sandbox/bindings/local.js";+import { isToolSessionId } from "#execution/tool-session/id.js";+import {+ getToolSessionSandboxSupport,+ ToolSessionSandboxUnsupportedError,+ withToolSessionSandboxes,+} from "#execution/tool-session/sandbox.js";+import { isEveDevEnvironment } from "#internal/application/dev-environment.js";import type { DockerSandboxEnvironmentOptions } from "#public/sandbox/docker-sandbox.js";import type { JustBashSandboxCreateOptions } from "#public/sandbox/just-bash-sandbox.js";import type { VercelSandboxCreateOptions } from "#public/sandbox/vercel-sandbox.js";+import {+ type SandboxSessionEndWithArtifact,+ withAdoptedSandboxSessionStates,+ withSessionEndArtifact,+} from "#sandbox/state.js";import { DockerSandbox } from "#sandbox/providers/docker.js";import { JustBashSandbox } from "#sandbox/providers/just-bash.js";-import { createDefaultVercelEnvironment } from "#sandbox/providers/vercel.js";-import type { SandboxEnvironment } from "#shared/sandbox-environment.js";+import { VercelSandbox } from "#sandbox/providers/vercel.js";+import { getSandboxEnvironmentRuntime } from "#shared/sandbox-environment.js";+import type {+ SandboxNetworkOptions,+ SandboxNetworkPolicy,+} from "#shared/sandbox-network-policy.js";+import {+ defineSandboxProvider,+ isSandboxPreparedArtifactRecord,+ type SandboxPreparedArtifact,+ type SandboxProviderHandle,+ type SandboxProviderImplementation,+ type SandboxProviderRuntime,+} from "#shared/sandbox-provider.js";+import { SandboxSessionGoneError } from "#shared/sandbox-session-gone-error.js";import type { SandboxSession } from "#shared/sandbox-session.js";export interface DefaultSandboxEnvironmentOptions {@@ -15,46 +40,248 @@ export interface DefaultSandboxEnvironmentOptions {readonly vercel?: VercelSandboxCreateOptions;}-export interface DefaultSandboxProbes {- readonly isDeployedOnVercel: () => boolean;- readonly isDockerAvailable: () => boolean;+/** Options applied when eve creates one live sandbox from a `DefaultSandbox` environment. */+export type DefaultSandboxRuntimeOptions = SandboxNetworkOptions;++/** Live sandbox capabilities exposed by a `DefaultSandbox` environment. */+export interface DefaultSandboxSession extends SandboxSession {+ /**+ * Applies a network policy to the live sandbox. Docker accepts only+ * `"allow-all"` and `"deny-all"`; just-bash accepts only `"allow-all"`.+ */+ setNetworkPolicy(policy: SandboxNetworkPolicy): Promise<void>;}-const SANDBOX_PROVIDER_PROBES: DefaultSandboxProbes = {- isDeployedOnVercel: () => Boolean(process.env.VERCEL),- isDockerAvailable: () => isLinuxDockerDaemonAvailableSync(),+type SelectedProvider = "docker" | "just-bash" | "vercel";++type DefaultSandboxPreparedArtifact =+ | { readonly artifact: SandboxPreparedArtifact; readonly provider: SelectedProvider }+ | { readonly provider: null };++type DefaultSandboxSessionState = {+ readonly provider: SelectedProvider;+ readonly state: SandboxPreparedArtifact;+ /** The selected provider's state protocol when it recorded `state`. */+ readonly stateProtocolVersion: number;};-export const DefaultSandbox = defineDefaultSandboxProvider(SANDBOX_PROVIDER_PROBES);+const SELECTED_PROVIDERS: readonly SelectedProvider[] = ["docker", "just-bash", "vercel"];-export function defineDefaultSandboxProvider(probes: DefaultSandboxProbes) {- return {- name: "default",- environment(options: DefaultSandboxEnvironmentOptions = {}): SandboxEnvironment<undefined> {- if (probes.isDeployedOnVercel()) {- return withoutOpenOptions(- createDefaultVercelEnvironment(withPreparation(options.vercel, options.prepare)),- );+const NO_PROVIDER_MESSAGE =+ "DefaultSandbox has no sandbox provider for this build: it did not run on Vercel, no Docker " ++ "daemon was reachable, and production builds do not fall back to just-bash. Start Docker " ++ "and rebuild, deploy to Vercel, or select a provider explicitly in your sandbox module, such " ++ "as agent/sandbox/sandbox.ts.";++const JUST_BASH_NETWORK_POLICY_MESSAGE =+ 'DefaultSandbox selected just-bash, which always allows network access and accepts only the "allow-all" ' ++ "network policy. Start Docker so DefaultSandbox selects it, or select VercelSandbox or " ++ "DockerSandbox explicitly.";++/**+ * Selects Vercel Sandbox on Vercel, Docker when a daemon is reachable, and+ * just-bash in development. Preparation records the choice, so the runtime+ * uses the provider the build selected and never probes the host.+ */+export const DefaultSandbox = defineSandboxProvider<+ DefaultSandboxEnvironmentOptions,+ DefaultSandboxRuntimeOptions,+ DefaultSandboxPreparedArtifact,+ DefaultSandboxSessionState,+ DefaultSandboxSession+>({+ name: "default",+ environment(options = {}) {+ // Created on first use, so a hosted bundle never constructs the local providers it prunes.+ const providers = new Map<SelectedProvider, SandboxProviderRuntime>();+ const provider = (name: SelectedProvider) => {+ let runtime = providers.get(name);+ if (runtime === undefined) {+ runtime = getSandboxEnvironmentRuntime(createEnvironment(name, options));+ providers.set(name, runtime);}- if (probes.isDockerAvailable()) {- return withoutOpenOptions(- DockerSandbox.environment(withPreparation(options.docker, options.prepare)),- );+ return runtime;+ };+ const releases = new WeakMap<SandboxProviderHandle, () => Promise<void>>();++ function wrapHandle(+ inner: SandboxProviderRuntime,+ handle: SandboxProviderHandle,+ ): SandboxProviderHandle<DefaultSandboxSession> {+ const wrapped: SandboxProviderHandle<DefaultSandboxSession> = {+ sandbox: hasNetworkPolicy(handle.sandbox)+ ? handle.sandbox+ : { ...handle.sandbox, setNetworkPolicy: rejectJustBashNetworkPolicy },+ onRuntimeShutdown: () => handle.onRuntimeShutdown(),+ onSandboxDelete: (deleteOptions) => handle.onSandboxDelete(deleteOptions),+ onSandboxStop: () => handle.onSandboxStop(),+ };+ const release = getToolSessionSandboxSupport(inner.implementation)?.releaseHandle;+ if (release !== undefined) releases.set(wrapped, () => release(handle));+ return wrapped;+ }++ function requireProvider(name: SelectedProvider, sessionId: string) {+ const inner = provider(name);+ if (+ isToolSessionId(sessionId) &&+ getToolSessionSandboxSupport(inner.implementation) === undefined+ ) {+ throw new ToolSessionSandboxUnsupportedError(name);}- return JustBashSandbox.environment(withPreparation(options.justBash, options.prepare));- },- };+ return inner;+ }++ // Routes to the provider that recorded the state, or else the one this build selected.+ const endSession = async (+ context: Parameters<SandboxSessionEndWithArtifact>[0],+ state: Readonly<DefaultSandboxSessionState> | null,+ options: {+ readonly artifact: DefaultSandboxPreparedArtifact | undefined;+ readonly reason: Parameters<SandboxSessionEndWithArtifact>[2]["reason"];+ },+ ) => {+ const name = state?.provider ?? options.artifact?.provider ?? null;+ if (name === null) return;+ const inner = provider(name);+ const innerState =+ state?.stateProtocolVersion === inner.stateProtocolVersion ? state.state : null;+ await inner.implementation.onSessionEnd(context, innerState, { reason: options.reason });+ };++ const implementation: SandboxProviderImplementation<+ DefaultSandboxRuntimeOptions,+ DefaultSandboxPreparedArtifact,+ DefaultSandboxSessionState,+ DefaultSandboxSession+ > = {+ async onSessionEnd(context, state, { reason }) {+ await endSession(context, state, { artifact: undefined, reason });+ },+ async prepare(context) {+ const name = selectProvider();+ if (name === null) {+ context.log?.(NO_PROVIDER_MESSAGE);+ return { provider: null };+ }+ return { artifact: await provider(name).implementation.prepare(context), provider: name };+ },+ async resume(context, artifact, state) {+ if (artifact.provider === null || artifact.provider !== state.provider) {+ throw new SandboxSessionGoneError(+ `The session's ${state.provider} sandbox cannot resume because this build selected ${artifact.provider ?? "no provider"}.`,+ );+ }+ const inner = requireProvider(state.provider, context.session.id);+ if (state.stateProtocolVersion !== inner.stateProtocolVersion) {+ throw new SandboxSessionGoneError(+ `The session's ${state.provider} sandbox state uses protocol ${state.stateProtocolVersion}, not ${inner.stateProtocolVersion}.`,+ );+ }+ const handle = await inner.implementation.resume(context, artifact.artifact, state.state);+ return wrapHandle(inner, handle);+ },+ async start(context, options, artifact) {+ if (artifact.provider === null) throw new Error(NO_PROVIDER_MESSAGE);+ const inner = requireProvider(artifact.provider, context.session.id);+ const result = await inner.implementation.start(+ context,+ openOptions(artifact.provider, options),+ artifact.artifact,+ );+ return {+ handle: wrapHandle(inner, result.handle),+ state: {+ provider: artifact.provider,+ state: result.state,+ stateProtocolVersion: inner.stateProtocolVersion,+ },+ };+ },+ };++ withToolSessionSandboxes(implementation, {+ releaseHandle: async (handle) => await releases.get(handle)?.(),+ });+ withSessionEndArtifact(implementation, async (context, state, options) => {+ await endSession(context, isDefaultSandboxSessionState(state) ? state : null, {+ artifact: isDefaultSandboxPreparedArtifact(options.artifact) ? options.artifact : undefined,+ reason: options.reason,+ });+ });+ // Sessions saved before DefaultSandbox recorded its own state hold the state+ // of the provider it picked. Remove this once eve stops resuming sessions+ // saved by releases before it, at the next sandbox state reset like eve 0.64's.+ // `resume` treats a protocol the inner provider no longer speaks as gone.+ return withAdoptedSandboxSessionStates(implementation, (record) => {+ const name = record.providerName;+ if (!isSelectedProvider(name)) return undefined;+ return {+ provider: name,+ state: record.state,+ stateProtocolVersion: record.stateProtocolVersion,+ };+ });+ },+});++function selectProvider(): SelectedProvider | null {+ if (process.env.VERCEL?.trim()) return "vercel";+ if (isLinuxDockerDaemonAvailableSync()) return "docker";+ return isEveDevEnvironment() ? "just-bash" : null;+}++function createEnvironment(name: SelectedProvider, options: DefaultSandboxEnvironmentOptions) {+ const prepare = options.prepare === undefined ? {} : { prepare: options.prepare };+ switch (name) {+ case "docker":+ return DockerSandbox.environment({ ...options.docker, ...prepare });+ case "just-bash":+ return JustBashSandbox.environment({ ...options.justBash, ...prepare });+ case "vercel":+ return VercelSandbox.environment({ ...options.vercel, ...prepare });+ }+}++function openOptions(+ name: SelectedProvider,+ options: Readonly<DefaultSandboxRuntimeOptions> | undefined,+): Readonly<DefaultSandboxRuntimeOptions> | undefined {+ if (name !== "just-bash") return options;+ if (options?.networkPolicy !== undefined && options.networkPolicy !== "allow-all") {+ throw new Error(JUST_BASH_NETWORK_POLICY_MESSAGE);+ }+ return undefined;+}++async function rejectJustBashNetworkPolicy(policy: SandboxNetworkPolicy): Promise<void> {+ if (policy !== "allow-all") throw new Error(JUST_BASH_NETWORK_POLICY_MESSAGE);+}++function hasNetworkPolicy(session: SandboxSession): session is DefaultSandboxSession {+ return typeof Reflect.get(session, "setNetworkPolicy") === "function";+}++function isSelectedProvider(value: unknown): value is SelectedProvider {+ return SELECTED_PROVIDERS.some((name) => name === value);}-function withPreparation<Options extends object>(- options: Options | undefined,- prepare: ((sandbox: SandboxSession) => Promise<void> | void) | undefined,-) {- return Object.assign({}, options, prepare === undefined ? {} : { prepare });+function isDefaultSandboxSessionState(+ value: SandboxPreparedArtifact | null,+): value is DefaultSandboxSessionState {+ return (+ isSandboxPreparedArtifactRecord(value) &&+ isSelectedProvider(value.provider) &&+ typeof value.stateProtocolVersion === "number" &&+ "state" in value+ );}-function withoutOpenOptions<Options extends object | undefined>(- environment: SandboxEnvironment<Options>,-): SandboxEnvironment<undefined> {- return environment as SandboxEnvironment<undefined>;+function isDefaultSandboxPreparedArtifact(+ value: SandboxPreparedArtifact | undefined,+): value is DefaultSandboxPreparedArtifact {+ return (+ isSandboxPreparedArtifactRecord(value) &&+ (value.provider === null || (isSelectedProvider(value.provider) && "artifact" in value))+ );}diff --git a/packages/eve/src/sandbox/providers/vercel.ts b/packages/eve/src/sandbox/providers/vercel.tsindex 5a3643fac..2560d45ac 100644--- a/packages/eve/src/sandbox/providers/vercel.ts+++ b/packages/eve/src/sandbox/providers/vercel.ts@@ -1,6 +1,5 @@import type { VercelSandboxSession } from "#public/sandbox/vercel.js";import {- createVercelSandbox,createVercelSandboxProvider,type VercelSandboxPreparedArtifact,type VercelSandboxSessionState,@@ -18,20 +17,6 @@ export type VercelSandboxEnvironmentOptions = VercelSandboxCreateOptions & {};export type { VercelSandboxRuntimeOptions } from "#public/sandbox/vercel-sandbox.js";-const defaultProvider = defineSandboxProvider<- VercelSandboxEnvironmentOptions | undefined,- VercelSandboxRuntimeOptions,- VercelSandboxPreparedArtifact,- VercelSandboxSessionState,- VercelSandboxSession->({- name: "vercel",- environment: (options) => {- const { prepare, ...createOptions } = options ?? {};- return createVercelSandbox({ createOptions, prepare, skipEmptyPreparation: true });- },-});-const provider = defineSandboxProvider<VercelSandboxEnvironmentOptions | undefined,VercelSandboxRuntimeOptions,@@ -43,12 +28,6 @@ const provider = defineSandboxProvider<environment: (options) => createVercelSandboxProvider(options),});-export function createDefaultVercelEnvironment(- options?: VercelSandboxEnvironmentOptions,-): SandboxEnvironment<VercelSandboxRuntimeOptions, VercelSandboxSession> {- return defaultProvider.environment(options);-}-export const VercelSandbox = {name: "vercel",environment(diff --git a/packages/eve/src/sandbox/state.ts b/packages/eve/src/sandbox/state.tsindex 1226fd853..94ae88985 100644--- a/packages/eve/src/sandbox/state.ts+++ b/packages/eve/src/sandbox/state.ts@@ -1,6 +1,11 @@import type { SandboxSession } from "#public/definitions/sandbox.js";import type { SandboxEnvironmentIdentity } from "#shared/sandbox-environment.js";-import type { SandboxDeleteOptions, SandboxPreparedArtifact } from "#shared/sandbox-provider.js";+import type {+ SandboxDeleteOptions,+ SandboxPreparedArtifact,+ SandboxProviderRuntime,+ SandboxProviderSessionContext,+} from "#shared/sandbox-provider.js";export type SandboxSessionEndReason = "completed" | "expired" | "failed";@@ -32,6 +37,80 @@ export function isRetiredSandboxSessionState(state: SandboxSessionState): booleareturn state.providerName === undefined || state.providerName === "microsandbox";}+/** Converts a record another provider wrote into this provider's state, or `undefined`. */+type SandboxSessionStateAdopter = (+ state: SandboxSessionState,+) => SandboxPreparedArtifact | undefined;++const adopters = new WeakMap<object, SandboxSessionStateAdopter>();++/**+ * Lets an eve-owned provider resume records that another provider name wrote,+ * such as `DefaultSandbox` for sessions saved when it recorded the provider it+ * picked. Internal, so the public provider API is unchanged.+ */+export function withAdoptedSandboxSessionStates<Implementation extends object>(+ implementation: Implementation,+ adopt: SandboxSessionStateAdopter,+): Implementation {+ adopters.set(implementation, adopt);+ return implementation;+}++/**+ * The persisted record the current provider should resume, or `null` for no+ * sandbox. A record the provider cannot adopt is returned as-is; resuming it+ * starts a fresh sandbox, and handoff rejects it. An adopted record keeps its+ * `generation`, because it still names the same live sandbox.+ */+export function resolvePersistedSandboxSessionState(+ state: SandboxSessionState | null | undefined,+ provider: SandboxProviderRuntime | undefined,+): SandboxSessionState | null {+ if (state === null || state === undefined || isRetiredSandboxSessionState(state)) return null;+ if (provider === undefined || state.providerName === provider.providerName) return state;+ const adopted = adopters.get(provider.implementation)?.(state);+ return adopted === undefined+ ? state+ : {+ ...state,+ providerName: provider.providerName,+ state: adopted,+ stateProtocolVersion: provider.stateProtocolVersion,+ };+}++/** Session-end cleanup that also needs the current build's prepared artifact. */+export type SandboxSessionEndWithArtifact = (+ context: SandboxProviderSessionContext,+ state: SandboxPreparedArtifact | null,+ options: {+ readonly artifact: SandboxPreparedArtifact | undefined;+ readonly reason: SandboxSessionEndReason;+ },+) => Promise<void>;++const sessionEndsWithArtifact = new WeakMap<object, SandboxSessionEndWithArtifact>();++/**+ * Lets an eve-owned provider receive the prepared artifact at session end,+ * such as `DefaultSandbox`, which finds the provider it selected there when+ * no state was recorded. Internal, so the public provider API is unchanged.+ */+export function withSessionEndArtifact<Implementation extends object>(+ implementation: Implementation,+ onSessionEnd: SandboxSessionEndWithArtifact,+): Implementation {+ sessionEndsWithArtifact.set(implementation, onSessionEnd);+ return implementation;+}++export function getSessionEndWithArtifact(+ implementation: object,+): SandboxSessionEndWithArtifact | undefined {+ return sessionEndsWithArtifact.get(implementation);+}+export interface SandboxAccess {readonly environment?: SandboxEnvironmentIdentity;captureState(): Promise<SandboxState>;diff --git a/packages/eve/src/self-modification/deployed-sandbox.ts b/packages/eve/src/self-modification/deployed-sandbox.tsindex f9e59ff64..d7f297cba 100644--- a/packages/eve/src/self-modification/deployed-sandbox.ts+++ b/packages/eve/src/self-modification/deployed-sandbox.ts@@ -1,6 +1,6 @@import { defineSandbox } from "#public/definitions/sandbox.js";import { JustBashSandbox } from "#sandbox/providers/just-bash.js";-import { createDefaultVercelEnvironment } from "#sandbox/providers/vercel.js";+import { VercelSandbox } from "#sandbox/providers/vercel.js";import { bindSandboxEnvironment, type SandboxSelector } from "#shared/sandbox-environment.js";import { shellQuote } from "#shared/shell-quote.js";@@ -18,8 +18,8 @@ const VERCEL_SANDBOX_REQUIRED_MESSAGE =/*** Defines the deployed child's sandbox. During `eve dev` the deployed child is never- * offered, so its sandbox binds an inert environment. Other builds bind the default- * Vercel environment, whose empty preparation is a no-op, so they compile on any host;+ * offered, so its sandbox binds an inert environment. Other builds bind a Vercel+ * environment, whose empty preparation is a no-op, so they compile on any host;* the Vercel requirement is enforced when a deployed child opens its sandbox.*/export function defineDeployedSelfModificationSandbox(@@ -35,7 +35,7 @@ export function defineDeployedSelfModificationSandbox(}const deployed = resolveDeployedSelfModificationConfig(config);- const environment = createDefaultVercelEnvironment();+ const environment = VercelSandbox.environment();return bindSandboxEnvironment(defineSandbox(async ({ session }) => {if (!isDeployedOnVercel()) throw new Error(VERCEL_SANDBOX_REQUIRED_MESSAGE);diff --git a/packages/eve/test/runtime-agent-graph.test.ts b/packages/eve/test/runtime-agent-graph.test.tsindex ce264af5a..bcf03776e 100644--- a/packages/eve/test/runtime-agent-graph.test.ts+++ b/packages/eve/test/runtime-agent-graph.test.ts@@ -25,7 +25,7 @@ describe("resolveRuntimeAgentGraph", () => {expect(graph.root.nodeId).toBe("__root__");const definition = graph.root.sandboxRegistry.sandbox.definition;expect(definition.kind).toBe("independent");- if (definition.kind === "independent") expect(definition.environment.provider).toBe("vercel");+ if (definition.kind === "independent") expect(definition.environment.provider).toBe("default");expect(names).toEqual(manifest.tools.map((tool) => tool.name));expect(names).toContain("web_search");expect(graph.root.agent.tools.every((tool) => tool.owner.kind === "framework")).toBe(true);