Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(sandbox)!: connection-based public sandbox provider API (#5241)

Andrew Barba5b27aa8ade75
diff --git a/.changeset/sandbox-provider-connection-api.md b/.changeset/sandbox-provider-connection-api.md
new file mode 100644
index 000000000..67a10c9b5
--- /dev/null
+++ b/.changeset/sandbox-provider-connection-api.md
@@ -0,0 +1,11 @@
+---
+"eve": minor
+---
+
+**Breaking for custom sandbox providers.** `defineSandboxProvider()` now takes a byte-level `SandboxConnection` (`spawn`, `readFile`, `writeFiles`, `removePath`, `stop`, optional `close` and `extensions`), and eve derives the full sandbox session from it. Built-in providers are unchanged. See the [custom sandbox providers guide](https://eve.dev/docs/sandbox/custom-providers). To migrate a provider:
+
+- Return `{ connection, state }` from `start()` and a connection from `resume()`. `onSandboxStop()` and `onRuntimeShutdown()` become `connection.stop()`, and `onSandboxDelete()` folds into `onSessionEnd()` with `reason: "deleted"`.
+- Replace `ctx.resources` and `ctx.sourceRevision` with `ctx.templateKey()` and `ctx.populate()`, and remove your own `prepare` option, which eve now runs. `environment()` receives `{}` instead of `undefined` when no options are passed. Set `toolSessions: true` to support keyed `invokeTool` calls.
+- Rename `SandboxPreparedArtifact` to `SandboxJson`, `SandboxProviderSessionContext` to `SandboxSessionContext`, and `SandboxProviderPrepareContext` to `SandboxPrepareContext`. `SandboxProviderHandle` and the `SandboxProviderResource*` and `SandboxProviderTargetFile` types are removed, as is `ctx.host`.
+
+`eve/sandbox/provider` also exports `SandboxSessionGoneError`, `SandboxTemplateNotProvisionedError`, and `SANDBOX_AGENT_ENV`. In `eve/sandbox`, `SandboxSession` gains a required `writeFiles()`, so hand-built sessions such as test doubles need one, and `SandboxNetworkPolicy` is now an eve-owned type rather than the Vercel Sandbox SDK's `NetworkPolicy`.
diff --git a/docs/channels/custom.mdx b/docs/channels/custom.mdx
index f3f9218b9..44349f336 100644
--- a/docs/channels/custom.mdx
+++ b/docs/channels/custom.mdx
@@ -68,7 +68,7 @@ Each route receives these operation surfaces:
- `to(channel, target).send(message, options)` hands work to another authored channel.
- `params`, `waitUntil`, and `requestIp` provide request metadata and lifetime control.
- `describe()` returns the agent's name, description, the compiled tools a caller can run outside a turn, with their JSON schemas, and the compiled skills, each with its `name` and `description`, sorted by name. It reads the compiled manifest only, never a skill file, and carries no other paths, config, or inspection detail, so a channel can publish it to its callers. Tools that need a turn (framework tools, workflow and provider tools, tools without `execute`) and tools and skills added by dynamic resolvers or subagents are left out.
-- `invokeTool(name, input, { auth, key })` runs one of those tools as `auth`, outside any conversation: no model, turn, or workflow run. Authored state starts from its initial value and is not kept. Without `key`, each call gets its own session, and a sandbox the tool opens is deleted when the call ends. With `key` (1 to 512 characters), calls from the same `auth` principal with the same key share a session id and a sandbox, which is kept between calls; this needs Vercel Sandbox or just-bash, and an authenticated `auth` (a keyed call from the anonymous principal is `denied`); see [MCP tool sessions](./mcp#tool-sessions). When a trusted forwarder asserted `auth`, pass the principal your route verified as `forwardedBy`: it is part of the session, so one user reached through two forwarders gets two sessions. It resolves to `completed` with the tool's output, or to `invalid-input`, `denied`, `failed`, `approval-required` when the tool's approval policy asks a person (the tool did not run), or `authorization-required` with the connections the tool needs a sign-in to.
+- `invokeTool(name, input, { auth, key })` runs one of those tools as `auth`, outside any conversation: no model, turn, or workflow run. Authored state starts from its initial value and is not kept. Without `key`, each call gets its own session, and a sandbox the tool opens is deleted when the call ends. With `key` (1 to 512 characters), calls from the same `auth` principal with the same key share a session id and a sandbox, which is kept between calls; this needs Vercel Sandbox, just-bash, or a custom provider that sets `toolSessions: true`, and an authenticated `auth` (a keyed call from the anonymous principal is `denied`); see [MCP tool sessions](./mcp#tool-sessions). When a trusted forwarder asserted `auth`, pass the principal your route verified as `forwardedBy`: it is part of the session, so one user reached through two forwarders gets two sessions. It resolves to `completed` with the tool's output, or to `invalid-input`, `denied`, `failed`, `approval-required` when the tool's approval policy asks a person (the tool did not run), or `authorization-required` with the connections the tool needs a sign-in to.
A direct call doesn't go through the AI SDK, so AI SDK telemetry integrations never see it. Conversation tool calls do: an integration that an `agent/instrumentation/*.ts` module registers with `registerTelemetry()` from `ai` receives `onToolExecutionStart` and `onToolExecutionEnd` for each of them. A direct call is traced by eve itself instead. It gets an `execute_tool` span under the caller's trace and emits `tool.call.started` and `tool.call.completed` to instrumentation. Over MCP, the caller's trace comes from the request's `_meta` trace context (see [Trace context](./mcp#trace-context)).
diff --git a/docs/channels/mcp.mdx b/docs/channels/mcp.mdx
index fba795e7d..9f3d2d14a 100644
--- a/docs/channels/mcp.mdx
+++ b/docs/channels/mcp.mdx
@@ -314,7 +314,7 @@ In a tool session:
- Authored state still starts from its initial value on every call, and updates are not kept. Keep data that must outlive a call in the sandbox.
- Calls may still run in parallel, and nothing orders them.
-Tool sessions need a sandbox provider whose kept sandboxes stay bounded: Vercel Sandbox or just-bash. On another provider, a call with a key fails with a `Sandbox provider "<name>" cannot keep a sandbox between invokeTool calls` error when the tool opens its sandbox. Tools that never open a sandbox still run. just-bash keeps its sandboxes on the local disk, so on Vercel Functions a just-bash tool session lasts only as long as the function instance.
+Tool sessions need a sandbox provider whose kept sandboxes stay bounded: Vercel Sandbox, just-bash, or a [custom provider](/docs/sandbox/custom-providers#keep-sandboxes-for-keyed-tool-calls) that sets `toolSessions: true`. On another provider, a call with a key fails with a `Sandbox provider "<name>" cannot keep a sandbox between invokeTool calls` error when the tool opens its sandbox. Tools that never open a sandbox still run. just-bash keeps its sandboxes on the local disk, so on Vercel Functions a just-bash tool session lasts only as long as the function instance.
A tool session has no end, so eve bounds how long its sandbox is kept. On Vercel Sandbox, a tool-session sandbox's saved filesystem expires a day after its last use, and each call that resumes it restarts that day. The next call with the key after that replaces it with a fresh, empty sandbox. If two calls with the key find the expired filesystem at the same time, each can replace the sandbox, and files the first one writes can be lost. Vercel only keeps the latest snapshot of the sandbox. Tool sessions use this one-day expiry whatever `snapshotExpiration` `sandbox.ts` sets; sessions that conversations start keep the authored setting.
diff --git a/docs/guides/deployment/self-hosting.md b/docs/guides/deployment/self-hosting.md
index 4ce7d5938..e0880b00d 100644
--- a/docs/guides/deployment/self-hosting.md
+++ b/docs/guides/deployment/self-hosting.md
@@ -90,7 +90,7 @@ This adds conversation text as context to the replacement session.
## Select a sandbox provider
-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.
+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](../../sandbox/custom-providers) 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.
diff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.md
index 72b7d4082..cd1959f8f 100644
--- a/docs/reference/typescript-api.md
+++ b/docs/reference/typescript-api.md
@@ -50,7 +50,7 @@ export default defineTool({
| `defineState` | `eve/context` | tools, hooks, lifecycle | [Session context](../guides/session-context) |
| `defineSandbox` | `eve/sandbox` | `agent/sandbox.ts` or `agent/sandbox/sandbox.ts` | [Sandbox](../sandbox) |
| `defineParentSandbox` | `eve/sandbox` | `agent/subagents/<name>/sandbox.ts` | [Sandbox](../sandbox#share-a-parent-sandbox) |
-| `defineSandboxProvider` | `eve/sandbox/provider` | custom sandbox provider modules | [Sandbox](../sandbox#custom-providers) |
+| `defineSandboxProvider` | `eve/sandbox/provider` | custom sandbox provider modules | [Custom providers](../sandbox/custom-providers) |
| `defineInstrumentation` | `eve/instrumentation` | `agent/instrumentation/<name>.ts` | [Instrumentation](../observability/instrumentation) |
| `otel`, `otelIntegration` | `eve/instrumentation/otel` | `agent/instrumentation/<destination>.ts` | [OpenTelemetry](../observability/otel) |
| `defineRemoteAgent` | `eve` | `agent/subagents/<id>/agent.ts` | [Remote agents](../guides/remote-agents) |
@@ -142,8 +142,8 @@ Tool definitions accept `availableInSubagents: false` to restrict the tool to to
| `eve/memory/file` | `fileMemory`, `inMemory`, and the conditional document backend contract |
| `eve/memory/file/vercel` | `vercelBlob` and Vercel Blob backend options |
| `eve/context` | `defineState`, session and state types |
-| `eve/sandbox` | `defineSandbox`, `defineParentSandbox`, `DefaultSandbox`, and sandbox session types |
-| `eve/sandbox/provider` | `defineSandboxProvider` and custom provider types |
+| `eve/sandbox` | `defineSandbox`, `defineParentSandbox`, `DefaultSandbox`, and sandbox session and network policy types |
+| [`eve/sandbox/provider`](../sandbox/custom-providers) | `defineSandboxProvider`, provider errors, `SANDBOX_AGENT_ENV`, and connection and lifecycle types |
| [`eve/sandbox/docker`](../sandbox/docker) | `DockerSandbox` and Docker environment and session types |
| [`eve/sandbox/vercel`](../sandbox/vercel) | `VercelSandbox`, `Drive`, and Vercel environment, session, and mount types |
| [`eve/sandbox/just-bash`](../sandbox/just-bash) | `JustBashSandbox` and just-bash environment types |
diff --git a/docs/sandbox/custom-providers.mdx b/docs/sandbox/custom-providers.mdx
new file mode 100644
index 000000000..e2bfd13c2
--- /dev/null
+++ b/docs/sandbox/custom-providers.mdx
@@ -0,0 +1,248 @@
+---
+title: "Custom Sandbox Providers"
+description: "Connect eve to your own sandbox backend with defineSandboxProvider()."
+---
+
+A custom sandbox provider connects eve to a backend that eve does not ship, such as your own container service or virtual machine pool. You implement a byte-level connection to one sandbox and four lifecycle methods. eve derives the full sandbox session from the connection, seeds workspace and skill files into templates, hashes template keys, and maps `sandbox.stop()`, `sandbox.delete()`, and server shutdown onto the lifecycle.
+
+## Define a provider
+
+`defineSandboxProvider()` from `eve/sandbox/provider` takes a name and an `environment()` function that returns the lifecycle. This example targets `@acme/sdk`, a hypothetical client for a snapshot-capable machine service:
+
+```ts title="agent/lib/acme-sandbox.ts"
+import { createHash } from "node:crypto";
+import {
+ defineSandboxProvider,
+ SANDBOX_AGENT_ENV,
+ SandboxSessionGoneError,
+ type SandboxConnection,
+} from "eve/sandbox/provider";
+import { AcmeClient, type AcmeMachine } from "@acme/sdk";
+
+export const AcmeSandbox = defineSandboxProvider({
+ name: "acme",
+ environment(options: { readonly project: string }) {
+ const acme = new AcmeClient({ project: options.project });
+ // Session ids can be long, so hash them into a bounded machine name.
+ const nameFor = (sessionId: string) =>
+ `eve-${createHash("sha256").update(sessionId).digest("hex").slice(0, 32)}`;
+ return {
+ async prepare(ctx) {
+ const template = `eve-tpl-${ctx.templateKey({ project: options.project, version: 1 }).slice(0, 32)}`;
+ const cached = await acme.snapshots.find(template);
+ if (cached !== null) return { snapshotId: cached.id };
+ const machine = await acme.machines.create({
+ env: SANDBOX_AGENT_ENV,
+ image: "ubuntu:24.04",
+ });
+ try {
+ await ctx.populate(connect(machine));
+ return { snapshotId: (await machine.snapshot({ name: template })).id };
+ } finally {
+ await machine.destroy();
+ }
+ },
+ async start(ctx, open: { readonly egress?: "allow-all" | "deny-all" } | undefined, artifact) {
+ const name = nameFor(ctx.session.id);
+ // Atomic create-if-absent: an existing machine is returned unchanged,
+ // so `egress` and the snapshot apply only on creation.
+ const machine = await acme.machines.createIfAbsent({
+ egress: open?.egress ?? "allow-all",
+ env: SANDBOX_AGENT_ENV,
+ name,
+ snapshotId: artifact.snapshotId,
+ });
+ return { connection: connect(machine), state: { name, version: 1 } };
+ },
+ async resume(_ctx, _artifact, state) {
+ const machine = await acme.machines.get(state.name);
+ if (machine === null)
+ throw new SandboxSessionGoneError(`Acme machine "${state.name}" is gone.`);
+ return connect(machine);
+ },
+ async onSessionEnd(ctx, state, { abortSignal }) {
+ await acme.machines.destroyIfExists(state?.name ?? nameFor(ctx.session.id), {
+ signal: abortSignal,
+ });
+ },
+ };
+ },
+});
+
+function connect(machine: AcmeMachine): SandboxConnection {
+ return {
+ spawn: ({ abortSignal, command, env, workingDirectory }) =>
+ machine.exec({
+ argv: ["bash", "-lc", command],
+ cwd: workingDirectory,
+ env,
+ signal: abortSignal,
+ }),
+ // Acme returns `null` for a missing path and rejects for a directory.
+ readFile: ({ abortSignal, path }) => machine.files.read(path, { signal: abortSignal }),
+ writeFiles: ({ abortSignal, files }) =>
+ machine.files.write(files, { mkdirs: true, signal: abortSignal }),
+ removePath: ({ abortSignal, force, path, recursive }) =>
+ machine.files.remove(path, { force, recursive, signal: abortSignal }),
+ stop: () => machine.suspend(),
+ };
+}
+```
+
+Use the provider from a sandbox file like any built-in environment. Every provider accepts the standard `prepare` option:
+
+```ts title="agent/sandbox.ts"
+import { defineSandbox } from "eve/sandbox";
+import { AcmeSandbox } from "./lib/acme-sandbox";
+
+export const environment = AcmeSandbox.environment({
+ project: "agents",
+ prepare: async (sandbox) => {
+ await sandbox.run({ command: "apt-get install -y ripgrep" });
+ },
+});
+
+export default defineSandbox(() => environment.open({ egress: "deny-all" }));
+```
+
+`environment(options)` always receives an object, without `prepare`: `{}` when the sandbox file passes no options, so make every field optional or require the caller to pass it. TypeScript infers the environment options, open options, artifact, state, and connection extensions from the implementation, so you do not pass type arguments. Write `start()` before `resume()` so the state type comes from `start()`'s return value, or annotate `resume()`'s `state` parameter.
+
+## Implement the connection
+
+A `SandboxConnection` is the byte-level link to one sandbox. Each method has a fixed contract:
+
+- `spawn({ command, workingDirectory, env, abortSignal })` runs `command` as a Bash login-shell script (`bash -lc`) in `workingDirectory`, with the sandbox's environment plus `env`. `env` holds only the per-call variables. Aborting kills the process tree. It resolves to a process with `stdout` and `stderr` byte streams, `wait()`, and `kill()`.
+- `readFile({ path, abortSignal })` resolves to the file's bytes or a byte stream, or to `null` only when the path does not exist. A directory or an unreadable path rejects.
+- `writeFiles({ files, abortSignal })` writes every file, creating missing parent directories and overwriting existing files. It is the only write primitive.
+- `removePath({ path, force, recursive, abortSignal })` removes a file or directory. `force` ignores a missing path, and `recursive` removes a non-empty directory.
+- `stop()` releases compute and keeps the sandbox's files.
+- `close()` is optional. It releases what this process holds for the connection, such as a local interpreter, without touching the sandbox. eve calls it whenever it lets go of a connection: after `stop()`, before deletion and terminal cleanup, and when a keyed call ends.
+- `extensions` is optional. It is a plain object whose own properties eve merges onto the session, such as `setNetworkPolicy()`. Use closures rather than class methods, because eve does not copy inherited members.
+
+Every path a connection receives is absolute, and `workingDirectory` is always set. eve resolves relative paths and a missing or relative working directory from `/workspace` before it calls the connection.
+
+eve builds the rest of the session from these methods: `run()` over `spawn()`, the binary and text read and write variants, encodings and line ranges, `writeFiles()`, `resolvePath()`, and abort-signal binding. An extension member named like a session method, or `stop` or `delete`, is a type error, and eve throws when it opens the connection:
+
+```text
+Sandbox connection extensions cannot replace the session members eve provides: run. Rename them.
+```
+
+Type the connection with its extensions, such as `SandboxConnection<{ setNetworkPolicy(policy: SandboxNetworkPolicy): Promise<void> }>`, and `environment.open()` and `ctx.getSandbox(environment)` return a session that includes them.
+
+## Implement the lifecycle
+
+eve calls the lifecycle methods at these points:
+
+| When | eve calls |
+| ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `eve build`, or the first sandbox access in `eve dev` | `prepare(ctx)`, and stores the artifact it returns with the deployment |
+| The first sandbox access in a session | `start(ctx, options, artifact)` from `environment.open(options)` in the selector |
+| A later workflow step or process | `resume(ctx, artifact, state)` |
+| `sandbox.stop()` | `connection.stop()`, then `connection.close()` |
+| `sandbox.delete()` | `connection.close()`, then `onSessionEnd(ctx, state, { reason: "deleted" })` |
+| The eve server shuts down | `connection.stop()`, then `connection.close()`, on every open session connection; eve logs failures and does not throw them |
+| The owning session reaches a terminal outcome | `connection.close()` on this process's connections for the session, then `onSessionEnd(ctx, state, { reason })` with `"completed"`, `"expired"`, or `"failed"` |
+
+eve calls `stop()` and `close()` at most once per connection, retrying only after a failure. A failed `close()` never prevents `onSessionEnd()` from deleting the sandbox.
+
+### `prepare()`
+
+`prepare()` builds a reusable template and returns a JSON-compatible artifact, such as a snapshot or image id. It runs during `eve build`, so the deployment ships with the artifact, and the production runtime never calls it. A running sandbox keeps the template it started from: `resume()` receives the current deployment's artifact, but reconnects existing state.
+
+`ctx.isEmpty` is `true` when the agent has no workspace files, no skill files, and no authored `prepare`. A provider can skip building a template in that case. See [Bake files into templates](#bake-files-into-templates) for `ctx.populate()` and `ctx.templateKey()`.
+
+### `start()`
+
+`start()` returns the sandbox for `ctx.session.id`, creating it when none exists, together with the minimal JSON-compatible state eve checkpoints for the session. It must be an idempotent upsert: repeated, concurrent, cross-process, and cross-deployment calls for one session id return the same sandbox while it exists and is usable. A subagent that shares its parent's sandbox can open it before the parent does, and two processes can race to create it.
+
+Derive the sandbox's native identity from `ctx.session.id` and a provider-level namespace, such as a project or account, only. Never derive it from the open options or the artifact, which can differ between callers and deployments. Apply them only when `start()` creates the sandbox.
+
+`ctx.session.id` is the id of the session that owns the sandbox. For a subagent that shares its parent's sandbox it is the parent's id. `ctx.kind` is `"tool-session"` for a keyed `invokeTool` call's sandbox and `"session"` otherwise.
+
+### `resume()`
+
+`resume()` reconnects to the sandbox that `state` names and never recreates it. Open options are not passed to `resume()`, so put anything reconnection needs in the state. When the sandbox no longer exists, throw `SandboxSessionGoneError`: eve clears the session's state and reruns the selector, which starts a fresh sandbox without the lost sandbox's files. Let other failures, such as an outage, surface unchanged.
+
+Validate the shape of your own state in `resume()`. When you change it incompatibly, raise `stateProtocolVersion` in the provider definition: state recorded under another version starts a fresh sandbox instead of reaching `resume()`.
+
+### `onSessionEnd()`
+
+`onSessionEnd()` deletes whatever exists for `ctx.session.id`. `state` is `null` when the session never recorded it, for example when only a subagent that shares the sandbox opened it, or when a step failed before its checkpoint, so find the sandbox from the session id. The method must succeed when nothing exists and must be idempotent, because eve retries the cleanup step. eve logs an exhausted failure without replacing the session's outcome.
+
+`sandbox.delete()` uses the same method with `reason: "deleted"` and the caller's `abortSignal`, so a provider has one deletion path. A subagent that shares its parent's sandbox never calls it, because cleanup belongs to the parent. An `invokeTool` call without a key calls it when the call ends if the tool requested the sandbox.
+
+## Bake files into templates
+
+Call `ctx.populate(connection)` on the build instance before you capture it. `populate()` writes the agent's workspace files to `/workspace` and its skill files to `$HOME/.agents/skills` in one `writeFiles()` batch, then runs the authored `prepare` callback with a session over the same connection. eve finds `$HOME` by running a command through `spawn()`. When the sandbox has no usable home directory, skills go to `/workspace/skills`.
+
+A provider that can mount host directories can avoid writing every file. `ctx.resourcesDirectory()` resolves to a stable read-only host directory that contains `workspace/` and `skills/`, or to `undefined` when there is none. Mount it in the build instance and pass its sandbox path:
+
+```ts
+const resources = await ctx.resourcesDirectory();
+const machine = await acme.machines.create({
+ mounts:
+ resources === undefined ? [] : [{ host: resources, path: "/eve/resources", readOnly: true }],
+});
+await ctx.populate(
+ connect(machine),
+ resources === undefined ? undefined : { mountedAt: "/eve/resources" },
+);
+```
+
+With `mountedAt`, `populate()` copies `<mountedAt>/workspace/.` into `/workspace` and `<mountedAt>/skills/.` into `$HOME/.agents/skills` with `cp -a`. When eve has no resource directory, `populate()` ignores `mountedAt` and writes the files instead.
+
+`ctx.templateKey(identity)` returns a SHA-256 hex key that changes whenever `identity`, the workspace files, the skill files, or the sandbox file's source changes. Pass every option that affects the template, such as the base image, and use the key to name or look up a cached template. `identity` accepts JSON values, `undefined` (omitted), plain objects and arrays, and functions (hashed by their source). `resources` and `sourceRevision` are reserved, and eve throws if `identity` sets either one. The source revision covers only the sandbox file, so a `prepare` callback imported from another module does not change the key.
+
+Only build time seeds files. A sandbox that `start()` creates gets them from the template, so a provider whose templates cannot hold files cannot provide workspace or skill files.
+
+## Keep sandboxes for keyed tool calls
+
+Set `toolSessions: true` on the implementation to let keyed `invokeTool` calls keep their sandbox between calls, as Vercel Sandbox and just-bash do. A keyed call does not own its sandbox: eve runs the selector and `start()` on every call, calls `connection.close()` when the call ends, and never calls `onSessionEnd()`. Because nothing ever ends a keyed sandbox, the provider must bound its retention, for example with snapshot expiration.
+
+Without `toolSessions`, a keyed call fails when its tool requests the sandbox:
+
+```text
+Sandbox provider "acme" cannot keep a sandbox between invokeTool calls, so a call with a key cannot open one.
+```
+
+A keyed call whose tool never requests the sandbox runs normally. See [MCP tool sessions](/docs/channels/mcp#tool-sessions).
+
+## Enforce network policy
+
+eve has no built-in network control for custom providers. To offer one, accept a `SandboxNetworkPolicy` from `eve/sandbox` as an open option, as a `setNetworkPolicy()` extension, or both. Reject any part of a policy that the backend cannot enforce instead of weakening it. For example, a backend that can only switch egress on or off accepts `"allow-all"` and `"deny-all"` and throws on allow-lists, subnets, and header transforms, as the Docker provider does.
+
+## Set environment variables
+
+`SANDBOX_AGENT_ENV` is `{ AI_AGENT: "eve" }`, which tells agent-aware CLIs to skip interactive prompts. Apply it beneath your environment-level variables when you create the sandbox, as the built-in providers do. A per-call `env` passed to `spawn()` overrides both. If the backend has no sandbox-level environment, merge it beneath the per-call `env` in `spawn()` instead, as in `{ ...SANDBOX_AGENT_ENV, ...env }`.
+
+## Report missing templates
+
+Throw `SandboxTemplateNotProvisionedError` from `start()` or `resume()` when the artifact names an image, snapshot, or template that no longer exists:
+
+```ts
+import { SandboxTemplateNotProvisionedError } from "eve/sandbox/provider";
+
+throw new SandboxTemplateNotProvisionedError({
+ providerName: "acme",
+ reason: "The snapshot expired.",
+ templateKey: artifact.snapshotId,
+});
+```
+
+eve surfaces the error to the caller and never retries or rebuilds the template at runtime. eve throws the same error when a deployment has no artifact for the sandbox. Template retention and pruning stay with the provider. See [Sandbox troubleshooting](/docs/sandbox/troubleshooting#sandbox-template--is-not-available-to-this-runtime).
+
+## Migrate from the handle-based API
+
+Earlier releases asked a provider to return a handle with a complete sandbox session. To move a provider to the current API:
+
+- Return `{ connection, state }` from `start()` and a connection from `resume()`, instead of a handle. Move provider-specific session methods to `extensions`.
+- Remove `onSandboxStop()` and `onRuntimeShutdown()`; implement `connection.stop()`. Move `onSandboxDelete()` into `onSessionEnd()`, which receives `reason: "deleted"`.
+- Replace hashes of `ctx.resources` and `ctx.sourceRevision` with `ctx.templateKey()`, and replace writes of resource files plus your own `prepare` call with `ctx.populate()`. Remove `prepare` from your environment options; eve owns it.
+- Replace `ctx.host.resolveProjectPath()` with `ctx.resolveProjectPath()`. `ctx.host.loadOptionalPackage()` is no longer available; import your SDK directly.
+- Drop the explicit type arguments to `defineSandboxProvider()` and let TypeScript infer them. `environment()` now receives `{}` instead of `undefined` when the sandbox file passes no options.
+- Rename `SandboxPreparedArtifact` to `SandboxJson`, `SandboxProviderSessionContext` to `SandboxSessionContext`, and `SandboxProviderPrepareContext` to `SandboxPrepareContext`. `SandboxProviderHandle`, `SandboxProviderResources`, `SandboxProviderResourceTree`, `SandboxProviderResourceFile`, `SandboxProviderResourceSource`, and `SandboxProviderTargetFile` are removed.
+
+Two changes in `eve/sandbox` also affect code outside providers:
+
+- `SandboxSession` has a required `writeFiles()` method, so an object you build by hand as a `SandboxSession`, such as a test double, needs one.
+- `SandboxNetworkPolicy` is an eve-owned type with `readonly` members instead of the Vercel Sandbox SDK's `NetworkPolicy`. Code that passes a policy to the SDK directly needs its own conversion.
diff --git a/docs/sandbox/index.mdx b/docs/sandbox/index.mdx
index 5a9292831..a23f42e74 100644
--- a/docs/sandbox/index.mdx
+++ b/docs/sandbox/index.mdx
@@ -99,7 +99,7 @@ During `eve dev`, startup and authored-source rebuilds do not prepare sandbox en
### Reuse native resources across sessions
-Built-in environments do not expose cross-session sharing. To reuse native compute or storage across eve sessions, define a custom provider that returns a session-owned logical sandbox view and keeps shared resources outside that view's `stop`, `shutdown`, and `delete` operations. A session-specific path is not an isolation boundary; mutually untrusted sessions require separate native compute or stronger provider-owned isolation.
+Built-in environments do not expose cross-session sharing. To reuse native compute or storage across eve sessions, define a [custom provider](/docs/sandbox/custom-providers) whose connection is a session-owned logical sandbox view and that keeps shared resources outside the connection's `stop()` and the provider's `onSessionEnd()`. A session-specific path is not an isolation boundary; mutually untrusted sessions require separate native compute or stronger provider-owned isolation.
### Share a parent sandbox
@@ -175,73 +175,7 @@ Each call sends the same bytes for the same file, so the model still sees attach
## Custom providers
-Define a provider with `defineSandboxProvider()` from `eve/sandbox/provider`. The five generic parameters describe environment options, live options, the prepared artifact, minimal serialized session state, and the provider-specific sandbox session type:
-
-```ts
-import type { SandboxSession } from "eve/sandbox";
-import { defineSandboxProvider } from "eve/sandbox/provider";
-
-export const AcmeSandbox = defineSandboxProvider<
- { image: string; prepare?: (sandbox: SandboxSession) => Promise<void> },
- { networkPolicy?: "allow-all" | "deny-all" },
- { templateId: string },
- { name: string; version: 1 },
- SandboxSession
->({
- name: "acme",
- environment(options) {
- const client = createAcmeClient(options);
- // The session key alone names the sandbox, so every caller finds the same one.
- const sandboxName = (sessionId: string) => `eve-${sessionId}`;
-
- return {
- async onSessionEnd(ctx, state, { reason }) {
- // `state` is null when the session never recorded it, for example when
- // only a subagent that shares the sandbox opened it.
- await client.deleteIfExists({ name: state?.name ?? sandboxName(ctx.session.id), reason });
- },
-
- async prepare(ctx) {
- const temporary = await client.createTemporary({
- files: await ctx.files.list(),
- resources: ctx.resources,
- });
- const sandbox = adaptAcmeSandbox(temporary);
- await options?.prepare?.(sandbox);
- return { templateId: (await temporary.capture()).id };
- },
-
- async start(ctx, liveOptions, artifact) {
- const name = sandboxName(ctx.session.id);
- // Returns the sandbox with this name, or atomically creates it with these options.
- const remote = await client.getOrCreate({
- name,
- networkPolicy: liveOptions?.networkPolicy,
- templateId: artifact.templateId,
- });
- return { handle: createHandle(remote), state: { name, version: 1 } };
- },
-
- async resume(_ctx, artifact, state) {
- const remote = await client.resume({ name: state.name, templateId: artifact.templateId });
- return createHandle(remote);
- },
- };
- },
-});
-```
-
-`prepare()` returns the complete JSON-serializable artifact.
-
-`start()` must be an idempotent upsert keyed by `ctx.session.id`: return the live sandbox for that key when one exists, and create it otherwise. eve can call `start()` for one key more than once, from different processes and deployments, and concurrently. A subagent that shares its parent's sandbox can open it before the parent does, and two processes can race to create it. Derive the sandbox's identity from the key, plus a provider-level namespace such as a project or account when names would otherwise collide. Never derive it from the open options or the artifact, which can differ between callers and deployments; apply them only when `start()` creates the sandbox. eve persists the minimal JSON-compatible state `start()` returns. Process restarts call `resume()` with only the current context, that state, and the target deployment's exact artifact.
-
-`onSessionEnd()` is required. eve calls it for every owning durable session that reaches a completed, expired, or failed terminal outcome, including sessions with no recorded sandbox state. A failed step or process loss can create a sandbox before its state is checkpointed, so the last checkpoint cannot establish that no sandbox exists. The hook receives the session context, the persisted provider state or `null`, and a `reason` of `"completed"`, `"expired"`, or `"failed"`. Delete whatever exists under `ctx.session.id` without depending on a live handle, and find it from the key when the state is `null`. The hook must succeed when nothing exists and must be idempotent: eve retries the cleanup step and logs an exhausted failure without replacing the session's terminal outcome. A subagent that shares its parent's sandbox does not call the hook, because cleanup belongs to the parent. An `invokeTool` call without a key also calls `onSessionEnd()` when the call ends if it requested sandbox access, including an initialization attempt that failed.
-
-Provider handles implement `onSandboxStop()`, `onRuntimeShutdown()`, and `onSandboxDelete()`. These handle-level methods cover authored stop or delete calls and process shutdown; `onSessionEnd()` is the single provider hook for durable terminal session cleanup. eve does not delete a sandbox whose initialization failed: the next access runs the selector against it again, and session end removes it.
-
-Open options belong to `start()` and are not serialized or passed to `resume()`. A provider must put any immutable option-derived data needed for reconnection in its session state. With the current immutable-state contract, `resume()` reconnects existing native state and fails if it is gone rather than recreating callback side effects. When a built-in provider reports that the native sandbox is gone, eve clears the session's provider state and reruns the selector. A custom provider may define start-only callback fields, but built-in providers initialize the sandbox in `defineSandbox()` after `open()`.
-
-Preparation discovers authored files through `ctx.files`; core keeps project layout and artifact storage keys private. Keep provider SDK values behind the provider. `environment.open()` preserves the provider's sandbox capability type, while the heterogeneous runtime registry erases it to eve's common session surface.
+To run sandboxes on a backend eve does not ship, define a provider with `defineSandboxProvider()` from `eve/sandbox/provider`. A provider implements a byte-level connection to one sandbox (`spawn`, `readFile`, `writeFiles`, `removePath`, and `stop`) and a lifecycle of `prepare`, `start`, `resume`, and `onSessionEnd`. eve derives the full sandbox session from the connection, seeds workspace and skill files into the provider's templates during `eve build`, and maps `sandbox.stop()`, `sandbox.delete()`, and server shutdown onto the lifecycle. [Custom sandbox providers](/docs/sandbox/custom-providers) has a complete example and the full contract.
## Providers
diff --git a/docs/sandbox/meta.json b/docs/sandbox/meta.json
index db48aa286..fcd656949 100644
--- a/docs/sandbox/meta.json
+++ b/docs/sandbox/meta.json
@@ -1,5 +1,13 @@
{
"title": "Sandbox",
"defaultOpen": false,
- "pages": ["index", "default", "vercel", "docker", "just-bash", "troubleshooting"]
+ "pages": [
+ "index",
+ "default",
+ "vercel",
+ "docker",
+ "just-bash",
+ "custom-providers",
+ "troubleshooting"
+ ]
}
diff --git a/docs/sandbox/troubleshooting.mdx b/docs/sandbox/troubleshooting.mdx
index 3a616655b..f42d852fa 100644
--- a/docs/sandbox/troubleshooting.mdx
+++ b/docs/sandbox/troubleshooting.mdx
@@ -95,6 +95,7 @@ The build recorded an artifact, but the provider can no longer use its template.
| Docker | The Docker daemon has no image with that name: it was removed, for example by `docker image prune -a`, or the build used another Docker daemon. |
| Vercel | The Vercel Sandbox snapshot expired or was deleted. |
| just-bash | The template directory under `.eve/sandbox-cache/` was deleted, or the build ran on another machine. |
+| Custom | The image, snapshot, or template that the artifact names no longer exists, so the provider threw `SandboxTemplateNotProvisionedError`. |
The runtime never recreates a template. Run `eve build` again and deploy its output.
@@ -146,6 +147,42 @@ Timed out after 10 minutes waiting for another request or eve dev worker to prep
Another request or `eve dev` worker is still preparing environments. Check the `eve dev` output, or run `eve logs`, to find the slow step, such as an image pull, a Dockerfile build, or a `prepare` callback. Retry after preparation finishes, or restart `eve dev` to cancel it.
+## Custom provider errors
+
+These errors come from a provider defined with `defineSandboxProvider()`, or from a keyed tool call on a provider that cannot keep its sandbox. See [Custom sandbox providers](/docs/sandbox/custom-providers).
+
+### `cannot keep a sandbox between invokeTool calls`
+
+```text
+Sandbox provider "acme" cannot keep a sandbox between invokeTool calls, so a call with a key cannot open one.
+```
+
+A keyed `invokeTool` call, such as an MCP tool session, requested the sandbox, and the provider does not keep sandboxes between calls. Call the tool without a key, use Vercel Sandbox or just-bash, or set `toolSessions: true` on a custom provider that bounds how long it keeps those sandboxes. Docker does not support keyed calls. See [Keep sandboxes for keyed tool calls](/docs/sandbox/custom-providers#keep-sandboxes-for-keyed-tool-calls).
+
+### `Sandbox connection extensions cannot replace the session members eve provides`
+
+```text
+Sandbox connection extensions cannot replace the session members eve provides: run. Rename them.
+```
+
+The connection's `extensions` define a member that eve already provides on every sandbox session, such as `run`, `readFile`, `stop`, or `delete`. Rename the extension member.
+
+### `ctx.templateKey() reserves`
+
+```text
+ctx.templateKey() reserves "sourceRevision": eve adds the workspace and skill files and the sandbox source revision itself.
+```
+
+The identity passed to `ctx.templateKey()` in `prepare()` sets `resources` or `sourceRevision`. eve adds both to every template key. Rename that identity field.
+
+### `returned non-serializable session state`
+
+```text
+Sandbox provider "acme" returned non-serializable session state.
+```
+
+`start()` returned state that is not JSON-compatible, such as a class instance, a function, or `undefined`. Return only strings, numbers, booleans, `null`, arrays, and plain objects, and keep live clients in the connection instead.
+
## Provider setup errors
### Docker is not installed or not running
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/agent.ts b/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/agent.ts
index e6c30d888..525c109e9 100644
--- a/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/agent.ts
+++ b/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/agent.ts
@@ -7,9 +7,14 @@ export default defineAgent({
...e2eSubagentConfig({ mock: respond }),
});
+/** Runs each scenario's tools in order, then replies with the last tool's output. */
function respond(request: MockModelRequest): MockModelResponse | string {
- const result = request.toolResults.find((entry) => entry.name === "verify-provider-session");
- return result === undefined
- ? { toolCalls: [{ input: {}, name: "verify-provider-session" }] }
- : String(result.output);
+ const message = request.lastUserMessage ?? "";
+ const tools = message.includes("maintenance")
+ ? ["leave-note", "check-note"]
+ : ["verify-provider-session"];
+ const next = tools.find((name) => !request.toolResults.some((entry) => entry.name === name));
+ if (next !== undefined) return { toolCalls: [{ input: {}, name: next }] };
+ const last = request.toolResults.find((entry) => entry.name === tools.at(-1));
+ return typeof last?.output === "string" ? last.output : JSON.stringify(last?.output);
}
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/sandbox.ts b/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/sandbox.ts
index ce6741cfb..b3752b51a 100644
--- a/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/sandbox.ts
+++ b/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/sandbox.ts
@@ -1,91 +1,107 @@
-import { defineSandbox, type SandboxSession } from "eve/sandbox";
-import { defineSandboxProvider } from "eve/sandbox/provider";
+import { randomUUID } from "node:crypto";
+
+import { defineSandbox } from "eve/sandbox";
+import {
+ defineSandboxProvider,
+ SandboxSessionGoneError,
+ type SandboxConnection,
+} from "eve/sandbox/provider";
export const CUSTOM_PROVIDER_TOKEN = "custom-provider-session-ok-P7M";
-type CustomSession = SandboxSession & { probe(): Promise<string> };
-type CustomState = { readonly marker: string; readonly version: 1 };
+/**
+ * One in-memory machine per session, standing in for a remote sandbox
+ * service. A machine lives in this process only, so a step that runs in
+ * another process finds it gone and continues in a fresh one, as it would
+ * after the service reclaimed it.
+ */
+interface Machine {
+ readonly files: Map<string, Uint8Array>;
+ readonly id: string;
+}
+
+type CustomExtensions = {
+ /** Returns the session marker the selector writes into each new machine. */
+ probe(): Promise<string>;
+ /** The machine backing this sandbox; a fresh sandbox has a new one. */
+ machineId(): string;
+ /** Removes the machine from the service, as maintenance would. */
+ retireForMaintenance(): Promise<void>;
+};
-const provider = defineSandboxProvider<undefined, undefined, null, CustomState, CustomSession>({
+const machines = new Map<string, Machine>();
+
+const CustomSandbox = defineSandboxProvider({
name: "custom-provider-session",
environment() {
return {
- // Each handle keeps its files in memory, so nothing outlives the session.
- async onSessionEnd() {},
- async prepare() {
- return null;
- },
- async resume(_context, _artifact, state) {
- return createHandle(state.marker);
+ async prepare(ctx) {
+ return { templateKey: ctx.templateKey({ machine: "memory", version: 1 }) };
},
- async start(context) {
- const marker = `${CUSTOM_PROVIDER_TOKEN}:${context.session.id}`;
+ async start(ctx) {
+ // An upsert on the session id: a live machine is returned unchanged.
+ let machine = machines.get(ctx.session.id);
+ if (machine === undefined) {
+ machine = { files: new Map(), id: randomUUID() };
+ machines.set(ctx.session.id, machine);
+ }
return {
- handle: createHandle(marker),
- state: { marker, version: 1 },
+ connection: connect(ctx.session.id, machine),
+ state: { machineId: machine.id, version: 1 },
};
},
+ async resume(ctx, _artifact, state) {
+ const machine = machines.get(ctx.session.id);
+ if (machine?.id !== state.machineId) {
+ throw new SandboxSessionGoneError(`Machine "${state.machineId}" no longer exists.`);
+ }
+ return connect(ctx.session.id, machine);
+ },
+ async onSessionEnd(ctx) {
+ machines.delete(ctx.session.id);
+ },
};
},
});
-export const environment = provider.environment();
+export const environment = CustomSandbox.environment();
export default defineSandbox(async () => {
const sandbox = await environment.open();
- await sandbox.writeTextFile({ content: await sandbox.probe(), path: "/workspace/probe.txt" });
+ await sandbox.writeTextFile({ content: await sandbox.probe(), path: "probe.txt" });
return sandbox;
});
-function createHandle(marker: string) {
- const files = new Map<string, Uint8Array>([["/workspace/probe.txt", Buffer.from(marker)]]);
- const resolvePath = (path: string) =>
- path.startsWith("/") ? path : `/workspace/${path.replace(/^\.\//u, "")}`;
- const session = {
- async probe() {
- return marker;
- },
- async readBinaryFile({ path }: { path: string }) {
- const content = files.get(resolvePath(path));
- if (content === undefined) throw new Error(`Missing fixture file: ${path}`);
- return content;
- },
- async readFile({ path }: { path: string }) {
- const content = files.get(resolvePath(path));
- if (content === undefined) throw new Error(`Missing fixture file: ${path}`);
- return new Blob([Buffer.from(content)]).stream();
- },
- async readTextFile({ path }: { path: string }) {
- const content = files.get(resolvePath(path));
- if (content === undefined) throw new Error(`Missing fixture file: ${path}`);
- return Buffer.from(content).toString("utf8");
- },
- async removePath({ path }: { path: string }) {
- files.delete(resolvePath(path));
- },
- resolvePath,
- async run() {
- return { exitCode: 0, stderr: "", stdout: "" };
- },
+function connect(sessionId: string, machine: Machine): SandboxConnection<CustomExtensions> {
+ return {
async spawn() {
- throw new Error("spawn is not used by this fixture.");
+ return {
+ kill: async () => {},
+ stderr: new Blob(["This fixture machine runs no commands.\n"]).stream(),
+ stdout: new Blob([]).stream(),
+ wait: async () => ({ exitCode: 127 }),
+ };
},
- async writeBinaryFile({ content, path }: { content: Uint8Array; path: string }) {
- files.set(resolvePath(path), content);
+ async readFile({ path }) {
+ return machine.files.get(path) ?? null;
},
- async writeFile({ content, path }: { content: ReadableStream<Uint8Array>; path: string }) {
- const chunks: Uint8Array[] = [];
- for await (const chunk of content) chunks.push(chunk);
- files.set(resolvePath(path), Buffer.concat(chunks));
+ async writeFiles({ files }) {
+ for (const file of files) machine.files.set(file.path, file.content);
},
- async writeTextFile({ content, path }: { content: string; path: string }) {
- files.set(resolvePath(path), Buffer.from(content));
+ async removePath({ force, path, recursive }) {
+ const removed = [...machine.files.keys()].filter(
+ (file) => file === path || (recursive === true && file.startsWith(`${path}/`)),
+ );
+ if (removed.length === 0 && force !== true) throw new Error(`No such path: ${path}`);
+ for (const file of removed) machine.files.delete(file);
+ },
+ async stop() {},
+ extensions: {
+ machineId: () => machine.id,
+ probe: async () => `${CUSTOM_PROVIDER_TOKEN}:${sessionId}`,
+ async retireForMaintenance() {
+ if (machines.get(sessionId) === machine) machines.delete(sessionId);
+ },
},
- } satisfies CustomSession;
- return {
- sandbox: Object.freeze(session),
- async onRuntimeShutdown() {},
- async onSandboxDelete() {},
- async onSandboxStop() {},
};
}
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/tools/check-note.ts b/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/tools/check-note.ts
new file mode 100644
index 000000000..7b5611f16
--- /dev/null
+++ b/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/tools/check-note.ts
@@ -0,0 +1,17 @@
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+
+import { environment } from "../sandbox.js";
+
+export default defineTool({
+ description: "Checks the workspace for Alice's note.",
+ inputSchema: z.object({}),
+ async execute(_input, ctx) {
+ const sandbox = await ctx.getSandbox(environment);
+ return {
+ machine: sandbox.machineId(),
+ note: await sandbox.readTextFile({ path: "note.txt" }),
+ probe: await sandbox.readTextFile({ path: "probe.txt" }),
+ };
+ },
+});
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/tools/leave-note.ts b/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/tools/leave-note.ts
new file mode 100644
index 000000000..c7d6ffc79
--- /dev/null
+++ b/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/tools/leave-note.ts
@@ -0,0 +1,16 @@
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+
+import { environment } from "../sandbox.js";
+
+export default defineTool({
+ description: "Leaves Alice's note in the workspace, then lets the host retire her machine.",
+ inputSchema: z.object({}),
+ async execute(_input, ctx) {
+ const sandbox = await ctx.getSandbox(environment);
+ await sandbox.writeTextFile({ content: "Bob, the report is ready.", path: "note.txt" });
+ const machine = sandbox.machineId();
+ await sandbox.retireForMaintenance();
+ return { machine };
+ },
+});
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/custom-provider-gone-recovery.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/custom-provider-gone-recovery.eval.ts
new file mode 100644
index 000000000..5b4ab7117
--- /dev/null
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/custom-provider-gone-recovery.eval.ts
@@ -0,0 +1,35 @@
+import { defineEval } from "eve/evals";
+import { equals, includes } from "eve/evals/expect";
+
+const TOKEN = "custom-provider-session-ok-P7M";
+
+export default defineEval({
+ description:
+ "Sandbox: when a custom provider's resume() reports the sandbox gone, the session continues in a fresh sandbox.",
+ async test(t) {
+ const turn = await t.send(
+ "Ask the `custom-provider` subagent with message: Alice leaves Bob a note in the workspace, " +
+ "and then the sandbox host retires her machine for maintenance before Bob checks the workspace.",
+ );
+ turn.expectOk();
+ const started = turn.events.find(
+ (event) => event.type === "agent.started" && event.data.name === "custom-provider",
+ );
+ if (started?.type !== "agent.started") {
+ throw new Error("The turn did not call the custom-provider subagent.");
+ }
+ const child = (await t.target.watchTurn(started.data.sessionId).result()).expectOk();
+
+ t.succeeded();
+ const left = child.requireToolCall("leave-note").output as { machine: string };
+ const checked = child.requireToolCall("check-note").output as {
+ machine: string;
+ note: string | null;
+ probe: string | null;
+ };
+ // The fresh sandbox has a new machine without Alice's note, and the selector ran again.
+ t.check(checked.machine === left.machine, equals(false));
+ t.check(checked.note, equals(null));
+ t.check(checked.probe, includes(TOKEN));
+ },
+});
diff --git a/packages/eve-code/test/integration/diagnostics.test.ts b/packages/eve-code/test/integration/diagnostics.test.ts
index 9841a996a..c289fabbd 100644
--- a/packages/eve-code/test/integration/diagnostics.test.ts
+++ b/packages/eve-code/test/integration/diagnostics.test.ts
@@ -155,6 +155,9 @@ function commandSandbox(
async writeBinaryFile() {
throw new Error("not used by this test");
},
+ async writeFiles() {
+ throw new Error("not used by this test");
+ },
async writeTextFile() {
throw new Error("not used by this test");
},
diff --git a/packages/eve-code/test/integration/patch.test.ts b/packages/eve-code/test/integration/patch.test.ts
index 88741eb12..102be1b8d 100644
--- a/packages/eve-code/test/integration/patch.test.ts
+++ b/packages/eve-code/test/integration/patch.test.ts
@@ -505,6 +505,9 @@ function memorySandbox(
async writeBinaryFile() {
throw new Error("not used by this test");
},
+ async writeFiles() {
+ throw new Error("not used by this test");
+ },
};
}
diff --git a/packages/eve/extension-contracts/compatibility/channel/v67.ts b/packages/eve/extension-contracts/compatibility/channel/v67.ts
new file mode 100644
index 000000000..5b8adf5cb
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/channel/v67.ts
@@ -0,0 +1,21 @@
+// Epoch 67 of the channel capability: sandbox sessions typed from the AI SDK. Epoch 68 declares
+// eve-owned session types with the same methods and adds `writeFiles`, which is additive.
+import { defineChannel, POST } from "#public/channels/index.js";
+
+export default defineChannel({
+ routes: [
+ POST("/reports", async (_request, { from }) => {
+ const { session } = await from("reports").create({
+ auth: null,
+ history: [{ role: "user", text: "Alice requested a report." }],
+ });
+ return Response.json({ sessionId: session.id });
+ }),
+ ],
+ events: {
+ "turn.completed": async (_event, _channel, ctx) => {
+ const sandbox = await ctx.getSandbox();
+ await sandbox.writeTextFile({ content: "Report sent to Bob.", path: "reports/status.txt" });
+ },
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/connection/v55.ts b/packages/eve/extension-contracts/compatibility/connection/v55.ts
new file mode 100644
index 000000000..06e0fa2c5
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/connection/v55.ts
@@ -0,0 +1,14 @@
+// Epoch 55 of the connection capability. Epoch 56 changes only the sandbox session types it reaches
+// (eve-owned declarations plus `writeFiles`); connection authoring is unchanged, as this example shows.
+import { defineDynamic, defineMcpClientConnection } from "#public/connections/index.js";
+
+export default defineDynamic({
+ events: {
+ "turn.started": (_event, ctx) =>
+ defineMcpClientConnection({
+ description: "Read Alice's support queue.",
+ url: "https://support.example.com/mcp",
+ headers: { "X-Session": ctx.session.id },
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicTool/v90.ts b/packages/eve/extension-contracts/compatibility/dynamicTool/v90.ts
new file mode 100644
index 000000000..b623ea8e8
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicTool/v90.ts
@@ -0,0 +1,21 @@
+// Epoch 90 of the dynamicTool capability: sandbox sessions typed from the AI SDK. Epoch 91 declares
+// eve-owned session types with the same methods and adds `writeFiles`, which is additive.
+import { defineDynamic, defineTool } from "#public/tools/index.js";
+
+export default defineDynamic({
+ events: {
+ "turn.started": () =>
+ defineTool({
+ description: "List Bob's report files.",
+ inputSchema: { type: "object", properties: {} },
+ async execute(_input, ctx) {
+ const sandbox = await ctx.getSandbox();
+ const result = await sandbox.run({
+ command: "ls reports",
+ workingDirectory: "/workspace",
+ });
+ return result.stdout.split("\n").filter(Boolean);
+ },
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/hook/v49.ts b/packages/eve/extension-contracts/compatibility/hook/v49.ts
new file mode 100644
index 000000000..d20aea967
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/hook/v49.ts
@@ -0,0 +1,12 @@
+// Epoch 49 of the hook capability: sandbox sessions typed from the AI SDK. Epoch 50 declares
+// eve-owned session types with the same methods and adds `writeFiles`, which is additive.
+import { defineHook } from "#public/hooks/index.js";
+
+export default defineHook({
+ events: {
+ "turn.completed": async (_event, ctx) => {
+ const sandbox = await ctx.getSandbox();
+ await sandbox.writeTextFile({ content: ctx.session.id, path: ".eve/last-turn" });
+ },
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/state/v14.ts b/packages/eve/extension-contracts/compatibility/state/v14.ts
new file mode 100644
index 000000000..ba60684ec
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/state/v14.ts
@@ -0,0 +1,9 @@
+// Epoch 14 of the state capability. Epoch 15 changes only the sandbox session types it reaches
+// (eve-owned declarations plus `writeFiles`); state authoring is unchanged, as this example shows.
+import { defineState } from "#public/context/index.js";
+
+export const visits = defineState("compatibility.visits", () => ({ count: 0, visitor: "Alice" }));
+export function recordVisit(): number {
+ visits.update((current) => ({ ...current, count: current.count + 1 }));
+ return visits.get().count;
+}
diff --git a/packages/eve/extension-contracts/compatibility/tool/v100.ts b/packages/eve/extension-contracts/compatibility/tool/v100.ts
new file mode 100644
index 000000000..f1b3dd690
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/tool/v100.ts
@@ -0,0 +1,16 @@
+// Epoch 100 of the tool capability: sandbox sessions typed from the AI SDK. Epoch 101 declares
+// eve-owned session types with the same methods and adds `writeFiles`, which is additive.
+import { defineTool } from "#public/tools/index.js";
+
+export default defineTool({
+ description: "Summarize Alice's notes in the sandbox.",
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
+ async execute(_input, ctx) {
+ const sandbox = await ctx.getSandbox();
+ const env: Record<string, string> = { NOTES_OWNER: "alice" };
+ await sandbox.writeTextFile({ content: "Feed the cat.", path: "notes/alice.txt" });
+ const result = await sandbox.run({ command: "wc -w notes/alice.txt", env });
+ const text = await sandbox.readTextFile({ path: "notes/alice.txt", startLine: 1 });
+ return { exitCode: result.exitCode, text, words: result.stdout.trim() };
+ },
+});
diff --git a/packages/eve/extension-contracts/reports/channel/v68.json b/packages/eve/extension-contracts/reports/channel/v68.json
new file mode 100644
index 000000000..c08a057cb
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/channel/v68.json
@@ -0,0 +1,24 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "channel",
+ "epoch": 68,
+ "sha256": "e42c40c8c20fc9acf037bab4552d0ec6f4b6296225e9d5397369dc414d6b353c",
+ "exports": [
+ "DELETE",
+ "GET",
+ "HEAD",
+ "InvalidSessionHistoryError",
+ "OPTIONS",
+ "PATCH",
+ "POST",
+ "PUT",
+ "SessionStrandedError",
+ "WS",
+ "attachmentError",
+ "createWebSocketUpgradeServer",
+ "defineChannel",
+ "disableRoute",
+ "isChannel",
+ "isDisabledRouteSentinel"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/connection/v56.json b/packages/eve/extension-contracts/reports/connection/v56.json
new file mode 100644
index 000000000..0053c0f14
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/connection/v56.json
@@ -0,0 +1,16 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "connection",
+ "epoch": 56,
+ "sha256": "908383e01bd15a58cf6a736097962dba523367fa9cf11adb76f8941e46271e99",
+ "exports": [
+ "ConnectionAuthorizationFailedError",
+ "ConnectionAuthorizationRequiredError",
+ "defineDynamic",
+ "defineInteractiveAuthorization",
+ "defineMcpClientConnection",
+ "defineOpenAPIConnection",
+ "isConnectionAuthorizationFailedError",
+ "isConnectionAuthorizationRequiredError"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v91.json b/packages/eve/extension-contracts/reports/dynamicTool/v91.json
new file mode 100644
index 000000000..47feda136
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicTool/v91.json
@@ -0,0 +1,16 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicTool",
+ "epoch": 91,
+ "sha256": "451c51f493fd60fafe8d8c7833c4f787613b91d38b6af3f98017ac51e96eb25c",
+ "exports": [
+ "DynamicToolEntry",
+ "DynamicToolEvents",
+ "DynamicToolResult",
+ "DynamicToolSet",
+ "auto",
+ "defineDurableCallback",
+ "defineDurableSchema",
+ "defineDynamic"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/hook/v50.json b/packages/eve/extension-contracts/reports/hook/v50.json
new file mode 100644
index 000000000..fa7bbb1a2
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/hook/v50.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "hook",
+ "epoch": 50,
+ "sha256": "203ae7d87aeddd3bf5976d5eb0a91a83c105cc6542318dbe83cf112507a1dcd5",
+ "exports": ["defineHook"]
+}
diff --git a/packages/eve/extension-contracts/reports/state/v15.json b/packages/eve/extension-contracts/reports/state/v15.json
new file mode 100644
index 000000000..d35666ecb
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/state/v15.json
@@ -0,0 +1,15 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "state",
+ "epoch": 15,
+ "sha256": "c6ef401da56721e1248bafd205f6879ba4a3c3ff07be31ea48eb1bdd98defe1a",
+ "exports": [
+ "Session",
+ "SessionAuth",
+ "SessionAuthContext",
+ "SessionContext",
+ "SessionParent",
+ "SessionTurn",
+ "defineState"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/tool/v101.json b/packages/eve/extension-contracts/reports/tool/v101.json
new file mode 100644
index 000000000..7c5d1cc4e
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/tool/v101.json
@@ -0,0 +1,29 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "tool",
+ "epoch": 101,
+ "sha256": "a93f0ad96135c5b27ef1eaaafcaa226070ab64b66f64ed83b9d8d5d19afb3fa3",
+ "exports": [
+ "AgentRouterInput",
+ "AgentRouterTool",
+ "WorkflowStepToolContext",
+ "WorkflowTool",
+ "WorkflowToolDefinition",
+ "WorkflowToolInput",
+ "WorkflowToolOptions",
+ "agentRouter",
+ "decide",
+ "defaultWebSearch",
+ "defineTool",
+ "defineWorkflowTool",
+ "disableTool",
+ "isDisabledToolSentinel",
+ "isWebSearchToolDefinition",
+ "serializeModelInputSchema",
+ "toolOutput",
+ "toolOutputPart",
+ "toolResultFrom",
+ "webSearch",
+ "workflow"
+ ]
+}
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index 8f8e1b476..16cebeb10 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -22,10 +22,10 @@ interface ExtensionCapabilityContract {
const EXTENSION_CAPABILITY_CONTRACTS = {
extension: { current: 1, supported: [1], dropped: {} },
tool: {
- current: 100,
+ current: 101,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 76, 77, 78, 80, 81, 82, 84,
- 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 97, 98, 99, 100,
+ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 97, 98, 99, 100, 101,
],
dropped: {
14: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
@@ -91,11 +91,11 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
dynamicTool: {
- current: 90,
+ current: 91,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 31, 32, 33, 52, 54,
60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 72, 73, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
- 85, 86, 87, 89, 90,
+ 85, 86, 87, 89, 90, 91,
],
dropped: {
21: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
@@ -137,10 +137,11 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
channel: {
- current: 67,
+ current: 68,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 29, 31, 36, 37, 38, 39, 40, 41, 42,
43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 65, 66, 67,
+ 68,
],
dropped: {
12: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
@@ -194,10 +195,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
connection: {
- current: 55,
+ current: 56,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 26, 32, 33, 34,
- 35, 36, 37, 38, 39, 40, 41, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 55,
+ 35, 36, 37, 38, 39, 40, 41, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 55, 56,
],
dropped: {
9: "Dynamic connection resolvers no longer receive conversation or channel continuation data",
@@ -214,9 +215,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
hook: {
- current: 49,
+ current: 50,
supported: [
20, 21, 22, 23, 25, 27, 31, 32, 33, 34, 35, 36, 37, 38, 39, 41, 42, 43, 44, 45, 46, 47, 49,
+ 50,
],
dropped: {
1: "Model identity moved from session.started runtime metadata to step.started call attribution.",
@@ -277,8 +279,8 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
config: { current: 1, supported: [1], dropped: {} },
state: {
- current: 14,
- supported: [1, 2, 3, 4, 5, 7, 9, 10, 12, 14],
+ current: 15,
+ supported: [1, 2, 3, 4, 5, 7, 9, 10, 12, 14, 15],
dropped: {
6: "Sandbox sessions no longer expose core identity and mutable networking is provider-specific.",
8: "SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities",
diff --git a/packages/eve/src/compiler/normalize-sandbox.test.ts b/packages/eve/src/compiler/normalize-sandbox.test.ts
index dfc0dd7f8..5e0a9b43a 100644
--- a/packages/eve/src/compiler/normalize-sandbox.test.ts
+++ b/packages/eve/src/compiler/normalize-sandbox.test.ts
@@ -1,8 +1,8 @@
import { describe, expect, it } from "vitest";
import { defineParentSandbox, defineSandbox } from "#public/definitions/sandbox.js";
-import { defineSandboxProvider } from "#shared/sandbox-provider.js";
+import { defineLegacySandboxProvider } from "#shared/sandbox-provider.js";
-const provider = defineSandboxProvider({
+const provider = defineLegacySandboxProvider({
name: "test",
environment: () => ({
async onSessionEnd() {},
diff --git a/packages/eve/src/context/dynamic-skill-lifecycle.test.ts b/packages/eve/src/context/dynamic-skill-lifecycle.test.ts
index 939afab35..17d54a82a 100644
--- a/packages/eve/src/context/dynamic-skill-lifecycle.test.ts
+++ b/packages/eve/src/context/dynamic-skill-lifecycle.test.ts
@@ -27,7 +27,7 @@ import { defineSandbox } from "#public/definitions/sandbox.js";
import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";
import {
- defineSandboxProvider,
+ defineLegacySandboxProvider,
type SandboxProviderSessionContext,
} from "#shared/sandbox-provider.js";
import { SandboxSessionGoneError } from "#shared/sandbox-session-gone-error.js";
@@ -76,7 +76,7 @@ function recreatableSandbox() {
onSandboxDelete: async () => {},
onSandboxStop: async () => {},
});
- const environment = defineSandboxProvider({
+ const environment = defineLegacySandboxProvider({
name: "recreatable",
environment: () => ({
onSessionEnd: async () => {},
@@ -556,7 +556,7 @@ describe("dynamic skill supporting files", () => {
const manifest = ctx.get(DynamicSkillManifestKey);
content = "B";
- vi.spyOn(sandbox.session, "writeBinaryFile").mockRejectedValueOnce(new Error("disk full"));
+ vi.spyOn(sandbox.session, "writeFiles").mockRejectedValueOnce(new Error("disk full"));
await expect(dispatch(ctx, resolver)).rejects.toThrow("disk full");
expect(ctx.get(DynamicSkillManifestKey)).toBe(manifest);
expect(ctx.get(DynamicSkillSandboxKey)).toEqual({});
diff --git a/packages/eve/src/execution/invoke-tool.test.ts b/packages/eve/src/execution/invoke-tool.test.ts
index bb797f6a1..fbcae127d 100644
--- a/packages/eve/src/execution/invoke-tool.test.ts
+++ b/packages/eve/src/execution/invoke-tool.test.ts
@@ -5,13 +5,12 @@ import type { SessionAuthContext } from "#channel/types.js";
import { shutdownActiveSandboxHandles } from "#execution/sandbox/active-handles.js";
import { invokeTool, type InvokeToolRuntime } from "#execution/invoke-tool.js";
import { createToolExecuteWithAuth } from "#execution/tool-auth.js";
-import { withToolSessionSandboxes } from "#execution/tool-session/sandbox.js";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";
import { defineSandbox } from "#public/definitions/sandbox.js";
import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";
-import { defineSandboxProvider } from "#shared/sandbox-provider.js";
+import { defineSandboxProvider, type SandboxConnection } from "#sandbox/provider.js";
import type { ToolContext } from "#tools/definition.js";
import { defineJsonSchema } from "#tools/schema.js";
@@ -48,125 +47,122 @@ function tool(
};
}
+/** A connection over an in-memory sandbox; `stop` and `close` are spies. */
+function connect(sandbox: ReturnType<typeof mockSandbox>, stop = vi.fn(async () => {})) {
+ const { session } = sandbox;
+ return {
+ readFile: (options: { readonly path: string }) => session.readBinaryFile(options),
+ removePath: session.removePath,
+ spawn: session.spawn,
+ stop,
+ writeFiles: session.writeFiles,
+ } satisfies SandboxConnection;
+}
+
+function registryFor(
+ environment: ReturnType<ReturnType<typeof defineSandboxProvider>["environment"]>,
+ options: { readonly failSelector?: () => boolean } = {},
+): RuntimeSandboxRegistry {
+ return {
+ sandbox: {
+ definition: {
+ environment,
+ kind: "independent",
+ logicalPath: "sandbox.ts",
+ revisionHash: "hash",
+ selector: defineSandbox(async () => {
+ const sandbox = await environment.open();
+ if (options.failSelector?.() === true) throw new Error("selector failed");
+ return sandbox;
+ }),
+ sourceId: "sandbox",
+ sourceKind: "module",
+ },
+ workspaceResourceRoot: { logicalPath: "", rootEntries: [] },
+ },
+ };
+}
+
/** A provider that keeps each call's sandbox under its session id; `deleted` records cleanup by id. */
-function sandboxes(options: { readonly startGate?: Promise<void> } = {}) {
+function sandboxes(
+ options: { readonly closeError?: Error; readonly startGate?: Promise<void> } = {},
+) {
const started: string[] = [];
- const deleted = vi.fn(async (_sessionId: string) => {});
+ const deleted = vi.fn(async (_sessionId: string, _reason: string) => {});
const shutdown = vi.fn(async () => {});
- const start = vi.fn(async (context: { readonly session: { readonly id: string } }) => {
- started.push(context.session.id);
- await options.startGate;
- const sandbox = mockSandbox();
- return {
- handle: {
- sandbox: sandbox.session,
- onRuntimeShutdown: shutdown,
- onSandboxDelete: async () => deleted(context.session.id),
- onSandboxStop: async () => {},
- },
- state: null,
- };
+ const closed = vi.fn(async () => {
+ if (options.closeError !== undefined) throw options.closeError;
});
const environment = defineSandboxProvider({
name: "memory",
environment: () => ({
- onSessionEnd: async (context: { readonly session: { readonly id: string } }) =>
- deleted(context.session.id),
+ onSessionEnd: async (context, _state, { reason }) => deleted(context.session.id, reason),
prepare: async () => null,
resume: async () => {
throw new Error("a call's sandbox is never resumed");
},
- start,
+ async start(context) {
+ started.push(context.session.id);
+ await options.startGate;
+ return { connection: { ...connect(mockSandbox(), shutdown), close: closed }, state: null };
+ },
}),
}).environment();
- const registry: RuntimeSandboxRegistry = {
- sandbox: {
- definition: {
- environment,
- kind: "independent",
- logicalPath: "sandbox.ts",
- revisionHash: "hash",
- selector: defineSandbox(async () => await environment.open()),
- sourceId: "sandbox",
- sourceKind: "module",
- },
- workspaceResourceRoot: { logicalPath: "", rootEntries: [] },
- },
- };
- return { deleted, registry, shutdown, started };
+ return { closed, deleted, registry: registryFor(environment), shutdown, started };
}
/**
- * A provider whose `start` is an upsert on the session id, opted into tool
- * sessions as Vercel Sandbox and just-bash are. Each open hands out its own
- * handle over the shared sandbox, as just-bash runs one interpreter per
- * handle; `released` records which handles a call let go of, and `stopped`
- * and `shutdown` which were stopped through the sandbox API or at server
- * shutdown.
+ * A provider whose `start` is an upsert on the session id and that sets
+ * `toolSessions`, as Vercel Sandbox and just-bash do. Each open hands out its
+ * own connection over the shared sandbox, as just-bash runs one interpreter
+ * per connection; `released` records which connections a call closed, and
+ * `stopped` any stop through the sandbox API or at server shutdown.
*/
function keyedSandboxes(options: { readonly failSelector?: () => boolean } = {}) {
- const live = new Map<string, { sandbox: ReturnType<typeof mockSandbox> }>();
+ const live = new Map<string, ReturnType<typeof mockSandbox>>();
const starts: string[] = [];
+ const kinds: string[] = [];
const handles: object[] = [];
const released: object[] = [];
- const stopped = vi.fn();
- const shutdown = vi.fn(async () => {});
+ const stopped = vi.fn(async () => {});
const deleted = vi.fn((sessionId: string) => void live.delete(sessionId));
const reopen = (sessionId: string) => {
- let entry = live.get(sessionId);
- if (entry === undefined) {
+ let sandbox = live.get(sessionId);
+ if (sandbox === undefined) {
starts.push(sessionId);
- entry = { sandbox: mockSandbox() };
- live.set(sessionId, entry);
+ sandbox = mockSandbox();
+ live.set(sessionId, sandbox);
}
- const handle = {
- sandbox: entry.sandbox.session,
- onRuntimeShutdown: shutdown,
- onSandboxDelete: async () => deleted(sessionId),
- onSandboxStop: stopped,
+ const connection = {
+ ...connect(sandbox, stopped),
+ close: async () => void released.push(connection),
};
- handles.push(handle);
- return handle;
+ handles.push(connection);
+ return connection;
};
const environment = defineSandboxProvider({
name: "keyed",
- environment: () =>
- withToolSessionSandboxes(
- {
- onSessionEnd: async (context: { readonly session: { readonly id: string } }) =>
- deleted(context.session.id),
- prepare: async () => null,
- resume: async (context: { readonly session: { readonly id: string } }) =>
- reopen(context.session.id),
- start: async (context: { readonly session: { readonly id: string } }) => ({
- handle: reopen(context.session.id),
- state: {},
- }),
- },
- {
- releaseHandle: async (handle) => void released.push(handle),
- },
- ),
- }).environment();
- const registry: RuntimeSandboxRegistry = {
- sandbox: {
- definition: {
- environment,
- kind: "independent",
- logicalPath: "sandbox.ts",
- revisionHash: "hash",
- selector: defineSandbox(async () => {
- const sandbox = await environment.open();
- if (options.failSelector?.() === true) throw new Error("selector failed");
- return sandbox;
- }),
- sourceId: "sandbox",
- sourceKind: "module",
+ environment: () => ({
+ onSessionEnd: async (context) => deleted(context.session.id),
+ prepare: async () => null,
+ resume: async (context) => reopen(context.session.id),
+ async start(context) {
+ kinds.push(context.kind);
+ return { connection: reopen(context.session.id), state: {} };
},
- workspaceResourceRoot: { logicalPath: "", rootEntries: [] },
- },
+ toolSessions: true,
+ }),
+ }).environment();
+ return {
+ deleted,
+ handles,
+ kinds,
+ live,
+ registry: registryFor(environment, options),
+ released,
+ starts,
+ stopped,
};
- return { deleted, handles, live, registry, released, shutdown, starts, stopped };
}
/** A tool that appends to a note in its sandbox and returns the note, after `gate` opens. */
@@ -302,6 +298,53 @@ describe("invokeTool", () => {
expect(shutdown).not.toHaveBeenCalled();
});
+ it("maps sandbox.stop() onto the connection and sandbox.delete() onto onSessionEnd", async () => {
+ const { closed, deleted, registry, shutdown } = sandboxes();
+ const runtime = runtimeWith(
+ [
+ tool("open", async (_input: unknown, ctx) => void (await ctx.getSandbox())),
+ tool("pause", async (_input: unknown, ctx) => await (await ctx.getSandbox()).stop()),
+ tool("discard", async (_input: unknown, ctx) => await (await ctx.getSandbox()).delete()),
+ ],
+ registry,
+ );
+ const reasons = () => deleted.mock.calls.map(([, reason]) => reason);
+
+ // Session end closes what this process holds for the call's connection.
+ expect(await invokeTool(runtime, "open", {}, { auth: alice })).toMatchObject({
+ status: "completed",
+ });
+ expect(closed).toHaveBeenCalledTimes(1);
+ expect(reasons()).toEqual(["completed"]);
+
+ // Stopping stops and closes the connection once, even when shutdown follows.
+ expect(await invokeTool(runtime, "pause", {}, { auth: alice })).toMatchObject({
+ status: "completed",
+ });
+ await shutdownActiveSandboxHandles();
+ expect(shutdown).toHaveBeenCalledOnce();
+ expect(closed).toHaveBeenCalledTimes(2);
+
+ expect(await invokeTool(runtime, "discard", {}, { auth: alice })).toMatchObject({
+ status: "completed",
+ });
+ expect(closed).toHaveBeenCalledTimes(3);
+ expect(reasons()).toEqual(["completed", "completed", "deleted", "completed"]);
+ });
+
+ it("deletes the sandbox even when closing the connection fails", async () => {
+ const { deleted, registry } = sandboxes({ closeError: new Error("interpreter stuck") });
+ const runtime = runtimeWith(
+ [tool("discard", async (_input: unknown, ctx) => await (await ctx.getSandbox()).delete())],
+ registry,
+ );
+
+ expect(await invokeTool(runtime, "discard", {}, { auth: alice })).toMatchObject({
+ status: "failed",
+ });
+ expect(deleted.mock.calls.map(([, reason]) => reason)).toEqual(["deleted", "completed"]);
+ });
+
it("deletes a sandbox whose start finishes after the call failed", async () => {
let finishStart!: () => void;
const startGate = new Promise<void>((resolve) => {
@@ -386,7 +429,7 @@ describe("invokeTool", () => {
});
it("leaves a keyed sandbox running and lets go of each call's handle when it ends", async () => {
- const { deleted, handles, registry, released, shutdown, stopped } = keyedSandboxes();
+ const { deleted, handles, kinds, registry, released, stopped } = keyedSandboxes();
let openGate!: () => void;
const held = runtimeWith(
[noteTool(new Promise<void>((resolve) => (openGate = resolve)))],
@@ -414,10 +457,10 @@ describe("invokeTool", () => {
expect(handles).toHaveLength(3);
expect(released).toEqual([handles[1], handles[0], handles[2]]);
- // No call's handle is left for server shutdown, and the sandbox itself stays.
+ // No call's connection is left for server shutdown, and the sandbox itself stays.
await shutdownActiveSandboxHandles();
- expect(shutdown).not.toHaveBeenCalled();
expect(stopped).not.toHaveBeenCalled();
+ expect(new Set(kinds)).toEqual(new Set(["tool-session"]));
expect(deleted).not.toHaveBeenCalled();
expect(await call("note", "c")).toMatchObject({ output: expect.stringMatching(/^[ab]{2}c$/u) });
});
diff --git a/packages/eve/src/execution/sandbox/abort-bound-session.test.ts b/packages/eve/src/execution/sandbox/abort-bound-session.test.ts
index 1f0bd05d5..34ff74940 100644
--- a/packages/eve/src/execution/sandbox/abort-bound-session.test.ts
+++ b/packages/eve/src/execution/sandbox/abort-bound-session.test.ts
@@ -6,9 +6,7 @@ import type {
SandboxCommandResult,
SandboxProcess,
SandboxSession,
- SandboxWriteFilesOptions,
} from "#shared/sandbox-session.js";
-import { SANDBOX_WRITE_FILES, writeSandboxFiles } from "#shared/sandbox-write-files.js";
import { bindSandboxAbortSignal } from "#execution/sandbox/abort-bound-session.js";
interface RecordedCall {
@@ -53,6 +51,9 @@ function createRecordingSession(calls: RecordedCall[]): SandboxSession {
writeTextFile: async (options) => {
record("writeTextFile", options.abortSignal);
},
+ writeFiles: async (options) => {
+ record("writeFiles", options.abortSignal);
+ },
removePath: async (options) => {
record("removePath", options.abortSignal);
},
@@ -73,6 +74,7 @@ describe("bindSandboxAbortSignal", () => {
await bound.writeFile({ content: new ReadableStream<Uint8Array>(), path: "a.txt" });
await bound.writeBinaryFile({ content: new Uint8Array(), path: "a.bin" });
await bound.writeTextFile({ content: "hello", path: "a.txt" });
+ await bound.writeFiles({ files: [{ content: new Uint8Array(), path: "a.bin" }] });
await bound.removePath({ path: "a.txt" });
expect(calls.map((call) => call.method)).toEqual([
@@ -84,6 +86,7 @@ describe("bindSandboxAbortSignal", () => {
"writeFile",
"writeBinaryFile",
"writeTextFile",
+ "writeFiles",
"removePath",
]);
for (const call of calls) {
@@ -93,23 +96,6 @@ describe("bindSandboxAbortSignal", () => {
expect(new Set(calls.map((call) => call.abortSignal)).size).toBe(calls.length);
});
- it("injects the bound signal into a provider's batch write", async () => {
- const calls: RecordedCall[] = [];
- const session = Object.assign(createRecordingSession(calls), {
- [SANDBOX_WRITE_FILES]: async (options: SandboxWriteFilesOptions) => {
- calls.push({ abortSignal: options.abortSignal, method: "writeFiles" });
- },
- });
- const controller = new AbortController();
- const bound = bindSandboxAbortSignal(session, controller.signal);
-
- await writeSandboxFiles(bound, { files: [{ content: new Uint8Array(), path: "a.bin" }] });
- controller.abort();
-
- expect(calls.map((call) => call.method)).toEqual(["writeFiles"]);
- expect(calls[0]?.abortSignal?.aborted).toBe(true);
- });
-
it("does not accumulate provider listeners on the bound signal", async () => {
const calls: RecordedCall[] = [];
const recordingSession = createRecordingSession(calls);
diff --git a/packages/eve/src/execution/sandbox/abort-bound-session.ts b/packages/eve/src/execution/sandbox/abort-bound-session.ts
index b8a4670c3..5f552d4b4 100644
--- a/packages/eve/src/execution/sandbox/abort-bound-session.ts
+++ b/packages/eve/src/execution/sandbox/abort-bound-session.ts
@@ -11,7 +11,6 @@ import type {
SandboxWriteFilesOptions,
SandboxWriteTextFileOptions,
} from "#shared/sandbox-session.js";
-import { getSandboxWriteFiles, SANDBOX_WRITE_FILES } from "#shared/sandbox-write-files.js";
/**
* Returns a sandbox session that applies `abortSignal` to every operation.
@@ -42,16 +41,11 @@ export function bindSandboxAbortSignal<TSession extends SandboxSession>(
session.writeBinaryFile({ ...options, abortSignal: compose(options.abortSignal) }),
writeTextFile: (options: SandboxWriteTextFileOptions) =>
session.writeTextFile({ ...options, abortSignal: compose(options.abortSignal) }),
+ writeFiles: (options: SandboxWriteFilesOptions) =>
+ session.writeFiles({ ...options, abortSignal: compose(options.abortSignal) }),
removePath: (options: SandboxRemovePathOptions) =>
session.removePath({ ...options, abortSignal: compose(options.abortSignal) }),
} satisfies SandboxSession;
- const writeFiles = getSandboxWriteFiles(session);
- if (writeFiles !== undefined) {
- Object.assign(bound, {
- [SANDBOX_WRITE_FILES]: (options: SandboxWriteFilesOptions) =>
- writeFiles({ ...options, abortSignal: compose(options.abortSignal) }),
- });
- }
// The spread retains provider-specific lifecycle methods not declared on SandboxSession.
return bound as TSession;
diff --git a/packages/eve/src/execution/sandbox/bash.test.ts b/packages/eve/src/execution/sandbox/bash.test.ts
index 6cffaad0d..6db2ce468 100644
--- a/packages/eve/src/execution/sandbox/bash.test.ts
+++ b/packages/eve/src/execution/sandbox/bash.test.ts
@@ -59,6 +59,7 @@ function createTestSandboxSession(result: SandboxCommandResult): SandboxSession
wait: async () => ({ exitCode: result.exitCode }),
}),
writeBinaryFile: async () => {},
+ writeFiles: async () => {},
writeFile: async () => {},
writeTextFile: async () => {},
};
diff --git a/packages/eve/src/execution/sandbox/bindings/docker.ts b/packages/eve/src/execution/sandbox/bindings/docker.ts
index 724041d83..1d652135a 100644
--- a/packages/eve/src/execution/sandbox/bindings/docker.ts
+++ b/packages/eve/src/execution/sandbox/bindings/docker.ts
@@ -50,7 +50,7 @@ import {
isSandboxPreparedArtifactRecord,
sandboxProviderResourceIdentity,
type SandboxPreparedArtifact,
- type SandboxProviderImplementation,
+ type LegacySandboxProviderImplementation,
type SandboxProviderSessionContext,
} from "#shared/sandbox-provider.js";
import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";
@@ -98,7 +98,7 @@ type DockerSandboxSessionState = {
export function createDockerSandboxProvider(
createOptions?: DockerSandboxEnvironmentOptions,
dockerCli?: DockerCli,
-): SandboxProviderImplementation<
+): LegacySandboxProviderImplementation<
DockerSandboxRuntimeOptions,
DockerSandboxPreparedArtifact,
DockerSandboxSessionState,
diff --git a/packages/eve/src/execution/sandbox/bindings/immutable-resources.ts b/packages/eve/src/execution/sandbox/bindings/immutable-resources.ts
index c9113052a..d8e752ab0 100644
--- a/packages/eve/src/execution/sandbox/bindings/immutable-resources.ts
+++ b/packages/eve/src/execution/sandbox/bindings/immutable-resources.ts
@@ -48,16 +48,19 @@ export async function hydrateSandboxProviderResources(input: {
}
}
-async function hydrateSandboxFromImmutableResources(session: SandboxSession): Promise<void> {
+export async function hydrateSandboxFromImmutableResources(
+ session: SandboxSession,
+ root = SANDBOX_RESOURCES_ROOT,
+): Promise<void> {
const result = await session.run({
command: [
"set -e",
- `if [ -d ${SANDBOX_RESOURCES_ROOT}/workspace ]; then cp -a ${SANDBOX_RESOURCES_ROOT}/workspace/. /workspace/; fi`,
- `if [ -d ${SANDBOX_RESOURCES_ROOT}/skills ]; then`,
+ `if [ -d ${root}/workspace ]; then cp -a ${root}/workspace/. /workspace/; fi`,
+ `if [ -d ${root}/skills ]; then`,
' mkdir -p "$HOME/.agents"',
' rm -rf "$HOME/.agents/skills"',
' mkdir -p "$HOME/.agents/skills"',
- ` cp -a ${SANDBOX_RESOURCES_ROOT}/skills/. "$HOME/.agents/skills/"`,
+ ` cp -a ${root}/skills/. "$HOME/.agents/skills/"`,
"fi",
].join("\n"),
});
diff --git a/packages/eve/src/execution/sandbox/bindings/just-bash.ts b/packages/eve/src/execution/sandbox/bindings/just-bash.ts
index cf4ecd161..79adde6e0 100644
--- a/packages/eve/src/execution/sandbox/bindings/just-bash.ts
+++ b/packages/eve/src/execution/sandbox/bindings/just-bash.ts
@@ -34,7 +34,7 @@ import {
providerResourceTargetFiles,
sandboxProviderResourceIdentity,
type SandboxPreparedArtifact,
- type SandboxProviderImplementation,
+ type LegacySandboxProviderImplementation,
type SandboxProviderSessionContext,
} from "#shared/sandbox-provider.js";
import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";
@@ -53,7 +53,7 @@ type JustBashSessionState = { readonly rootPath: string; readonly version: 2 };
export function createJustBashSandboxProvider(
authoredOptions: JustBashSandboxCreateOptions | undefined = undefined,
-): SandboxProviderImplementation<
+): LegacySandboxProviderImplementation<
undefined,
JustBashPreparedArtifact,
JustBashSessionState,
diff --git a/packages/eve/src/execution/sandbox/bindings/vercel-base-runtime.ts b/packages/eve/src/execution/sandbox/bindings/vercel-base-runtime.ts
index dff63f8d7..52da724f0 100644
--- a/packages/eve/src/execution/sandbox/bindings/vercel-base-runtime.ts
+++ b/packages/eve/src/execution/sandbox/bindings/vercel-base-runtime.ts
@@ -35,10 +35,17 @@ export function createVercelNetworkPolicySetter(
sandbox: VercelSandbox,
): (policy: SandboxNetworkPolicy) => Promise<void> {
return async (policy) => {
- await sandbox.update({ networkPolicy: policy });
+ await sandbox.update({ networkPolicy: toVercelNetworkPolicy(policy) });
};
}
+/** eve's policy is the SDK's shape with readonly members, and the SDK never mutates it. */
+export function toVercelNetworkPolicy(
+ policy: SandboxNetworkPolicy,
+): NonNullable<VercelCreateOptions["networkPolicy"]> {
+ return policy as NonNullable<VercelCreateOptions["networkPolicy"]>;
+}
+
async function runSandboxInitializationStep(
sandbox: VercelSandbox,
input: { readonly failureMessage: string; readonly script: string },
diff --git a/packages/eve/src/execution/sandbox/bindings/vercel.test.ts b/packages/eve/src/execution/sandbox/bindings/vercel.test.ts
index e929bdde2..b9503c573 100644
--- a/packages/eve/src/execution/sandbox/bindings/vercel.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/vercel.test.ts
@@ -3,7 +3,6 @@ import { Readable } from "node:stream";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";
-import { writeSandboxFiles } from "#shared/sandbox-write-files.js";
import { VERCEL_EVE_SANDBOX_IMAGE } from "#execution/sandbox/bindings/eve-image.js";
import { createVercelSandbox as createVercelImplementation } from "#execution/sandbox/bindings/vercel.js";
import { createSandboxProviderHarness } from "#internal/testing/sandbox-provider-harness.js";
@@ -490,7 +489,7 @@ describe("createVercelSandbox", () => {
const { handle, sessionSandbox } = await createTestVercelSession();
vi.mocked(sessionSandbox.runCommand).mockClear();
- await writeSandboxFiles(handle.sandbox, {
+ await handle.sandbox.writeFiles({
files: [
{ content: Buffer.from("A"), path: "/home/agent/.agents/skills/policy/a.md" },
{ content: Buffer.from("B"), path: "skills/policy/b notes.md " },
diff --git a/packages/eve/src/execution/sandbox/bindings/vercel.ts b/packages/eve/src/execution/sandbox/bindings/vercel.ts
index 28116f40e..5e7f642c6 100644
--- a/packages/eve/src/execution/sandbox/bindings/vercel.ts
+++ b/packages/eve/src/execution/sandbox/bindings/vercel.ts
@@ -24,7 +24,7 @@ import {
providerResourceTargetFiles,
type SandboxPreparedArtifact,
type SandboxProviderHandle,
- type SandboxProviderImplementation,
+ type LegacySandboxProviderImplementation,
type SandboxProviderSessionContext,
} from "#shared/sandbox-provider.js";
import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";
@@ -95,7 +95,7 @@ type VercelEnvironmentOptions = VercelCreateOptions & {
export function createVercelSandboxProvider(
environmentOptions: Readonly<VercelEnvironmentOptions> | undefined,
-): SandboxProviderImplementation<
+): LegacySandboxProviderImplementation<
VercelSandboxRuntimeOptions,
VercelSandboxPreparedArtifact,
VercelSandboxSessionState,
@@ -115,7 +115,7 @@ interface CreateVercelSandboxInput {
export function createVercelSandbox(
input: CreateVercelSandboxInput = {},
-): SandboxProviderImplementation<
+): LegacySandboxProviderImplementation<
VercelSandboxRuntimeOptions,
VercelSandboxPreparedArtifact,
VercelSandboxSessionState,
diff --git a/packages/eve/src/execution/sandbox/ensure.test.ts b/packages/eve/src/execution/sandbox/ensure.test.ts
index 8dbd814cd..13234dbf0 100644
--- a/packages/eve/src/execution/sandbox/ensure.test.ts
+++ b/packages/eve/src/execution/sandbox/ensure.test.ts
@@ -8,7 +8,7 @@ import { ensureSandboxAccess } from "#execution/sandbox/ensure.js";
import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";
import { defineParentSandbox, defineSandbox } from "#public/definitions/sandbox.js";
import {
- defineSandboxProvider,
+ defineLegacySandboxProvider,
type SandboxProviderSessionContext,
} from "#shared/sandbox-provider.js";
import { SandboxSessionGoneError } from "#shared/sandbox-session-gone-error.js";
@@ -39,7 +39,7 @@ function fixture(setup?: () => void, returnCopy = false) {
handle: await create(),
state: { key: context.session.id },
}));
- const provider = defineSandboxProvider({
+ const provider = defineLegacySandboxProvider({
name: "test",
environment: () => ({ onSessionEnd, prepare: async () => null, resume: create, start }),
});
@@ -89,7 +89,7 @@ function upsertingFixture() {
onSandboxStop: async () => {},
};
};
- const environment = defineSandboxProvider({
+ const environment = defineLegacySandboxProvider({
name: "upserting",
environment: () => ({
onSessionEnd: async (context: SandboxProviderSessionContext) =>
diff --git a/packages/eve/src/execution/sandbox/ensure.ts b/packages/eve/src/execution/sandbox/ensure.ts
index 9b73fec82..865ce1f63 100644
--- a/packages/eve/src/execution/sandbox/ensure.ts
+++ b/packages/eve/src/execution/sandbox/ensure.ts
@@ -286,7 +286,7 @@ export async function ensureSandboxAccess(
try {
return await resumePersisted(context);
} catch (error) {
- if (!(error instanceof SandboxSessionGoneError)) throw error;
+ if (!SandboxSessionGoneError.is(error)) throw error;
log.warn("session sandbox is gone, starting a fresh one", {
error,
providerName: persisted.providerName,
diff --git a/packages/eve/src/execution/sandbox/logging-session.test.ts b/packages/eve/src/execution/sandbox/logging-session.test.ts
index 5eb1de1b0..dfe468a72 100644
--- a/packages/eve/src/execution/sandbox/logging-session.test.ts
+++ b/packages/eve/src/execution/sandbox/logging-session.test.ts
@@ -102,6 +102,7 @@ function createTestSession(runResult = { exitCode: 0, stderr: "", stdout: "" }):
readTextFile: vi.fn(async () => null),
writeFile: vi.fn(async () => {}),
writeBinaryFile: vi.fn(async () => {}),
+ writeFiles: vi.fn(async () => {}),
writeTextFile: vi.fn(async () => {}),
removePath: vi.fn(async () => {}),
};
diff --git a/packages/eve/src/execution/sandbox/logging-session.ts b/packages/eve/src/execution/sandbox/logging-session.ts
index 6a038171e..66405bdc7 100644
--- a/packages/eve/src/execution/sandbox/logging-session.ts
+++ b/packages/eve/src/execution/sandbox/logging-session.ts
@@ -5,6 +5,7 @@ import type {
SandboxSpawnOptions,
SandboxWriteBinaryFileOptions,
SandboxWriteFileOptions,
+ SandboxWriteFilesOptions,
SandboxWriteTextFileOptions,
} from "#shared/sandbox-session.js";
import { truncateTail } from "#execution/sandbox/truncate-output.js";
@@ -44,6 +45,10 @@ export function createLoggingSandboxSession(input: {
log?.(`preparation write text file: ${options.path} (${options.content.length} chars)`);
return await session.writeTextFile(options);
},
+ async writeFiles(options: SandboxWriteFilesOptions) {
+ log?.(`preparation write files: ${options.files.length} files`);
+ return await session.writeFiles(options);
+ },
async removePath(options: SandboxRemovePathOptions) {
log?.(`preparation remove path: ${options.path}`);
return await session.removePath(options);
diff --git a/packages/eve/src/execution/sandbox/prewarm.test.ts b/packages/eve/src/execution/sandbox/prewarm.test.ts
index c040c6ef7..89d8d95fc 100644
--- a/packages/eve/src/execution/sandbox/prewarm.test.ts
+++ b/packages/eve/src/execution/sandbox/prewarm.test.ts
@@ -5,7 +5,7 @@ import {
type SandboxPreparedArtifactStore,
} from "#execution/sandbox/prewarm.js";
import {
- defineSandboxProvider,
+ defineLegacySandboxProvider,
type SandboxProviderPrepareContext,
} from "#shared/sandbox-provider.js";
import { createDiskRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
@@ -159,7 +159,7 @@ function createGraph(
};
} = {},
): ResolvedAgentGraphBundle {
- const provider = defineSandboxProvider({
+ const provider = defineLegacySandboxProvider({
name: input.providerName ?? "test",
environment: () => ({
async onSessionEnd() {},
diff --git a/packages/eve/src/execution/sandbox/session.test.ts b/packages/eve/src/execution/sandbox/session.test.ts
index 772e57bdd..1d4cbb679 100644
--- a/packages/eve/src/execution/sandbox/session.test.ts
+++ b/packages/eve/src/execution/sandbox/session.test.ts
@@ -64,6 +64,31 @@ describe("buildSandboxSession", () => {
// resolvePath
// ---------------------------------------------------------------------------
+ it("writes a batch through one primitive call, or several files at once without one", async () => {
+ const writeFiles = vi.fn(async () => {});
+ const files = Array.from({ length: 40 }, (_, i) => ({
+ content: new Uint8Array(),
+ path: `${i}.md`,
+ }));
+ await buildSandboxSession({ ...createTestPrimitives(), writeFiles }).writeFiles({ files });
+ expect(writeFiles).toHaveBeenCalledExactlyOnceWith({
+ abortSignal: undefined,
+ files: files.map((file) => ({ content: file.content, path: `/resolved/${file.path}` })),
+ });
+
+ let inFlight = 0;
+ let maxInFlight = 0;
+ const writeFile = vi.fn(async () => {
+ maxInFlight = Math.max(maxInFlight, ++inFlight);
+ await Promise.resolve();
+ inFlight -= 1;
+ });
+ await buildSandboxSession(createTestPrimitives({ writeFile })).writeFiles({ files });
+ expect(writeFile).toHaveBeenCalledTimes(files.length);
+ expect(maxInFlight).toBeGreaterThan(1);
+ expect(maxInFlight).toBeLessThan(files.length);
+ });
+
it("exposes resolvePath through the public session", () => {
const resolvePath = vi.fn((path: string) => `/resolved/${path}`);
const session = buildSandboxSession(createTestPrimitives({ resolvePath }));
diff --git a/packages/eve/src/execution/sandbox/session.ts b/packages/eve/src/execution/sandbox/session.ts
index c76ff9b61..f554379b3 100644
--- a/packages/eve/src/execution/sandbox/session.ts
+++ b/packages/eve/src/execution/sandbox/session.ts
@@ -17,15 +17,17 @@ import type {
SandboxWriteFilesOptions,
SandboxWriteTextFileOptions,
} from "#shared/sandbox-session.js";
-import { SANDBOX_WRITE_FILES } from "#shared/sandbox-write-files.js";
+import { mapWithConcurrency } from "#shared/map-with-concurrency.js";
import { bufferToStream, streamToBuffer } from "./stream-utils.js";
export type { InternalSandboxSession };
+const FALLBACK_WRITE_CONCURRENCY = 16;
+
/**
* Tells agent-aware CLIs (such as `vercel`) that an automated agent runs
- * the command, so they skip interactive prompts. Built-in providers apply it
- * beneath environment-level and per-call env so authors can override it.
+ * the command, so they skip interactive prompts. Providers apply it beneath
+ * environment-level and per-call env so authors can override it.
*/
export const SANDBOX_AGENT_ENV: Readonly<Record<string, string>> = { AI_AGENT: "eve" };
@@ -118,6 +120,23 @@ export function buildSandboxSession(
path: primitives.resolvePath(options.path),
});
},
+ async writeFiles(options: SandboxWriteFilesOptions) {
+ const files = options.files.map((file) => ({
+ content: file.content,
+ path: primitives.resolvePath(file.path),
+ }));
+ if (primitives.writeFiles !== undefined) {
+ await primitives.writeFiles({ abortSignal: options.abortSignal, files });
+ return;
+ }
+ await mapWithConcurrency(files, FALLBACK_WRITE_CONCURRENCY, async (file) => {
+ await primitives.writeFile({
+ abortSignal: options.abortSignal,
+ content: bufferToStream(file.content),
+ path: file.path,
+ });
+ });
+ },
async removePath(options: SandboxRemovePathOptions) {
await primitives.removePath({
abortSignal: options.abortSignal,
@@ -127,19 +146,6 @@ export function buildSandboxSession(
});
},
};
- if (primitives.writeFiles !== undefined) {
- Object.assign(session, {
- [SANDBOX_WRITE_FILES]: async (options: SandboxWriteFilesOptions) => {
- await primitives.writeFiles?.({
- abortSignal: options.abortSignal,
- files: options.files.map((file) => ({
- content: file.content,
- path: primitives.resolvePath(file.path),
- })),
- });
- },
- });
- }
if (setNetworkPolicy === undefined) return session;
return { ...session, setNetworkPolicy } as NetworkPolicySandboxSession;
}
diff --git a/packages/eve/src/execution/session-reset.integration.test.ts b/packages/eve/src/execution/session-reset.integration.test.ts
index 377a295c7..efa8c2dd8 100644
--- a/packages/eve/src/execution/session-reset.integration.test.ts
+++ b/packages/eve/src/execution/session-reset.integration.test.ts
@@ -9,7 +9,7 @@ import { sessionCommandInboxWorkflow } from "#internal/testing/session-inbox-wor
import { waitForHook, startSessionOwner } from "#internal/testing/workflow-test-helpers.js";
import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";
import { createWorkflowRuntime } from "#execution/workflow-runtime.js";
-import { defineSandboxProvider } from "#shared/sandbox-provider.js";
+import { defineLegacySandboxProvider } from "#shared/sandbox-provider.js";
import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";
@@ -76,7 +76,7 @@ function createSessionSandboxHarness() {
const initializedSessionIds: string[] = [];
const sessionKeys: string[] = [];
let sandboxCount = 0;
- const provider = defineSandboxProvider({
+ const provider = defineLegacySandboxProvider({
name: "session-reset-test",
environment: () => ({
async onSessionEnd() {},
diff --git a/packages/eve/src/execution/tool-session/sandbox.ts b/packages/eve/src/execution/tool-session/sandbox.ts
index e398973ee..96fdd22e7 100644
--- a/packages/eve/src/execution/tool-session/sandbox.ts
+++ b/packages/eve/src/execution/tool-session/sandbox.ts
@@ -10,8 +10,8 @@ import type { SandboxProviderHandle, SandboxProviderRuntime } from "#shared/sand
* A keyed tool session has no end, so nothing ever runs its sandbox's
* session-end cleanup. Only eve's bindings whose kept sandboxes stay bounded
* opt in: Vercel's saved filesystems expire, and just-bash keeps only files on
- * the local disk. The marker stays internal so the public provider API is
- * unchanged.
+ * the local disk. Custom providers opt in with `toolSessions: true`, which
+ * `defineSandboxProvider()` turns into this marker.
*/
/** What a binding that keeps tool-session sandboxes tells the calls that use them. */
@@ -49,7 +49,7 @@ export class ToolSessionSandboxUnsupportedError extends Error {
super(
`Sandbox provider "${providerName}" cannot keep a sandbox between invokeTool calls, ` +
"so a call with a key cannot open one. Call without a key for a sandbox that lasts " +
- "one call, or use Vercel Sandbox or just-bash.",
+ "one call, or use Vercel Sandbox, just-bash, or a custom provider that sets `toolSessions: true`.",
);
this.name = "ToolSessionSandboxUnsupportedError";
}
diff --git a/packages/eve/src/execution/tools/workflow/step-execution.test.ts b/packages/eve/src/execution/tools/workflow/step-execution.test.ts
index 156611712..91d92bbb5 100644
--- a/packages/eve/src/execution/tools/workflow/step-execution.test.ts
+++ b/packages/eve/src/execution/tools/workflow/step-execution.test.ts
@@ -24,7 +24,7 @@ import {
} from "#runtime/compiled-artifacts-source.js";
import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";
import {
- defineSandboxProvider,
+ defineLegacySandboxProvider,
type SandboxProviderSessionContext,
} from "#shared/sandbox-provider.js";
@@ -97,7 +97,7 @@ function upsertSandboxes() {
handles.push(handle);
return handle;
};
- const provider = defineSandboxProvider({
+ const provider = defineLegacySandboxProvider({
name: "upsert",
environment: () => ({
onSessionEnd: async (context: SandboxProviderSessionContext) =>
@@ -274,7 +274,7 @@ describe("workflow step authorization", () => {
return "opened";
}),
).resolves.toMatchObject({ output: "opened" });
- const other = defineSandboxProvider({
+ const other = defineLegacySandboxProvider({
name: "other",
environment: () => ({
onSessionEnd: async () => {},
diff --git a/packages/eve/src/internal/testing/app-harness.ts b/packages/eve/src/internal/testing/app-harness.ts
index 587127411..3b826be54 100644
--- a/packages/eve/src/internal/testing/app-harness.ts
+++ b/packages/eve/src/internal/testing/app-harness.ts
@@ -21,7 +21,7 @@ import { createNodeHarnessTools } from "#execution/node-step.js";
import { serializeInputSchema, serializeOutputSchema } from "#tools/schema.js";
import { defineSandbox } from "#public/definitions/sandbox.js";
import {
- defineSandboxProvider,
+ defineLegacySandboxProvider,
type SandboxProviderSessionContext,
} from "#shared/sandbox-provider.js";
import {
@@ -177,7 +177,7 @@ function createTestSandboxProvider() {
};
}
- const provider = defineSandboxProvider({
+ const provider = defineLegacySandboxProvider({
name: TEST_SANDBOX_PROVIDER_NAME,
environment: () => ({
async onSessionEnd(context) {
diff --git a/packages/eve/src/internal/testing/mocks/mock-sandbox.ts b/packages/eve/src/internal/testing/mocks/mock-sandbox.ts
index d556f7847..074aa3687 100644
--- a/packages/eve/src/internal/testing/mocks/mock-sandbox.ts
+++ b/packages/eve/src/internal/testing/mocks/mock-sandbox.ts
@@ -10,6 +10,7 @@ import type {
SandboxSpawnOptions,
SandboxWriteBinaryFileOptions,
SandboxWriteFileOptions,
+ SandboxWriteFilesOptions,
SandboxWriteTextFileOptions,
} from "#public/definitions/sandbox.js";
import type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";
@@ -183,6 +184,18 @@ export function mockSandbox(input: MockSandboxInput = {}): MockSandbox {
}
}
+ async function writeBinaryFile(options: SandboxWriteBinaryFileOptions): Promise<void> {
+ const resolved = resolveWorkspacePath(options.path);
+ writes.push({ content: options.content, path: resolved });
+ const buf = Buffer.from(
+ options.content.buffer,
+ options.content.byteOffset,
+ options.content.byteLength,
+ );
+ files.set(resolved, buf.toString("utf8"));
+ fileBytes.set(resolved, buf);
+ }
+
const baseSession: NetworkPolicySandboxSession = {
name: input.name ?? "sbx_mock",
resolvePath(path: string): string {
@@ -232,16 +245,9 @@ export function mockSandbox(input: MockSandboxInput = {}): MockSandbox {
files.set(resolved, buf.toString("utf8"));
fileBytes.set(resolved, buf);
},
- async writeBinaryFile(options: SandboxWriteBinaryFileOptions): Promise<void> {
- const resolved = resolveWorkspacePath(options.path);
- writes.push({ content: options.content, path: resolved });
- const buf = Buffer.from(
- options.content.buffer,
- options.content.byteOffset,
- options.content.byteLength,
- );
- files.set(resolved, buf.toString("utf8"));
- fileBytes.set(resolved, buf);
+ writeBinaryFile,
+ async writeFiles(options: SandboxWriteFilesOptions): Promise<void> {
+ for (const file of options.files) await writeBinaryFile(file);
},
async writeTextFile(options: SandboxWriteTextFileOptions): Promise<void> {
const resolved = resolveWorkspacePath(options.path);
diff --git a/packages/eve/src/internal/testing/sandbox-provider-harness.ts b/packages/eve/src/internal/testing/sandbox-provider-harness.ts
index 94e524a6b..ba2693eea 100644
--- a/packages/eve/src/internal/testing/sandbox-provider-harness.ts
+++ b/packages/eve/src/internal/testing/sandbox-provider-harness.ts
@@ -4,7 +4,7 @@ import {
createSandboxProviderResources,
type SandboxPreparedArtifact,
type SandboxProviderHandle,
- type SandboxProviderImplementation,
+ type LegacySandboxProviderImplementation,
type SandboxProviderResourceFile,
} from "#shared/sandbox-provider.js";
import type { SandboxSession } from "#shared/sandbox-session.js";
@@ -15,7 +15,12 @@ export function createSandboxProviderHarness<
SessionState,
Session extends SandboxSession,
>(
- implementation: SandboxProviderImplementation<Options, PreparedArtifact, SessionState, Session>,
+ implementation: LegacySandboxProviderImplementation<
+ Options,
+ PreparedArtifact,
+ SessionState,
+ Session
+ >,
options: Options,
harnessOptions: {
readonly preparedArtifact?: () => PreparedArtifact;
diff --git a/packages/eve/src/public/definitions/sandbox.ts b/packages/eve/src/public/definitions/sandbox.ts
index ccaaf0828..eec4809dc 100644
--- a/packages/eve/src/public/definitions/sandbox.ts
+++ b/packages/eve/src/public/definitions/sandbox.ts
@@ -14,6 +14,7 @@ export type {
SandboxSpawnOptions,
SandboxWriteBinaryFileOptions,
SandboxWriteFileOptions,
+ SandboxWriteFilesOptions,
SandboxWriteTextFileOptions,
} from "#shared/sandbox-session.js";
export type {
diff --git a/packages/eve/src/public/sandbox/index.ts b/packages/eve/src/public/sandbox/index.ts
index 8d7fa1c0a..d0dd65334 100644
--- a/packages/eve/src/public/sandbox/index.ts
+++ b/packages/eve/src/public/sandbox/index.ts
@@ -15,8 +15,10 @@ export {
type RuntimeSandboxSession,
type RuntimeSandboxSessionFor,
type SandboxSpawnOptions,
+ type SandboxRemovePathOptions,
type SandboxWriteBinaryFileOptions,
type SandboxWriteFileOptions,
+ type SandboxWriteFilesOptions,
type SandboxWriteTextFileOptions,
} from "#public/definitions/sandbox.js";
export { DefaultSandbox } from "#sandbox/providers/default.js";
@@ -26,6 +28,9 @@ export type {
DefaultSandboxSession,
} from "#sandbox/providers/default.js";
export type {
+ SandboxNetworkMatch,
+ SandboxNetworkMatcher,
SandboxNetworkOptions,
SandboxNetworkPolicy,
+ SandboxNetworkRule,
} from "#shared/sandbox-network-policy.js";
diff --git a/packages/eve/src/public/sandbox/provider.ts b/packages/eve/src/public/sandbox/provider.ts
index 158846f7e..0f6e8a2f2 100644
--- a/packages/eve/src/public/sandbox/provider.ts
+++ b/packages/eve/src/public/sandbox/provider.ts
@@ -1,17 +1,21 @@
export {
defineSandboxProvider,
- type SandboxDeleteOptions,
- type SandboxPreparedArtifact,
- type SandboxProvider,
+ type SandboxConnection,
+ type SandboxIdentity,
+ type SandboxJson,
+ type SandboxPrepareContext,
+ type SandboxPrepareOption,
type SandboxProviderDefinition,
- type SandboxProviderFiles,
- type SandboxProviderHandle,
type SandboxProviderImplementation,
- type SandboxProviderPrepareContext,
- type SandboxProviderResourceFile,
- type SandboxProviderResources,
- type SandboxProviderResourceSource,
- type SandboxProviderResourceTree,
- type SandboxProviderSessionContext,
- type SandboxProviderTargetFile,
+ type SandboxSessionContext,
+ type SandboxSessionEndOptions,
+ type WithPrepareOption,
+} from "#sandbox/provider.js";
+export type {
+ SandboxDeleteOptions,
+ SandboxProvider,
+ SandboxProviderFiles,
} from "#shared/sandbox-provider.js";
+export { SANDBOX_AGENT_ENV } from "#execution/sandbox/session.js";
+export { SandboxSessionGoneError } from "#shared/sandbox-session-gone-error.js";
+export { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";
diff --git a/packages/eve/src/sandbox/provider.test.ts b/packages/eve/src/sandbox/provider.test.ts
new file mode 100644
index 000000000..38755fbe9
--- /dev/null
+++ b/packages/eve/src/sandbox/provider.test.ts
@@ -0,0 +1,316 @@
+import type { Experimental_SandboxSession } from "ai";
+import { describe, expect, expectTypeOf, it, vi } from "vitest";
+
+import type * as Vercel from "#compiled/@vercel/sandbox/index.js";
+import { defineSandboxProvider, type SandboxConnection } from "#sandbox/provider.js";
+import { getSandboxEnvironmentRuntime } from "#shared/sandbox-environment.js";
+import type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";
+import {
+ createSandboxProviderResources,
+ type SandboxProviderPrepareContext,
+ type SandboxProviderSessionContext,
+} from "#shared/sandbox-provider.js";
+import type { SandboxSession } from "#shared/sandbox-session.js";
+
+const HOME_PROBE = `printf '%s\\n' "$HOME"`;
+
+/** A connection that records what eve sends it and answers the `$HOME` probe. */
+function recordingConnection() {
+ const files = new Map<string, Uint8Array>();
+ const calls: string[] = [];
+ const connection = {
+ close: vi.fn(async () => void calls.push("close")),
+ extensions: { ping: async () => "pong" },
+ async readFile({ path }: { readonly path: string }) {
+ return files.get(path) ?? null;
+ },
+ removePath: vi.fn(async () => {}),
+ spawn: vi.fn(async (options: Parameters<SandboxConnection["spawn"]>[0]) => ({
+ kill: async () => {},
+ stderr: new Blob([]).stream(),
+ stdout: new Blob([options.command === HOME_PROBE ? "/home/agent\n" : ""]).stream(),
+ wait: async () => ({ exitCode: 0 }),
+ })),
+ stop: vi.fn(async () => {}),
+ writeFiles: vi.fn(
+ async (options: { readonly files: readonly { content: Uint8Array; path: string }[] }) => {
+ calls.push(`write ${options.files.map((file) => file.path).join(" ")}`);
+ for (const file of options.files) files.set(file.path, file.content);
+ },
+ ),
+ };
+ return { calls, connection, files };
+}
+
+function sessionContext(id = "session-1"): SandboxProviderSessionContext {
+ return {
+ host: { loadOptionalPackage: vi.fn(), resolveProjectPath: (path) => `/app/${path}` },
+ session: { auth: { current: null, initiator: null }, id, turn: { id: "turn", sequence: 0 } },
+ storagePath: "/app/.eve/sandbox",
+ };
+}
+
+type ResourceTrees = Pick<
+ Parameters<typeof createSandboxProviderResources>[0],
+ "skills" | "workspace"
+>;
+
+function prepareContext(trees: ResourceTrees = {}, path?: string): SandboxProviderPrepareContext {
+ return {
+ files: { list: async () => [], read: vi.fn(), readText: vi.fn() },
+ host: sessionContext().host,
+ resources: createSandboxProviderResources({ key: "resources-key", path, ...trees }),
+ sourceRevision: "revision-1",
+ storagePath: "/app/.eve/sandbox",
+ };
+}
+
+/** A provider whose `prepare` populates `connection`, passing `mountedAt` through. */
+function bakingProvider(
+ connection: SandboxConnection<{ ping(): Promise<string> }>,
+ mountedAt?: string,
+) {
+ return defineSandboxProvider({
+ name: "baking",
+ environment: () => ({
+ async prepare(ctx) {
+ if (!ctx.isEmpty) await ctx.populate(connection, { mountedAt });
+ return { empty: ctx.isEmpty };
+ },
+ start: async () => ({ connection, state: null }),
+ resume: async () => connection,
+ onSessionEnd: async () => {},
+ }),
+ });
+}
+
+describe("defineSandboxProvider", () => {
+ it("derives the session from the connection, resolving paths from /workspace", async () => {
+ const { connection, files } = recordingConnection();
+ const kinds: string[] = [];
+ const provider = defineSandboxProvider({
+ name: "recording",
+ environment: () => ({
+ prepare: async () => null,
+ async start(ctx) {
+ kinds.push(ctx.kind);
+ return { connection, state: null };
+ },
+ resume: async () => connection,
+ onSessionEnd: async () => {},
+ }),
+ });
+ const { implementation } = getSandboxEnvironmentRuntime(provider.environment());
+
+ const { handle } = await implementation.start(sessionContext(), undefined, null);
+ await implementation.start(sessionContext("tool_session_abc"), undefined, null);
+ const sandbox = handle.sandbox as SandboxSession & { ping(): Promise<string> };
+ await sandbox.writeTextFile({ content: "hi", path: "notes/./a.txt" });
+ await sandbox.run({ command: "ls", workingDirectory: "src" });
+ await sandbox.removePath({ path: "../tmp/x", recursive: true });
+
+ expect(kinds).toEqual(["session", "tool-session"]);
+ expect([...files.keys()]).toEqual(["/workspace/notes/a.txt"]);
+ expect(await sandbox.readTextFile({ path: "/workspace/notes/a.txt" })).toBe("hi");
+ expect(connection.spawn).toHaveBeenCalledWith({
+ abortSignal: undefined,
+ command: "ls",
+ env: {},
+ workingDirectory: "/workspace/src",
+ });
+ expect(connection.removePath).toHaveBeenCalledWith(
+ expect.objectContaining({ path: "/tmp/x", recursive: true }),
+ );
+ expect(await sandbox.ping()).toBe("pong");
+ // A backend may answer with a stream instead of bytes.
+ vi.spyOn(connection, "readFile").mockResolvedValueOnce(
+ new Blob(["streamed"]).stream() as never,
+ );
+ expect(await sandbox.readTextFile({ path: "b.txt" })).toBe("streamed");
+ expect(connection.readFile).toHaveBeenLastCalledWith({
+ abortSignal: undefined,
+ path: "/workspace/b.txt",
+ });
+ });
+
+ it("rejects connection extensions that would replace a session member", async () => {
+ const { connection } = recordingConnection();
+ const provider = defineSandboxProvider({
+ name: "colliding",
+ environment: () => ({
+ prepare: async () => null,
+ start: async () => ({
+ connection: { ...connection, extensions: { run: async () => "mine" } } as never,
+ state: null,
+ }),
+ resume: async () => connection,
+ onSessionEnd: async () => {},
+ }),
+ });
+ const { implementation } = getSandboxEnvironmentRuntime(provider.environment());
+
+ await expect(implementation.start(sessionContext(), undefined, null)).rejects.toThrow(
+ "Sandbox connection extensions cannot replace the session members eve provides: run.",
+ );
+ });
+
+ it("passes environment options to the provider without prepare, and {} when omitted", () => {
+ const received: object[] = [];
+ const provider = defineSandboxProvider({
+ name: "options",
+ environment(options: { readonly region?: string }) {
+ received.push(options);
+ return {
+ prepare: async () => null,
+ start: async () => ({ connection: recordingConnection().connection, state: null }),
+ resume: async () => recordingConnection().connection,
+ onSessionEnd: async () => {},
+ };
+ },
+ });
+
+ provider.environment();
+ provider.environment({ prepare: async () => {} });
+ provider.environment({ prepare: async () => {}, region: "iad1" });
+
+ expect(received).toEqual([{}, {}, { region: "iad1" }]);
+ });
+
+ it("hashes template identities with the workspace, skills, and source revision", async () => {
+ const keys: string[] = [];
+ const provider = defineSandboxProvider({
+ name: "keys",
+ environment: () => ({
+ async prepare(ctx) {
+ keys.push(ctx.templateKey({ image: "ubuntu", skip: undefined, version: 1 }));
+ expect(() => ctx.templateKey({ sourceRevision: "mine" })).toThrow(
+ 'ctx.templateKey() reserves "sourceRevision"',
+ );
+ // These would hash like `{}` or overflow the stack, so they reject.
+ expect(() => ctx.templateKey({ builtAt: new Date(0) })).toThrow(
+ "but identity.builtAt is a Date",
+ );
+ expect(() => ctx.templateKey({ layers: [new Map()] })).toThrow(
+ "but identity.layers[0] is a Map",
+ );
+ const loop: unknown[] = [];
+ loop.push(loop);
+ expect(() => ctx.templateKey({ loop })).toThrow("circular value at identity.loop[0]");
+ return null;
+ },
+ start: async () => ({ connection: recordingConnection().connection, state: null }),
+ resume: async () => recordingConnection().connection,
+ onSessionEnd: async () => {},
+ }),
+ });
+ const { implementation } = getSandboxEnvironmentRuntime(provider.environment());
+
+ await implementation.prepare(prepareContext());
+
+ // Golden value: if it changes, every custom provider's template keys change with it.
+ expect(keys).toEqual(["d02550d7328ec5806580c8cd02c0c2b0b3e9a90bbbec7f552938442d79ffd8e1"]);
+ });
+
+ it("seeds workspace and skills in one batch before the authored prepare", async () => {
+ const { calls, connection } = recordingConnection();
+ const provider = bakingProvider(connection);
+ const environment = provider.environment({
+ prepare: async (sandbox) => {
+ await sandbox.writeTextFile({ content: await sandbox.ping(), path: "prepared.txt" });
+ },
+ });
+
+ const artifacts = [
+ await getSandboxEnvironmentRuntime(environment).implementation.prepare(
+ prepareContext({
+ skills: [{ content: "# Skill", relativePath: "review/SKILL.md" }],
+ workspace: [{ content: "seed", relativePath: "seed.txt" }],
+ }),
+ ),
+ await getSandboxEnvironmentRuntime(provider.environment()).implementation.prepare(
+ prepareContext(),
+ ),
+ ];
+
+ expect(artifacts).toEqual([{ empty: false }, { empty: true }]);
+ expect(calls).toEqual([
+ "write /workspace/seed.txt /home/agent/.agents/skills/review/SKILL.md",
+ "write /workspace/prepared.txt",
+ ]);
+ });
+
+ it("copies from mounted resources, and writes files when there is no resource directory", async () => {
+ const seed = { workspace: [{ content: "seed", relativePath: "seed.txt" }] };
+ const mounted = recordingConnection();
+ await getSandboxEnvironmentRuntime(
+ bakingProvider(mounted.connection, "/eve/res ources").environment(),
+ ).implementation.prepare(prepareContext(seed, "/app/.eve/compile/resources"));
+ const inline = recordingConnection();
+ await getSandboxEnvironmentRuntime(
+ bakingProvider(inline.connection, "/eve/resources").environment(),
+ ).implementation.prepare(prepareContext(seed));
+
+ expect(mounted.calls).toEqual([]);
+ expect(mounted.connection.spawn).toHaveBeenCalledWith(
+ expect.objectContaining({
+ command: expect.stringContaining("cp -a '/eve/res ources'/workspace/. /workspace/"),
+ }),
+ );
+ expect(inline.calls).toEqual(["write /workspace/seed.txt"]);
+ });
+});
+
+describe("public sandbox types", () => {
+ it("infers a provider's options, state, and extensions from its implementation", () => {
+ type Extensions = { setNetworkPolicy(policy: "deny-all"): Promise<void> };
+ const provider = defineSandboxProvider({
+ name: "acme",
+ environment(options: { readonly project: string }) {
+ return {
+ prepare: async (ctx) => ({ snapshotId: ctx.templateKey({ project: options.project }) }),
+ async start(_ctx, open: { readonly egress?: "deny-all" } | undefined) {
+ return { connection: connect(), state: { name: String(open?.egress), version: 1 } };
+ },
+ async resume(_ctx, artifact, state) {
+ expectTypeOf(artifact.snapshotId).toEqualTypeOf<string>();
+ expectTypeOf(state.name).toEqualTypeOf<string>();
+ return connect();
+ },
+ onSessionEnd: async () => {},
+ };
+ },
+ });
+ function connect(): SandboxConnection<Extensions> {
+ throw new Error("type-only");
+ }
+ const environment = provider.environment({
+ prepare: (sandbox) => {
+ expectTypeOf(sandbox).toEqualTypeOf<SandboxSession & Extensions>();
+ },
+ project: "agents",
+ });
+
+ expectTypeOf(environment.open).toBeCallableWith({ egress: "deny-all" });
+ // @ts-expect-error The provider's open options accept only "deny-all".
+ void (() => environment.open({ egress: "allow-all" }));
+ const colliding: SandboxConnection<{ run(): Promise<string> }> = {
+ ...recordingConnection().connection,
+ // @ts-expect-error `run` belongs to the session eve derives.
+ extensions: { run: async () => "mine" },
+ };
+ void colliding;
+ });
+
+ it("keeps SandboxSession assignable to the AI SDK sandbox session", () => {
+ expectTypeOf<SandboxSession>().toExtend<Omit<Experimental_SandboxSession, "description">>();
+ });
+
+ it("keeps SandboxNetworkPolicy within the Vercel Sandbox network policy shape", () => {
+ type Writable<T> = T extends (...args: never[]) => unknown
+ ? T
+ : T extends object
+ ? { -readonly [Key in keyof T]: Writable<T[Key]> }
+ : T;
+ expectTypeOf<Writable<SandboxNetworkPolicy>>().toExtend<Vercel.NetworkPolicy>();
+ });
+});
diff --git a/packages/eve/src/sandbox/provider.ts b/packages/eve/src/sandbox/provider.ts
new file mode 100644
index 000000000..713c782e1
--- /dev/null
+++ b/packages/eve/src/sandbox/provider.ts
@@ -0,0 +1,517 @@
+import { posix } from "node:path";
+
+import {
+ hydrateSandboxFromImmutableResources,
+ prepareImmutableResources,
+} from "#execution/sandbox/bindings/immutable-resources.js";
+import { createLoggingSandboxSession } from "#execution/sandbox/logging-session.js";
+import { createSandboxProviderIdentity } from "#execution/sandbox/provider-identity.js";
+import { buildSandboxSession } from "#execution/sandbox/session.js";
+import { shellQuote } from "#execution/sandbox/shell-quote.js";
+import { bufferToStream, streamToBuffer } from "#execution/sandbox/stream-utils.js";
+import { isToolSessionId } from "#execution/tool-session/id.js";
+import { withToolSessionSandboxes } from "#execution/tool-session/sandbox.js";
+import { WORKSPACE_ROOT } from "#runtime/workspace/types.js";
+import type { SandboxSelectorContext } from "#shared/sandbox-environment.js";
+import {
+ defineLegacySandboxProvider,
+ providerResourceTargetFiles,
+ sandboxProviderResourceIdentity,
+ type LegacySandboxProviderImplementation,
+ type SandboxPreparedArtifact,
+ type SandboxProvider,
+ type SandboxProviderFiles,
+ type SandboxProviderHandle,
+ type SandboxProviderPrepareContext,
+ type SandboxProviderSessionContext,
+} from "#shared/sandbox-provider.js";
+import type {
+ SandboxProcess,
+ SandboxRemovePathOptions,
+ SandboxSession,
+ SandboxWriteFilesOptions,
+} from "#shared/sandbox-session.js";
+import { resolveSandboxModelPath } from "#shared/skill-paths.js";
+
+/** A JSON-compatible value: what a provider may return as an artifact or session state. */
+export type SandboxJson = SandboxPreparedArtifact;
+
+/** Members eve owns on every live sandbox, which a connection's extensions cannot replace. */
+type ReservedSessionMember = keyof SandboxSession | "delete" | "stop";
+
+/**
+ * The byte-level connection to one sandbox that a provider implements. eve
+ * derives the full {@link SandboxSession} from it.
+ *
+ * Every path a connection receives is absolute, and `workingDirectory` is
+ * always set: eve resolves relative paths from `/workspace`.
+ */
+export interface SandboxConnection<Extensions extends object = {}> {
+ /**
+ * Runs `command` as a Bash login-shell script (`bash -lc`) in
+ * `workingDirectory`, with the sandbox's environment plus `env`. `env`
+ * holds only the per-call variables. Aborting kills the process tree.
+ */
+ spawn(options: {
+ readonly abortSignal?: AbortSignal;
+ readonly command: string;
+ readonly env: Readonly<Record<string, string>>;
+ readonly workingDirectory: string;
+ }): Promise<SandboxProcess>;
+ /**
+ * Resolves to `null` only when the path does not exist. A directory or an
+ * unreadable path rejects. Return bytes or a stream, whichever the backend has.
+ */
+ readFile(options: {
+ readonly abortSignal?: AbortSignal;
+ readonly path: string;
+ }): Promise<Uint8Array | ReadableStream<Uint8Array> | null>;
+ /** Creates missing parent directories and overwrites existing files. The only write primitive. */
+ writeFiles(options: SandboxWriteFilesOptions): Promise<void>;
+ /** `force` ignores a missing path; `recursive` removes a non-empty directory. */
+ removePath(options: SandboxRemovePathOptions): Promise<void>;
+ /** Releases compute and keeps the sandbox's files. */
+ stop(): Promise<void>;
+ /** Releases what this process holds, such as a local interpreter, without touching the sandbox. */
+ close?(): Promise<void>;
+ /**
+ * Provider capabilities merged onto the session, such as `setNetworkPolicy`.
+ * A plain object: eve merges its own enumerable properties, so use closures
+ * rather than class methods. A member named like a session method is a type
+ * error, and eve rejects it.
+ */
+ readonly extensions?: Extensions & { readonly [Key in ReservedSessionMember]?: never };
+}
+
+/** What eve passes to `start()`, `resume()`, and `onSessionEnd()`. */
+export interface SandboxSessionContext {
+ /**
+ * The session that owns the sandbox. Derive native names from `session.id`:
+ * for a subagent that shares its parent's sandbox it is the parent's id, and
+ * for a keyed `invokeTool` call it is the derived tool-session id.
+ */
+ readonly session: SandboxSelectorContext["session"];
+ /** `"tool-session"` for a keyed `invokeTool` call's sandbox, `"session"` otherwise. */
+ readonly kind: "session" | "tool-session";
+ /** A host directory the provider may use for local state. */
+ readonly storagePath: string;
+ /** Resolves a path relative to the app's project root on the host. */
+ resolveProjectPath(path: string): string;
+}
+
+/**
+ * Values hashed into a template key: JSON values, `undefined` (omitted),
+ * plain objects and arrays, and functions (hashed by their source). Other
+ * values and circular structures reject.
+ */
+export type SandboxIdentity = { readonly [key: string]: unknown };
+
+/**
+ * What eve passes to `prepare()` while it builds a template. Not generic over
+ * the provider's extensions, so TypeScript infers them from `start()`.
+ */
+export interface SandboxPrepareContext {
+ /** Authored files under the agent's `sandbox/` directory. */
+ readonly files: SandboxProviderFiles;
+ /** `true` when there are no workspace or skill files and no authored `prepare`. */
+ readonly isEmpty: boolean;
+ readonly storagePath: string;
+ /** Reports build progress, such as `eve build` output. */
+ log(message: string): void;
+ /**
+ * Seeds `/workspace` and `$HOME/.agents/skills`, then runs the authored
+ * `prepare` with a session over `connection`. With `mountedAt`, the
+ * provider has mounted {@link resourcesDirectory} read-only at that
+ * sandbox path, and eve copies from it instead of writing every file.
+ */
+ populate(
+ connection: SandboxConnection<object>,
+ options?: { readonly mountedAt?: string },
+ ): Promise<void>;
+ resolveProjectPath(path: string): string;
+ /** A stable read-only host directory holding `workspace/` and `skills/`, when one exists. */
+ resourcesDirectory(): Promise<string | undefined>;
+ /**
+ * Hashes `identity` together with the workspace files, skill files, and
+ * sandbox source revision into a stable SHA-256 hex key. `resources` and
+ * `sourceRevision` are reserved.
+ */
+ templateKey(identity: SandboxIdentity): string;
+}
+
+export interface SandboxSessionEndOptions {
+ readonly abortSignal?: AbortSignal;
+ readonly reason: "completed" | "expired" | "failed" | "deleted";
+}
+
+/** The lifecycle one sandbox environment implements. */
+export interface SandboxProviderImplementation<
+ OpenOptions extends object | undefined,
+ Artifact extends SandboxJson,
+ State extends SandboxJson,
+ Extensions extends object,
+> {
+ /**
+ * Builds a template during `eve build`, or on first access in `eve dev`, and
+ * returns the JSON artifact that ships with the deployment. Call
+ * `ctx.populate()` on the build instance before capturing it.
+ */
+ prepare(ctx: SandboxPrepareContext): Promise<Artifact>;
+ /**
+ * Returns the sandbox for `ctx.session.id`, creating it when none exists.
+ * An idempotent upsert: repeated, concurrent, cross-process, and
+ * cross-deployment calls return the same sandbox while it exists. Derive
+ * native identity from `ctx.session.id` and a provider-level namespace
+ * only; `options` and `artifact` apply only when this call creates it.
+ */
+ start(
+ ctx: SandboxSessionContext,
+ options: Readonly<OpenOptions> | undefined,
+ artifact: Readonly<Artifact>,
+ ): Promise<{ readonly connection: SandboxConnection<Extensions>; readonly state: State }>;
+ /**
+ * Reconnects to the sandbox `state` names, never recreating it. Throw
+ * `SandboxSessionGoneError` when it no longer exists.
+ */
+ resume(
+ ctx: SandboxSessionContext,
+ artifact: Readonly<Artifact>,
+ state: Readonly<State>,
+ ): Promise<SandboxConnection<Extensions>>;
+ /**
+ * Deletes whatever exists for `ctx.session.id`. `state` is `null` when the
+ * session never recorded it. Must succeed when nothing exists and be
+ * idempotent. `sandbox.delete()` also lands here, with `reason: "deleted"`.
+ */
+ onSessionEnd(
+ ctx: SandboxSessionContext,
+ state: Readonly<State> | null,
+ options: SandboxSessionEndOptions,
+ ): Promise<void>;
+ /**
+ * Lets a keyed `invokeTool` call keep its sandbox between calls. eve never
+ * ends a keyed sandbox, so the provider must bound its retention.
+ */
+ readonly toolSessions?: true;
+}
+
+export interface SandboxPrepareOption<Session> {
+ /** Runs once per template, after eve seeds workspace and skill files. */
+ readonly prepare?: (sandbox: Session) => void | Promise<void>;
+}
+
+/** Environment options plus the standard `prepare` option. */
+export type WithPrepareOption<Options extends object, Session> = Options &
+ SandboxPrepareOption<Session>;
+
+export interface SandboxProviderDefinition<
+ EnvironmentOptions extends object,
+ OpenOptions extends object | undefined,
+ Artifact extends SandboxJson,
+ State extends SandboxJson,
+ Extensions extends object,
+> {
+ readonly name: string;
+ /** Bump when `State` changes incompatibly; recorded state from another version starts fresh. */
+ readonly stateProtocolVersion?: number;
+ /**
+ * Receives the environment options without `prepare`, which eve runs in
+ * `ctx.populate()`. Always an object: `{}` when the caller passes none.
+ */
+ environment(
+ options: EnvironmentOptions,
+ ): SandboxProviderImplementation<OpenOptions, Artifact, State, Extensions>;
+}
+
+/** Defines a sandbox provider from a connection and a lifecycle. */
+export function defineSandboxProvider<
+ EnvironmentOptions extends object = {},
+ OpenOptions extends object | undefined = undefined,
+ Artifact extends SandboxJson = SandboxJson,
+ State extends SandboxJson = SandboxJson,
+ Extensions extends object = {},
+>(
+ definition: SandboxProviderDefinition<
+ EnvironmentOptions,
+ OpenOptions,
+ Artifact,
+ State,
+ Extensions
+ >,
+): SandboxProvider<
+ WithPrepareOption<EnvironmentOptions, SandboxSession & Extensions>,
+ OpenOptions,
+ SandboxSession & Extensions
+> {
+ type Session = SandboxSession & Extensions;
+ const provider = defineLegacySandboxProvider<
+ SandboxPrepareOption<Session> | undefined,
+ OpenOptions,
+ Artifact,
+ State,
+ Session
+ >({
+ name: definition.name,
+ stateProtocolVersion: definition.stateProtocolVersion,
+ environment(options) {
+ const { prepare, ...environmentOptions } = options ?? {};
+ const implementation = definition.environment(environmentOptions as EnvironmentOptions);
+ return adaptSandboxProvider(definition.name, implementation, prepare);
+ },
+ });
+ return provider as SandboxProvider<
+ WithPrepareOption<EnvironmentOptions, Session>,
+ OpenOptions,
+ Session
+ >;
+}
+
+function adaptSandboxProvider<
+ OpenOptions extends object | undefined,
+ Artifact extends SandboxJson,
+ State extends SandboxJson,
+ Extensions extends object,
+>(
+ providerName: string,
+ implementation: SandboxProviderImplementation<OpenOptions, Artifact, State, Extensions>,
+ prepare: ((sandbox: SandboxSession & Extensions) => void | Promise<void>) | undefined,
+): LegacySandboxProviderImplementation<OpenOptions, Artifact, State, SandboxSession & Extensions> {
+ const closers = new WeakMap<SandboxProviderHandle, () => Promise<void>>();
+ // Connections this process holds per session, so terminal cleanup can close them.
+ const open = new Map<string, Set<() => Promise<void>>>();
+
+ function createHandle(
+ context: SandboxSessionContext,
+ connection: SandboxConnection<Extensions>,
+ state: Readonly<State>,
+ ): SandboxProviderHandle<SandboxSession & Extensions> {
+ const sessionId = context.session.id;
+ // eve may stop or close one connection from several paths, such as
+ // `sandbox.stop()` and then server shutdown, so each runs once.
+ const stop = once(() => connection.stop());
+ const close = once(async () => {
+ const remaining = open.get(sessionId);
+ remaining?.delete(close);
+ if (remaining?.size === 0) open.delete(sessionId);
+ await connection.close?.();
+ });
+ let sessionClosers = open.get(sessionId);
+ if (sessionClosers === undefined) open.set(sessionId, (sessionClosers = new Set()));
+ sessionClosers.add(close);
+ const release = async () => {
+ try {
+ await stop();
+ } finally {
+ await close();
+ }
+ };
+ const handle: SandboxProviderHandle<SandboxSession & Extensions> = {
+ sandbox: createConnectionSession(connection),
+ onRuntimeShutdown: release,
+ async onSandboxDelete(options) {
+ try {
+ await close();
+ } finally {
+ await implementation.onSessionEnd(context, state, {
+ abortSignal: options?.abortSignal,
+ reason: "deleted",
+ });
+ }
+ },
+ onSandboxStop: release,
+ };
+ closers.set(handle, close);
+ return handle;
+ }
+
+ async function closeSession(sessionId: string): Promise<void> {
+ const sessionClosers = [...(open.get(sessionId) ?? [])];
+ open.delete(sessionId);
+ await Promise.allSettled(sessionClosers.map((close) => close()));
+ }
+
+ const adapted: LegacySandboxProviderImplementation<
+ OpenOptions,
+ Artifact,
+ State,
+ SandboxSession & Extensions
+ > = {
+ async onSessionEnd(context, state, { reason }) {
+ // A failed close of a process-local resource must not block deleting the sandbox.
+ await closeSession(context.session.id);
+ await implementation.onSessionEnd(createSessionContext(context), state, { reason });
+ },
+ async prepare(context) {
+ return await implementation.prepare(createPrepareContext(providerName, context, prepare));
+ },
+ async resume(context, artifact, state) {
+ const sessionContext = createSessionContext(context);
+ const connection = await implementation.resume(sessionContext, artifact, state);
+ return createHandle(sessionContext, connection, state);
+ },
+ async start(context, options, artifact) {
+ const sessionContext = createSessionContext(context);
+ const { connection, state } = await implementation.start(sessionContext, options, artifact);
+ return { handle: createHandle(sessionContext, connection, state), state };
+ },
+ };
+ if (implementation.toolSessions !== true) return adapted;
+ return withToolSessionSandboxes(adapted, {
+ releaseHandle: async (handle) => await closers.get(handle)?.(),
+ });
+}
+
+function createSessionContext(context: SandboxProviderSessionContext): SandboxSessionContext {
+ return {
+ kind: isToolSessionId(context.session.id) ? "tool-session" : "session",
+ resolveProjectPath: (path) => context.host.resolveProjectPath(path),
+ session: context.session,
+ storagePath: context.storagePath,
+ };
+}
+
+function createPrepareContext<Extensions extends object>(
+ providerName: string,
+ context: SandboxProviderPrepareContext,
+ prepare: ((sandbox: SandboxSession & Extensions) => void | Promise<void>) | undefined,
+): SandboxPrepareContext {
+ const files = providerResourceTargetFiles(context.resources);
+ const log = (message: string) => context.log?.(message);
+ return {
+ files: context.files,
+ isEmpty: files.length === 0 && prepare === undefined,
+ log,
+ async populate(connection, options) {
+ const session = createConnectionSession(connection);
+ // Without a resource directory there is nothing mounted to copy from.
+ if (options?.mountedAt !== undefined && context.resources.source.kind === "materialized") {
+ log("copying workspace and skills from mounted resources");
+ await hydrateSandboxFromImmutableResources(session, shellQuote(options.mountedAt));
+ } else if (files.length > 0) {
+ log("writing workspace and skills");
+ await session.writeFiles({
+ files: await Promise.all(
+ files.map(async (file) => ({
+ content: typeof file.content === "string" ? Buffer.from(file.content) : file.content,
+ path: await resolveSandboxModelPath({ path: file.path, sandbox: session }),
+ })),
+ ),
+ });
+ }
+ if (prepare === undefined) return;
+ log("running sandbox preparation");
+ // The provider builds the template with the connection type its sessions use.
+ await prepare(createLoggingSandboxSession({ log, session }) as SandboxSession & Extensions);
+ },
+ resolveProjectPath: (path) => context.host.resolveProjectPath(path),
+ async resourcesDirectory() {
+ const source = context.resources.source;
+ if (source.kind !== "materialized") return undefined;
+ return await prepareImmutableResources({
+ provider: providerName,
+ resourcesKey: source.key,
+ sourcePath: source.path,
+ storagePath: context.storagePath,
+ });
+ },
+ storagePath: context.storagePath,
+ templateKey(identity) {
+ assertSandboxIdentity(identity, "identity", new WeakSet());
+ for (const reserved of ["resources", "sourceRevision"]) {
+ if (Object.hasOwn(identity, reserved)) {
+ throw new Error(
+ `ctx.templateKey() reserves "${reserved}": eve adds the workspace and skill files and the sandbox source revision itself. Rename that identity field.`,
+ );
+ }
+ }
+ return createSandboxProviderIdentity({
+ ...identity,
+ resources: sandboxProviderResourceIdentity(context.resources),
+ sourceRevision: context.sourceRevision,
+ });
+ },
+ };
+}
+
+function createConnectionSession<Extensions extends object>(
+ connection: SandboxConnection<Extensions>,
+): SandboxSession & Extensions {
+ const session = buildSandboxSession({
+ async readFile(options) {
+ const content = await connection.readFile(options);
+ if (content === null || !ArrayBuffer.isView(content)) return content;
+ return bufferToStream(new Uint8Array(content.buffer, content.byteOffset, content.byteLength));
+ },
+ removePath: (options) => connection.removePath(options),
+ resolvePath: resolveSandboxPath,
+ spawn: (options) =>
+ connection.spawn({
+ abortSignal: options.abortSignal,
+ command: options.command,
+ env: options.env ?? {},
+ workingDirectory: resolveSandboxPath(options.workingDirectory ?? WORKSPACE_ROOT),
+ }),
+ async writeFile(options) {
+ await connection.writeFiles({
+ abortSignal: options.abortSignal,
+ files: [{ content: await streamToBuffer(options.content), path: options.path }],
+ });
+ },
+ writeFiles: (options) => connection.writeFiles(options),
+ });
+ const extensions: object = connection.extensions ?? {};
+ const collisions = Object.keys(extensions).filter(
+ (key) => Object.hasOwn(session, key) || key === "delete" || key === "stop",
+ );
+ if (collisions.length > 0) {
+ throw new Error(
+ `Sandbox connection extensions cannot replace the session members eve provides: ${collisions.join(", ")}. Rename them.`,
+ );
+ }
+ return { ...extensions, ...session } as SandboxSession & Extensions;
+}
+
+/** Runs `run` at most once while it succeeds; a failed run can be retried. */
+function once(run: () => Promise<void>): () => Promise<void> {
+ let running: Promise<void> | undefined;
+ return () =>
+ (running ??= run().catch((error: unknown) => {
+ running = undefined;
+ throw error;
+ }));
+}
+
+/**
+ * Rejects what the template-key hasher cannot tell apart, such as a `Date` or
+ * `Map` that would hash as `{}`, and circular values, before hashing.
+ */
+function assertSandboxIdentity(value: unknown, path: string, seen: WeakSet<object>): void {
+ if (value === null || value === undefined || typeof value === "function") return;
+ if (typeof value === "string" || typeof value === "boolean") return;
+ if (typeof value === "number" && Number.isFinite(value)) return;
+ const prototype = typeof value === "object" ? Object.getPrototypeOf(value) : undefined;
+ const plain = Array.isArray(value) || prototype === Object.prototype || prototype === null;
+ if (typeof value !== "object" || !plain) {
+ throw new Error(
+ `ctx.templateKey() accepts only JSON values, plain objects, arrays, and functions, but ${path} is ${describeIdentityValue(value)}. Pass a JSON form, such as a string.`,
+ );
+ }
+ if (seen.has(value))
+ throw new Error(`ctx.templateKey() cannot hash a circular value at ${path}.`);
+ seen.add(value);
+ for (const [key, entry] of Object.entries(value)) {
+ assertSandboxIdentity(entry, Array.isArray(value) ? `${path}[${key}]` : `${path}.${key}`, seen);
+ }
+ seen.delete(value);
+}
+
+function describeIdentityValue(value: unknown): string {
+ if (typeof value === "object" && value !== null) {
+ return `a ${value.constructor?.name ?? "non-plain object"}`;
+ }
+ return typeof value === "number" ? String(value) : `a ${typeof value}`;
+}
+
+function resolveSandboxPath(path: string): string {
+ return posix.resolve(WORKSPACE_ROOT, path);
+}
diff --git a/packages/eve/src/sandbox/providers/default.ts b/packages/eve/src/sandbox/providers/default.ts
index 53455e36a..f29c8d184 100644
--- a/packages/eve/src/sandbox/providers/default.ts
+++ b/packages/eve/src/sandbox/providers/default.ts
@@ -23,11 +23,11 @@ import type {
SandboxNetworkPolicy,
} from "#shared/sandbox-network-policy.js";
import {
- defineSandboxProvider,
+ defineLegacySandboxProvider,
isSandboxPreparedArtifactRecord,
type SandboxPreparedArtifact,
type SandboxProviderHandle,
- type SandboxProviderImplementation,
+ type LegacySandboxProviderImplementation,
type SandboxProviderRuntime,
} from "#shared/sandbox-provider.js";
import { SandboxSessionGoneError } from "#shared/sandbox-session-gone-error.js";
@@ -83,7 +83,7 @@ const JUST_BASH_NETWORK_POLICY_MESSAGE =
* 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<
+export const DefaultSandbox = defineLegacySandboxProvider<
DefaultSandboxEnvironmentOptions,
DefaultSandboxRuntimeOptions,
DefaultSandboxPreparedArtifact,
@@ -149,7 +149,7 @@ export const DefaultSandbox = defineSandboxProvider<
await inner.implementation.onSessionEnd(context, innerState, { reason: options.reason });
};
- const implementation: SandboxProviderImplementation<
+ const implementation: LegacySandboxProviderImplementation<
DefaultSandboxRuntimeOptions,
DefaultSandboxPreparedArtifact,
DefaultSandboxSessionState,
diff --git a/packages/eve/src/sandbox/providers/docker.ts b/packages/eve/src/sandbox/providers/docker.ts
index bc603c4e3..40ad76697 100644
--- a/packages/eve/src/sandbox/providers/docker.ts
+++ b/packages/eve/src/sandbox/providers/docker.ts
@@ -5,7 +5,7 @@ import type {
DockerSandboxRuntimeOptions,
} from "#public/sandbox/docker-sandbox.js";
import type { SandboxEnvironment } from "#shared/sandbox-environment.js";
-import { defineSandboxProvider } from "#shared/sandbox-provider.js";
+import { defineLegacySandboxProvider } from "#shared/sandbox-provider.js";
export type {
DockerSandboxEnvironmentOptions,
@@ -14,7 +14,7 @@ export type {
type DockerfileEnvironmentInput = Omit<DockerSandboxEnvironmentOptions, "image">;
-const provider = defineSandboxProvider<
+const provider = defineLegacySandboxProvider<
DockerSandboxEnvironmentOptions,
DockerSandboxRuntimeOptions,
{ readonly imageReference: string },
diff --git a/packages/eve/src/sandbox/providers/just-bash.ts b/packages/eve/src/sandbox/providers/just-bash.ts
index cd82deece..abab78ac0 100644
--- a/packages/eve/src/sandbox/providers/just-bash.ts
+++ b/packages/eve/src/sandbox/providers/just-bash.ts
@@ -1,11 +1,11 @@
import { createJustBashSandboxProvider } from "#execution/sandbox/bindings/local.js";
import type { JustBashSandboxCreateOptions } from "#public/sandbox/just-bash-sandbox.js";
-import { defineSandboxProvider } from "#shared/sandbox-provider.js";
+import { defineLegacySandboxProvider } from "#shared/sandbox-provider.js";
import type { SandboxSession } from "#shared/sandbox-session.js";
export type JustBashEnvironmentOptions = JustBashSandboxCreateOptions;
-export const JustBashSandbox = defineSandboxProvider<
+export const JustBashSandbox = defineLegacySandboxProvider<
JustBashEnvironmentOptions,
undefined,
{ readonly templateKey: string },
diff --git a/packages/eve/src/sandbox/providers/vercel.ts b/packages/eve/src/sandbox/providers/vercel.ts
index 2560d45ac..77b2dcff9 100644
--- a/packages/eve/src/sandbox/providers/vercel.ts
+++ b/packages/eve/src/sandbox/providers/vercel.ts
@@ -9,7 +9,7 @@ import type {
VercelSandboxRuntimeOptions,
} from "#public/sandbox/vercel-sandbox.js";
import type { SandboxEnvironment } from "#shared/sandbox-environment.js";
-import { defineSandboxProvider } from "#shared/sandbox-provider.js";
+import { defineLegacySandboxProvider } from "#shared/sandbox-provider.js";
import type { SandboxSession } from "#shared/sandbox-session.js";
export type VercelSandboxEnvironmentOptions = VercelSandboxCreateOptions & {
@@ -17,7 +17,7 @@ export type VercelSandboxEnvironmentOptions = VercelSandboxCreateOptions & {
};
export type { VercelSandboxRuntimeOptions } from "#public/sandbox/vercel-sandbox.js";
-const provider = defineSandboxProvider<
+const provider = defineLegacySandboxProvider<
VercelSandboxEnvironmentOptions | undefined,
VercelSandboxRuntimeOptions,
VercelSandboxPreparedArtifact,
diff --git a/packages/eve/src/shared/sandbox-network-policy.ts b/packages/eve/src/shared/sandbox-network-policy.ts
index 548b4ebff..6ffe0ba03 100644
--- a/packages/eve/src/shared/sandbox-network-policy.ts
+++ b/packages/eve/src/shared/sandbox-network-policy.ts
@@ -1,12 +1,9 @@
-import type * as Vercel from "#compiled/@vercel/sandbox/index.js";
-
/**
* Firewall network policy applied to a live sandbox session.
*
- * eve-owned alias of the provider network-policy shape. Use it to restrict
- * egress (`"deny-all"`, an allow-list) or to broker credentials onto
- * outgoing requests. A per-domain `transform` injects headers at the
- * firewall so secrets never enter the sandbox process:
+ * Use it to restrict egress (`"deny-all"`, an allow-list) or to broker
+ * credentials onto outgoing requests. A per-domain `transform` injects
+ * headers at the firewall so secrets never enter the sandbox process:
*
* ```ts
* import { environment } from "../sandbox";
@@ -20,11 +17,47 @@ import type * as Vercel from "#compiled/@vercel/sandbox/index.js";
* });
* ```
*
- * The Docker provider honors only the coarse `"allow-all"` and
- * `"deny-all"` policies. just-bash environments do not expose
- * `setNetworkPolicy` because their network policy is fixed at sandbox creation.
+ * A provider rejects any part of a policy it cannot enforce instead of
+ * weakening it. The Docker provider honors only `"allow-all"` and
+ * `"deny-all"`.
*/
-export type SandboxNetworkPolicy = Vercel.NetworkPolicy;
+export type SandboxNetworkPolicy =
+ | "allow-all"
+ | "deny-all"
+ | {
+ /** Allowed domains, or a map from domain to the rules applied to its requests. */
+ readonly allow?: readonly string[] | Readonly<Record<string, readonly SandboxNetworkRule[]>>;
+ readonly subnets?: {
+ readonly allow?: readonly string[];
+ readonly deny?: readonly string[];
+ };
+ };
+
+/** Exactly one of `transform` (inject headers) or `forwardURL` (proxy the request). */
+export type SandboxNetworkRule = { readonly match?: SandboxNetworkMatch } & (
+ | { readonly transform: readonly { readonly headers?: Readonly<Record<string, string>> }[] }
+ | { readonly forwardURL: string }
+);
+
+/** Which requests a {@link SandboxNetworkRule} applies to. */
+export interface SandboxNetworkMatch {
+ readonly headers?: readonly {
+ readonly key?: SandboxNetworkMatcher;
+ readonly value?: SandboxNetworkMatcher;
+ }[];
+ readonly method?: readonly string[];
+ readonly path?: SandboxNetworkMatcher;
+ readonly queryString?: readonly {
+ readonly key?: SandboxNetworkMatcher;
+ readonly value?: SandboxNetworkMatcher;
+ }[];
+}
+
+/** Sets exactly one of `exact`, `startsWith`, or `regex`. */
+export type SandboxNetworkMatcher =
+ | { readonly exact: string }
+ | { readonly startsWith: string }
+ | { readonly regex: string };
/** Initial network configuration shared by network-capable sandbox providers. */
export interface SandboxNetworkOptions {
diff --git a/packages/eve/src/shared/sandbox-provider.test.ts b/packages/eve/src/shared/sandbox-provider.test.ts
index 3eb347b66..ca902aad3 100644
--- a/packages/eve/src/shared/sandbox-provider.test.ts
+++ b/packages/eve/src/shared/sandbox-provider.test.ts
@@ -1,9 +1,9 @@
import { describe, expect, expectTypeOf, it, vi } from "vitest";
import { getSandboxEnvironmentRuntime } from "#shared/sandbox-environment.js";
-import { defineSandboxProvider } from "#shared/sandbox-provider.js";
+import { defineLegacySandboxProvider } from "#shared/sandbox-provider.js";
-const provider = defineSandboxProvider<
+const provider = defineLegacySandboxProvider<
{ readonly image?: string },
{ readonly networkPolicy?: "allow-all" | "deny-all" },
{ readonly templateId: string },
@@ -37,6 +37,7 @@ function handle(nativeId: string) {
readTextFile: vi.fn(),
writeFile: vi.fn(),
writeBinaryFile: vi.fn(),
+ writeFiles: vi.fn(),
writeTextFile: vi.fn(),
removePath: vi.fn(),
},
@@ -47,7 +48,7 @@ function handle(nativeId: string) {
};
}
-describe("defineSandboxProvider", () => {
+describe("defineLegacySandboxProvider", () => {
it("preserves provider-owned environment and open option types", () => {
const environment = provider.environment({ image: "node:24" });
expect(environment.provider).toBe("test-provider");
diff --git a/packages/eve/src/shared/sandbox-provider.ts b/packages/eve/src/shared/sandbox-provider.ts
index 26068209a..6ffccf9e1 100644
--- a/packages/eve/src/shared/sandbox-provider.ts
+++ b/packages/eve/src/shared/sandbox-provider.ts
@@ -128,7 +128,7 @@ export interface SandboxProviderHandle<Session extends SandboxSession = SandboxS
onSandboxStop(): Promise<void>;
}
-export interface SandboxProviderImplementation<
+export interface LegacySandboxProviderImplementation<
OpenOptions extends object | undefined,
PreparedArtifact extends SandboxPreparedArtifact,
SessionState,
@@ -172,7 +172,7 @@ type SandboxOptionArguments<Options extends object | undefined> = Options extend
? [options?: Readonly<Options>]
: [options: Readonly<Options>];
-export type SandboxProviderDefinition<
+export type LegacySandboxProviderDefinition<
EnvironmentOptions extends object | undefined,
OpenOptions extends object | undefined,
PreparedArtifact extends SandboxPreparedArtifact,
@@ -183,7 +183,7 @@ export type SandboxProviderDefinition<
readonly stateProtocolVersion?: number;
environment(
...args: SandboxOptionArguments<EnvironmentOptions>
- ): SandboxProviderImplementation<OpenOptions, PreparedArtifact, SessionState, Session>;
+ ): LegacySandboxProviderImplementation<OpenOptions, PreparedArtifact, SessionState, Session>;
};
export interface SandboxProvider<
@@ -197,7 +197,7 @@ export interface SandboxProvider<
): SandboxEnvironment<OpenOptions, Session>;
}
-type ErasedSandboxProviderImplementation = SandboxProviderImplementation<
+type ErasedSandboxProviderImplementation = LegacySandboxProviderImplementation<
object | undefined,
SandboxPreparedArtifact,
SandboxPreparedArtifact,
@@ -210,14 +210,20 @@ export interface SandboxProviderRuntime {
readonly stateProtocolVersion: number;
}
-export function defineSandboxProvider<
+/**
+ * Defines a provider on the handle-based contract that eve's built-in
+ * providers still implement and core runs. Internal: the public
+ * `defineSandboxProvider()` in `#sandbox/provider.js` compiles the
+ * connection-based contract onto it until every built-in migrates.
+ */
+export function defineLegacySandboxProvider<
EnvironmentOptions extends object | undefined = undefined,
OpenOptions extends object | undefined = undefined,
PreparedArtifact extends SandboxPreparedArtifact = SandboxPreparedArtifact,
SessionState = SandboxPreparedArtifact,
Session extends SandboxSession = SandboxSession,
>(
- definition: SandboxProviderDefinition<
+ definition: LegacySandboxProviderDefinition<
EnvironmentOptions,
OpenOptions,
PreparedArtifact,
@@ -247,7 +253,7 @@ function eraseSandboxProviderImplementation<
SessionState,
Session extends SandboxSession,
>(
- implementation: SandboxProviderImplementation<Options, Artifact, SessionState, Session>,
+ implementation: LegacySandboxProviderImplementation<Options, Artifact, SessionState, Session>,
): ErasedSandboxProviderImplementation {
return implementation as ErasedSandboxProviderImplementation;
}
diff --git a/packages/eve/src/shared/sandbox-session-gone-error.ts b/packages/eve/src/shared/sandbox-session-gone-error.ts
index e972b09b0..a9bcccb22 100644
--- a/packages/eve/src/shared/sandbox-session-gone-error.ts
+++ b/packages/eve/src/shared/sandbox-session-gone-error.ts
@@ -1,11 +1,21 @@
/**
* Thrown by a provider's `resume()` when the session's native sandbox no
- * longer exists. Core then clears the session's sandbox state and starts a
- * fresh sandbox, as it would after `sandbox.delete()`.
+ * longer exists. eve then clears the session's sandbox state and reruns the
+ * sandbox selector, which starts a fresh sandbox, as it would after
+ * `sandbox.delete()`. Throw it only for a sandbox that is gone; other
+ * failures must surface unchanged.
*/
export class SandboxSessionGoneError extends Error {
constructor(message: string) {
super(message);
this.name = "SandboxSessionGoneError";
}
+
+ /** Also matches an error from another copy of this class, such as one a provider bundles. */
+ static is(error: unknown): error is SandboxSessionGoneError {
+ return (
+ error instanceof SandboxSessionGoneError ||
+ (error instanceof Error && error.name === "SandboxSessionGoneError")
+ );
+ }
}
diff --git a/packages/eve/src/shared/sandbox-session.ts b/packages/eve/src/shared/sandbox-session.ts
index ec861596b..624134b7b 100644
--- a/packages/eve/src/shared/sandbox-session.ts
+++ b/packages/eve/src/shared/sandbox-session.ts
@@ -1,66 +1,82 @@
-import type { Experimental_SandboxSession as AiSdkSandbox } from "ai";
-
import type { SandboxDeleteOptions } from "#shared/sandbox-provider.js";
/**
- * Options for running one command in a sandbox. Shape mirrors the AI
- * SDK {@link AiSdkSandbox} `run` argument so authored code that targets
- * either surface uses the same call shape.
+ * Options for running one command, or spawning one process, in a sandbox.
+ * `env` holds per-call variables, merged over the sandbox's environment.
+ * Aborting kills the process.
*/
-export type SandboxRunOptions = Parameters<AiSdkSandbox["run"]>[0];
+export interface SandboxRunOptions {
+ readonly abortSignal?: AbortSignal;
+ readonly command: string;
+ readonly env?: Readonly<Record<string, string>>;
+ /** Relative directories resolve from `/workspace`, which is also the default. */
+ readonly workingDirectory?: string;
+}
-/**
- * Serializable result returned after running one sandbox command.
- */
-export type SandboxCommandResult = Awaited<ReturnType<AiSdkSandbox["run"]>>;
+/** Options for spawning one long-running process in a sandbox. */
+export type SandboxSpawnOptions = SandboxRunOptions;
-/**
- * Options for spawning one long-running process in a sandbox. Shape
- * mirrors the AI SDK {@link AiSdkSandbox} `spawn` argument.
- */
-export type SandboxSpawnOptions = Parameters<AiSdkSandbox["spawn"]>[0];
+/** Result of one finished sandbox command. A nonzero `exitCode` does not throw. */
+export interface SandboxCommandResult {
+ readonly exitCode: number;
+ readonly stderr: string;
+ readonly stdout: string;
+}
-/**
- * Handle to a long-running process spawned via {@link SandboxSession.spawn}.
- * Mirrors the AI SDK `Experimental_SandboxProcess` type.
- */
-export type SandboxProcess = Awaited<ReturnType<AiSdkSandbox["spawn"]>>;
+/** Handle to a long-running process spawned via {@link SandboxSession.spawn}. */
+export interface SandboxProcess {
+ readonly pid?: number;
+ readonly stderr: ReadableStream<Uint8Array>;
+ readonly stdout: ReadableStream<Uint8Array>;
+ /** Terminates the process. Idempotent. */
+ kill(): Promise<void>;
+ wait(): Promise<{ readonly exitCode: number }>;
+}
-/**
- * Options for reading one file as a stream of bytes.
- */
-export type SandboxReadFileOptions = Parameters<AiSdkSandbox["readFile"]>[0];
+/** Options for reading one file as a stream of bytes. */
+export interface SandboxReadFileOptions {
+ readonly abortSignal?: AbortSignal;
+ readonly path: string;
+}
-/**
- * Options for reading one file as raw bytes.
- */
-export type SandboxReadBinaryFileOptions = Parameters<AiSdkSandbox["readBinaryFile"]>[0];
+/** Options for reading one file as raw bytes. */
+export type SandboxReadBinaryFileOptions = SandboxReadFileOptions;
/**
* Options for reading one text file from a sandbox.
*
- * `encoding`, `startLine`, and `endLine` are passed through to the
- * public-surface decoder. `"utf-8"` decodes with `TextDecoder` in fatal
- * mode; other encodings fall back to Node's `Buffer.toString(encoding)`.
- * Line ranges are 1-based and inclusive; `endLine` past the file's line
- * count returns through EOF without error.
+ * `"utf-8"` decodes with `TextDecoder` in fatal mode; other encodings fall
+ * back to Node's `Buffer.toString(encoding)`. Line ranges are 1-based and
+ * inclusive; `endLine` past the file's line count returns through EOF
+ * without error.
*/
-export type SandboxReadTextFileOptions = Parameters<AiSdkSandbox["readTextFile"]>[0];
+export interface SandboxReadTextFileOptions extends SandboxReadFileOptions {
+ readonly encoding?: string;
+ readonly endLine?: number;
+ readonly startLine?: number;
+}
-/**
- * Options for writing one file from a stream of bytes.
- */
-export type SandboxWriteFileOptions = Parameters<AiSdkSandbox["writeFile"]>[0];
+/** Options for writing one file from a stream of bytes. */
+export interface SandboxWriteFileOptions {
+ readonly abortSignal?: AbortSignal;
+ readonly content: ReadableStream<Uint8Array>;
+ readonly path: string;
+}
-/**
- * Options for writing one file from raw bytes.
- */
-export type SandboxWriteBinaryFileOptions = Parameters<AiSdkSandbox["writeBinaryFile"]>[0];
+/** Options for writing one file from raw bytes. */
+export interface SandboxWriteBinaryFileOptions {
+ readonly abortSignal?: AbortSignal;
+ readonly content: Uint8Array;
+ readonly path: string;
+}
-/**
- * Options for writing one text file to a sandbox.
- */
-export type SandboxWriteTextFileOptions = Parameters<AiSdkSandbox["writeTextFile"]>[0];
+/** Options for writing one text file to a sandbox. Encodes as UTF-8 unless `encoding` is set. */
+export interface SandboxWriteTextFileOptions {
+ readonly abortSignal?: AbortSignal;
+ readonly content: string;
+ readonly encoding?: string;
+ readonly path: string;
+}
/**
* Options for writing several files from raw bytes in one batch.
@@ -85,42 +101,36 @@ export interface SandboxRemovePathOptions {
}
/**
- * Public eve-owned sandbox session exposed to authored lifecycle hooks.
+ * The sandbox session that authored tools, hooks, and `prepare` receive.
*
- * The eight I/O methods (`run`, `spawn`, `readFile`, `readBinaryFile`,
- * `readTextFile`, `writeFile`, `writeBinaryFile`, `writeTextFile`) are
- * pulled directly from the AI SDK {@link AiSdkSandbox} type, so authored
- * code that targets either surface uses identical signatures. `resolvePath`
- * is an eve-specific extension for `/workspace` path anchoring.
- *
- * Relative paths resolve from `/workspace`, the live working directory
- * for every provider. Absolute paths pass through unchanged.
+ * Relative paths resolve from `/workspace`, the live working directory for
+ * every provider. Absolute paths pass through unchanged. Writes create
+ * missing parent directories and overwrite existing files. Reads resolve to
+ * `null` only when the path does not exist.
*
+ * The method set stays assignable to the AI SDK's
+ * `Experimental_SandboxSession`, apart from its `description`.
*/
-export interface SandboxSession extends Pick<
- AiSdkSandbox,
- | "run"
- | "spawn"
- | "readFile"
- | "readBinaryFile"
- | "readTextFile"
- | "writeFile"
- | "writeBinaryFile"
- | "writeTextFile"
-> {
+export interface SandboxSession {
+ run(options: SandboxRunOptions): Promise<SandboxCommandResult>;
+ spawn(options: SandboxSpawnOptions): Promise<SandboxProcess>;
+ readFile(options: SandboxReadFileOptions): Promise<ReadableStream<Uint8Array> | null>;
+ readBinaryFile(options: SandboxReadBinaryFileOptions): Promise<Uint8Array | null>;
+ readTextFile(options: SandboxReadTextFileOptions): Promise<string | null>;
+ writeFile(options: SandboxWriteFileOptions): Promise<void>;
+ writeBinaryFile(options: SandboxWriteBinaryFileOptions): Promise<void>;
+ writeTextFile(options: SandboxWriteTextFileOptions): Promise<void>;
/**
- * Anchors a sandbox-relative path to `/workspace` and returns the
- * resulting absolute path.
- *
- * Relative paths resolve from `/workspace`; absolute paths pass through.
- * The read and write methods already apply this internally.
+ * Writes several files in as few provider calls as the provider allows. A
+ * batch is not atomic: a rejected batch may leave earlier files written.
*/
- resolvePath(path: string): string;
+ writeFiles(options: SandboxWriteFilesOptions): Promise<void>;
/**
- * Removes one file or directory from the sandbox filesystem.
- *
- * Relative paths resolve from `/workspace`; absolute paths pass through.
+ * Anchors a sandbox-relative path to `/workspace` and returns the
+ * resulting absolute path. The read and write methods already apply it.
*/
+ resolvePath(path: string): string;
+ /** Removes one file or directory from the sandbox filesystem. */
removePath(options: SandboxRemovePathOptions): Promise<void>;
}
@@ -139,27 +149,18 @@ export type RuntimeSandboxSessionFor<Session extends SandboxSession> = Session &
Pick<RuntimeSandboxSession, "delete" | "stop">;
/**
- * Internal sandbox session, used to construct the public {@link SandboxSession}.
- *
- * Provider implementations only need to provide byte-oriented file I/O and
- * a `spawn` primitive; the public surface (binary and text variants,
- * line-range slicing, encoding handling, the `run` wrapper) is built on
- * top of these primitives by `buildSandboxSession`.
- *
- * Each method's signature mirrors its public counterpart (and the AI
- * SDK {@link AiSdkSandbox} surface) so providers look symmetric with
- * what authored code sees. The `path` field on `readFile`/`writeFile`
- * here is the **already-resolved** path: the public-surface builder
- * calls `resolvePath` before delegating.
+ * Byte-level primitives a built-in provider implements; `buildSandboxSession`
+ * derives the public {@link SandboxSession} from them. Paths are already
+ * resolved.
*/
-export interface InternalSandboxSession extends Pick<
- AiSdkSandbox,
- "spawn" | "readFile" | "writeFile"
-> {
+export interface InternalSandboxSession {
+ readFile(options: SandboxReadFileOptions): Promise<ReadableStream<Uint8Array> | null>;
/** Removes an already-resolved path from the provider filesystem. */
removePath(options: SandboxRemovePathOptions): Promise<void>;
/** Translates a user-facing path to the provider's native path. */
resolvePath(path: string): string;
+ spawn(options: SandboxSpawnOptions): Promise<SandboxProcess>;
+ writeFile(options: SandboxWriteFileOptions): Promise<void>;
/**
* Writes several already-resolved files in one provider call. Providers that
* omit it get one `writeFile` per file.
diff --git a/packages/eve/src/shared/sandbox-write-files.ts b/packages/eve/src/shared/sandbox-write-files.ts
deleted file mode 100644
index 42e5ef439..000000000
--- a/packages/eve/src/shared/sandbox-write-files.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { mapWithConcurrency } from "#shared/map-with-concurrency.js";
-import type { SandboxSession, SandboxWriteFilesOptions } from "#shared/sandbox-session.js";
-
-const FALLBACK_WRITE_CONCURRENCY = 16;
-
-/**
- * Where `buildSandboxSession` puts a provider's batch write. A symbol keeps it
- * off the public session type while session wrappers, which spread or proxy
- * the session, still carry it. A wrapper that changes calls, such as
- * `bindSandboxAbortSignal`, must wrap it too.
- */
-export const SANDBOX_WRITE_FILES = Symbol("eve.sandbox.writeFiles");
-
-type SandboxWriteFiles = (options: SandboxWriteFilesOptions) => Promise<void>;
-
-/** The session's batch write, when its provider has one. */
-export function getSandboxWriteFiles(session: SandboxSession): SandboxWriteFiles | undefined {
- return (session as { readonly [SANDBOX_WRITE_FILES]?: SandboxWriteFiles })[SANDBOX_WRITE_FILES];
-}
-
-/**
- * Writes `files` in one provider call when the provider supports it, and one
- * `writeBinaryFile` per file otherwise. Paths resolve like `writeBinaryFile`.
- */
-export async function writeSandboxFiles(
- session: SandboxSession,
- options: SandboxWriteFilesOptions,
-): Promise<void> {
- const writeFiles = getSandboxWriteFiles(session);
- if (writeFiles !== undefined) {
- await writeFiles(options);
- return;
- }
- await mapWithConcurrency(options.files, FALLBACK_WRITE_CONCURRENCY, async (file) => {
- await session.writeBinaryFile({
- abortSignal: options.abortSignal,
- content: file.content,
- path: file.path,
- });
- });
-}
diff --git a/packages/eve/src/shared/skill-package.test.ts b/packages/eve/src/shared/skill-package.test.ts
index 0b9c33938..2e127b694 100644
--- a/packages/eve/src/shared/skill-package.test.ts
+++ b/packages/eve/src/shared/skill-package.test.ts
@@ -94,30 +94,6 @@ describe("writeSkillPackageToSandbox", () => {
);
});
- it("writes several files at once, but not all of them", async () => {
- let inFlight = 0;
- let maxInFlight = 0;
- const session = {
- ...mockSandbox().session,
- async writeBinaryFile() {
- maxInFlight = Math.max(maxInFlight, ++inFlight);
- await Promise.resolve();
- inFlight -= 1;
- },
- };
- const skill = normalizeSkillPackage({
- name: "tenant",
- description: "Tenant-specific procedures.",
- markdown: "Follow tenant policy.",
- files: Object.fromEntries(Array.from({ length: 40 }, (_, i) => [`references/${i}.md`, ""])),
- });
-
- await writeSkillPackageToSandbox({ sandbox: session, skill });
-
- expect(maxInFlight).toBeGreaterThan(1);
- expect(maxInFlight).toBeLessThan(skill.files.length);
- });
-
it("falls back to the legacy workspace skill directory when HOME is unavailable", async () => {
const sandbox = mockSandbox();
const skill = normalizeSkillPackage({
diff --git a/packages/eve/src/shared/skill-package.ts b/packages/eve/src/shared/skill-package.ts
index ed3a6caf8..d4acfb099 100644
--- a/packages/eve/src/shared/skill-package.ts
+++ b/packages/eve/src/shared/skill-package.ts
@@ -4,7 +4,6 @@ import { mkdir, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import type { SandboxSession } from "#shared/sandbox-session.js";
-import { writeSandboxFiles } from "#shared/sandbox-write-files.js";
import type { NamedSkillDefinition } from "#shared/skill-definition.js";
import { resolveSandboxSkillRoot, resolveSandboxSkillWritePath } from "#shared/skill-paths.js";
@@ -106,7 +105,7 @@ export async function writeSkillPackageToSandbox(input: {
}),
})),
);
- await writeSandboxFiles(input.sandbox, { files });
+ await input.sandbox.writeFiles({ files });
}
/**
diff --git a/packages/eve/test/glob-tool.test.ts b/packages/eve/test/glob-tool.test.ts
index cc3eb6e21..c973559a3 100644
--- a/packages/eve/test/glob-tool.test.ts
+++ b/packages/eve/test/glob-tool.test.ts
@@ -74,6 +74,7 @@ function createFakeAccess(
},
async writeFile() {},
async writeBinaryFile() {},
+ async writeFiles() {},
async writeTextFile() {},
};
},
diff --git a/packages/eve/test/grep-tool.test.ts b/packages/eve/test/grep-tool.test.ts
index f1f08f0ad..ea6ff499a 100644
--- a/packages/eve/test/grep-tool.test.ts
+++ b/packages/eve/test/grep-tool.test.ts
@@ -74,6 +74,7 @@ function createFakeAccess(
},
async writeFile() {},
async writeBinaryFile() {},
+ async writeFiles() {},
async writeTextFile() {},
};
},
diff --git a/packages/eve/test/read-file-tool.test.ts b/packages/eve/test/read-file-tool.test.ts
index 3aff26f1d..03c1f0117 100644
--- a/packages/eve/test/read-file-tool.test.ts
+++ b/packages/eve/test/read-file-tool.test.ts
@@ -55,6 +55,7 @@ function createFakeAccess(files: Record<string, string | null>): SandboxAccess {
},
async writeFile() {},
async writeBinaryFile() {},
+ async writeFiles() {},
async writeTextFile() {},
};
},
diff --git a/packages/eve/test/write-file-tool.test.ts b/packages/eve/test/write-file-tool.test.ts
index fd916518c..fc3a30db7 100644
--- a/packages/eve/test/write-file-tool.test.ts
+++ b/packages/eve/test/write-file-tool.test.ts
@@ -53,6 +53,7 @@ function createFakeAccess(files: Record<string, string>): {
},
async writeFile() {},
async writeBinaryFile() {},
+ async writeFiles() {},
async writeTextFile({ path, content }: { path: string; content: string }) {
files[path] = content;
},
diff --git a/research/sandbox-provider-api.md b/research/sandbox-provider-api.md
index 82ce01589..1be1c34df 100644
--- a/research/sandbox-provider-api.md
+++ b/research/sandbox-provider-api.md
@@ -1,6 +1,6 @@
---
issue: "TBD (maintainer-requested research; no matching issue found)"
-status: proposed
+status: in-progress
last_updated: "2026-10-22"
---
@@ -158,7 +158,7 @@ a type error (`never`), and eve throws on them at runtime.
```ts
export function defineSandboxProvider<
- EnvironmentOptions extends object | undefined,
+ EnvironmentOptions extends object,
OpenOptions extends object | undefined,
Artifact extends SandboxJson,
State extends SandboxJson,
@@ -167,7 +167,7 @@ export function defineSandboxProvider<
readonly name: string;
readonly stateProtocolVersion?: number;
environment(
- ...args: SandboxOptionArguments<EnvironmentOptions>
+ options: EnvironmentOptions,
): SandboxProviderImplementation<OpenOptions, Artifact, State, Extensions>;
}): SandboxProvider<
WithPrepareOption<EnvironmentOptions, SandboxSession & Extensions>,
@@ -176,7 +176,7 @@ export function defineSandboxProvider<
>;
export interface SandboxProviderImplementation<OpenOptions, Artifact, State, Extensions> {
- prepare(ctx: SandboxPrepareContext<Extensions>): Promise<Artifact>;
+ prepare(ctx: SandboxPrepareContext): Promise<Artifact>;
start(
ctx: SandboxSessionContext,
options: Readonly<OpenOptions> | undefined,
@@ -207,7 +207,7 @@ export interface SandboxSessionContext {
resolveProjectPath(path: string): string;
}
-export interface SandboxPrepareContext<Extensions extends object> {
+export interface SandboxPrepareContext {
readonly files: SandboxProviderFiles;
readonly storagePath: string;
/** No workspace or skill files and no authored `prepare`. */
@@ -219,14 +219,13 @@ export interface SandboxPrepareContext<Extensions extends object> {
resourcesDirectory(): Promise<string | undefined>;
/** Seeds `/workspace` and `$HOME/.agents/skills`, then runs authored `prepare`. */
populate(
- connection: SandboxConnection<Extensions>,
+ connection: SandboxConnection<object>,
options?: { readonly mountedAt?: string },
): Promise<void>;
}
-export type WithPrepareOption<Options, Session> = Options extends undefined
- ? SandboxPrepareOption<Session> | undefined
- : Options & SandboxPrepareOption<Session>;
+export type WithPrepareOption<Options extends object, Session> = Options &
+ SandboxPrepareOption<Session>;
export interface SandboxPrepareOption<Session> {
readonly prepare?: (sandbox: Session) => void | Promise<void>;
@@ -234,7 +233,11 @@ export interface SandboxPrepareOption<Session> {
```
Type parameters are inferred from the returned implementation, so authors do
-not pass five explicit generics. `SandboxJson` is today's
+not pass five explicit generics. `environment()` takes a plain parameter, and
+`SandboxPrepareContext` is not generic over the extensions, because TypeScript
+cannot infer through a conditional rest tuple and fixes a type parameter as soon
+as a context-sensitive method such as `prepare(ctx)` uses it. `State` comes from
+`start()`'s return value when `start()` precedes `resume()`. `SandboxJson` is today's
`SandboxPreparedArtifact` under a name that fits both artifacts and state.
`ctx.session.id` keeps its current meaning: the id of the session that owns
@@ -280,7 +283,8 @@ root.
`prepare` becomes a standard environment option through `WithPrepareOption`,
typed with the provider's extensions (#3717). A provider without environment
options still accepts `{ prepare }`. eve removes `prepare` before calling the
-provider's `environment()` and runs it inside `populate()`. No built-in
+provider's `environment()`, which always receives an object (`{}` when the
+caller passes none), and runs it inside `populate()`. No built-in
includes `prepare` in its template identity today. `sourceRevision` hashes only
the sandbox definition's source file, so it captures a `prepare` written there
but not one imported from another module (see open questions).
@@ -318,12 +322,14 @@ runtime
eve checkpoints { providerName, state, stateProtocolVersion }
later step ─ resume(ctx, artifact, state) → connection
└─ throws SandboxSessionGoneError → eve clears state, reruns selector
- sandbox.stop() → connection.stop()
+ sandbox.stop() → connection.stop(), connection.close?()
sandbox.delete() → connection.close?(), onSessionEnd(ctx, state, { reason: "deleted" }),
eve clears state
- process exit → connection.stop() (failures logged, not thrown)
+ process exit → connection.stop(), connection.close?() (failures logged, not thrown)
keyed call ends → connection.close?()
- terminal outcome → onSessionEnd(ctx, state | null, { reason })
+ terminal outcome → connection.close?() for this process's connections,
+ onSessionEnd(ctx, state | null, { reason })
+ (stop and close run at most once per connection; a failed close never blocks deletion)
```
## Invariants
@@ -503,13 +509,16 @@ the last step. There are no public dual-shape overloads.
custom-provider docs in `docs/sandbox/index.mdx`, migrate the e2e
`custom-provider` fixture, and add evals for gone-sandbox recovery and for
keyed calls on a provider without `toolSessions`. Built-ins keep the old
- shape through the internal type (minor changeset).
+ shape through the internal type (minor changeset). Implemented: the public
+ `writeFiles()` replaced `SANDBOX_WRITE_FILES` in this step, and unit tests
+ through the public API cover keyed calls, because no e2e fixture has a
+ custom root sandbox behind a keyed channel.
2. Migrate just-bash, with the golden key and name test.
3. Migrate Docker, with the golden key and name test.
4. Migrate Vercel Sandbox, with the golden key and name test. Its changeset
notes that a relative `workingDirectory` now resolves from `/workspace`.
5. Make core consume the new shape directly. Remove the internal old shape,
- the tool-session `WeakMap`, and `SANDBOX_WRITE_FILES`. Add a
+ and the tool-session `WeakMap`. Add a
`guard:invariants` rule for files under `src/execution/sandbox/bindings/`
and `src/sandbox/providers/`: they may import the provider contract only
through `#public/sandbox/*`, and may not import core sandbox modules
diff --git a/scripts/guard-invariants.mjs b/scripts/guard-invariants.mjs
index 30225465f..9967075b5 100644
--- a/scripts/guard-invariants.mjs
+++ b/scripts/guard-invariants.mjs
@@ -96,9 +96,10 @@
* import subagent modules; session/turn composition roots may
* compose built-in executors directly.
* rule 44 — Every concrete built-in sandbox provider is defined through
- * `defineSandboxProvider()` and does not import sandbox runtime
+ * `defineSandboxProvider()`, or the internal
+ * `defineLegacySandboxProvider()` until it migrates to the
+ * connection contract, and does not import sandbox runtime
* orchestration, registries, key derivation, or session state.
- * Built-ins and authored providers must share one contract.
* rule 45 — Provided tools under `packages/eve/src/tools/provided/**` and
* the body of every agent tool import only public eve entry
* points (the `#` specifiers of the package's `exports`), the
@@ -1695,7 +1696,7 @@ async function checkRule44SandboxProviders() {
for (const name of providerNames) {
const file = `packages/eve/src/sandbox/providers/${name}.ts`;
const source = await readFile(join(REPO_ROOT, file), "utf8");
- if (!source.includes("defineSandboxProvider")) {
+ if (!/\bdefine(Legacy)?SandboxProvider\b/.test(source)) {
issues.push({
file,
message: "Built-in sandbox providers must use defineSandboxProvider().",