Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

Redesign sandbox environments and provider sessions (#3271)

Casey Gowrie49971b7ef414
diff --git a/.changeset/sandbox-environments.md b/.changeset/sandbox-environments.md
new file mode 100644
index 000000000..d34e7e1d4
--- /dev/null
+++ b/.changeset/sandbox-environments.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+Replace object-form sandbox definitions with exported provider environments whose `open()` method starts and returns the current eve session's persistent live sandbox. After successful selector initialization, durable boundaries resume directly from immutable provider state without rerunning `defineSandbox()`; provider-specific session capabilities remain precisely typed.
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 74cc94631..e020efd0a 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -6,6 +6,9 @@ on:
pull_request:
branches: [main]
+env:
+ EVE_SANDBOX_IMAGE_TAG: latest
+
jobs:
lint:
runs-on: ubuntu-latest
diff --git a/.github/workflows/e2e-local.yml b/.github/workflows/e2e-local.yml
index b5bbfa009..235ac9723 100644
--- a/.github/workflows/e2e-local.yml
+++ b/.github/workflows/e2e-local.yml
@@ -103,6 +103,15 @@ jobs:
if: needs.changes.outputs.relevant == 'true'
run: pnpm install --frozen-lockfile
+ - name: Install microsandbox runtime
+ if: needs.changes.outputs.relevant == 'true' && matrix.name == 'agent-microsandbox-dockerfile'
+ run: |
+ test -e /dev/kvm
+ sudo chmod 666 /dev/kvm
+ docker info
+ pnpm --filter agent-microsandbox-dockerfile exec node --input-type=module -e \
+ 'import { setup } from "microsandbox"; await setup().install();'
+
- name: Build eve package
if: needs.changes.outputs.relevant == 'true'
# Full build, not build:js: the deployed/runtime bundles must carry the
diff --git a/apps/docs/app/[lang]/(home)/components/file-tree.tsx b/apps/docs/app/[lang]/(home)/components/file-tree.tsx
index 569599378..cf24bc67e 100644
--- a/apps/docs/app/[lang]/(home)/components/file-tree.tsx
+++ b/apps/docs/app/[lang]/(home)/components/file-tree.tsx
@@ -111,16 +111,21 @@ export default defineTool({
NavIcon: IconSandbox,
description:
"Every agent includes an isolated sandbox. Add sandbox/sandbox.ts to swap in any backend or customize its setup.",
- code: `import { defineSandbox } from
- "eve/sandbox";
+ code: `import { DefaultSandbox,
+ defineSandbox } from "eve/sandbox";
-export default defineSandbox({
- async bootstrap({ sandbox }) {
- await sandbox.run(
- "git clone repo /workspace"
- );
- },
-});`,
+export const environment =
+ DefaultSandbox.environment({
+ prepare: async (sandbox) => {
+ await sandbox.run({
+ command: "git clone repo /workspace"
+ });
+ }
+ });
+
+export default defineSandbox(() =>
+ environment.open()
+);`,
},
{
label: "Channels",
diff --git a/docs/README.md b/docs/README.md
index b15c0a0c9..459d02d58 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -12,32 +12,28 @@ Important naming note:
## Find the page for your task
-| To do this | Read this |
-| -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
-| Organize agents, subagents, and browser application code | [Project Structure](./concepts/project-structure.mdx) |
-| Create a project and run your first agent | [Getting Started](./getting-started.mdx) |
-| Look up agent files and discovery rules | [Agent Files](./reference/agent-files.md) |
-| Set the model, reasoning, or other agent-wide config | [Agents](./agent-config.md) |
-| Choose an agent model automatically for each request | [Automatic Model Selection](./guides/evaluate.md) |
-| Change what the agent does and how it behaves | [Instructions](./instructions.mdx) |
-| Give the agent a typed capability it can call | [Tools](./tools/overview.mdx) |
-| Require approval, or ask the user something mid-turn | [Human in the Loop](./tools/human-in-the-loop.md) |
-| Call an external HTTP API or MCP server | [Connections](./connections/overview.mdx) |
-| Add a messaging surface (Slack, Discord, iMessage, …) | [Channels](./channels/overview.mdx) |
-| Expose your own HTTP route as a conversation surface | [Custom Channels](./channels/custom.mdx) |
-| Package a procedure the agent loads only when it applies | [Skills](./skills.mdx) |
-| Carry state across turns, or shape what the model sees | [State](./concepts/state.md), [Context Control](./concepts/context-control.md) |
-| Run commands or untrusted code in isolation | [Sandboxes](./sandbox.mdx) |
-| Delegate work to a specialist child agent | [Subagents](./subagents/index.mdx) |
-| Run work on a recurring schedule | [Schedules](./schedules.mdx) |
-| Install an existing integration instead of writing one | [Add Integrations](./install-integrations.mdx) |
-| Link a Vercel project and deploy to production | [Deploy to Vercel](./guides/deployment/vercel.mdx) |
-| Self-host, or compare hosting strategies | [Deployment](./guides/deployment/overview.md) |
-| Authorize routes, sessions, and per-user access | [Authentication](./guides/auth-and-route-protection.md) |
-| Add a browser application | [Next.js](./guides/frontend/nextjs.mdx), [Nuxt](./guides/frontend/nuxt.mdx), or [SvelteKit](./guides/frontend/sveltekit.mdx) |
-| Build a custom web UI, or stream a session to a client | [Client SDK](./guides/client/overview.mdx), [Frontend](./guides/frontend/overview.mdx) |
-| Test the agent's behavior | [Evals](./evals/overview.mdx) |
-| Look up a CLI command or an exported type | [CLI](./reference/cli.md), [TypeScript API](./reference/typescript-api.md) |
+| To do this | Read this |
+| -------------------------------------------------------- | -------------------------------------------------------------------------------------- |
+| Create a project, or understand the file layout | [Getting Started](./getting-started.mdx) |
+| Set the model, reasoning, or other agent-wide config | [Agents](./agent-config.md) |
+| Change what the agent does and how it behaves | [Instructions](./instructions.mdx) |
+| Give the agent a typed capability it can call | [Tools](./tools/overview.mdx) |
+| Require approval, or ask the user something mid-turn | [Human in the Loop](./tools/human-in-the-loop.md) |
+| Call an external HTTP API or MCP server | [Connections](./connections/overview.mdx) |
+| Add a messaging surface (Slack, Discord, iMessage, …) | [Channels](./channels/overview.mdx) |
+| Expose your own HTTP route as a conversation surface | [Custom Channels](./channels/custom.mdx) |
+| Package a procedure the agent loads only when it applies | [Skills](./skills.mdx) |
+| Carry state across turns, or shape what the model sees | [State](./concepts/state.md), [Context Control](./concepts/context-control.md) |
+| Run commands or untrusted code in isolation | [Sandboxes](./sandbox/index.mdx) |
+| Delegate work to a specialist child agent | [Subagents](./subagents/index.mdx) |
+| Run work on a recurring schedule | [Schedules](./schedules.mdx) |
+| Install an existing integration instead of writing one | [Add Integrations](./install-integrations.mdx) |
+| Link a Vercel project and deploy to production | [Deploy to Vercel](./guides/deployment/vercel.mdx) |
+| Self-host, or compare hosting strategies | [Deployment](./guides/deployment/overview.md) |
+| Authorize routes, sessions, and per-user access | [Authentication](./guides/auth-and-route-protection.md) |
+| Build a web UI, or stream a session to a client | [Client SDK](./guides/client/overview.mdx), [Frontend](./guides/frontend/overview.mdx) |
+| Test the agent's behavior | [Evals](./evals/overview.mdx) |
+| Look up a CLI command or an exported type | [CLI](./reference/cli.md), [TypeScript API](./reference/typescript-api.md) |
## Legal and safeguards
@@ -58,25 +54,24 @@ Unless you configure stricter controls, eve agents may operate with permissive s
For a full picture rather than a single task, read in this order:
1. [Getting Started](./getting-started.mdx)
-2. [Project Structure](./concepts/project-structure.mdx)
-3. [Tutorial](./tutorial/first-agent.mdx)
-4. [Agents](./agent-config.md)
-5. [TypeScript API Reference](./reference/typescript-api.md)
-6. [Context Control](./concepts/context-control.md)
-7. [Skills](./skills.mdx)
-8. [Tools](./tools/overview.mdx)
-9. [Connections](./connections/overview.mdx)
-10. [Sandboxes](./sandbox.mdx)
-11. [Channels](./channels/overview.mdx)
-12. [Session Context](./guides/session-context.md)
-13. [Sessions and Streaming](./concepts/sessions-runs-and-streaming.md)
-14. [Client SDK](./guides/client/overview.mdx)
-15. [Subagents](./subagents/index.mdx)
-16. [Schedules](./schedules.mdx)
-17. [Evals](./evals/overview.mdx)
-18. [Authentication](./guides/auth-and-route-protection.md)
-19. [Deployment](./guides/deployment/overview.md)
-20. [CLI](./reference/cli.md)
+2. [Tutorial](./tutorial/first-agent.mdx)
+3. [Agents](./agent-config.md)
+4. [TypeScript API Reference](./reference/typescript-api.md)
+5. [Context Control](./concepts/context-control.md)
+6. [Skills](./skills.mdx)
+7. [Tools](./tools/overview.mdx)
+8. [Connections](./connections/overview.mdx)
+9. [Sandboxes](./sandbox/index.mdx)
+10. [Channels](./channels/overview.mdx)
+11. [Session Context](./guides/session-context.md)
+12. [Sessions and Streaming](./concepts/sessions-runs-and-streaming.md)
+13. [Client SDK](./guides/client/overview.mdx)
+14. [Subagents](./subagents/index.mdx)
+15. [Schedules](./schedules.mdx)
+16. [Evals](./evals/overview.mdx)
+17. [Authentication](./guides/auth-and-route-protection.md)
+18. [Deployment](./guides/deployment/overview.md)
+19. [CLI](./reference/cli.md)
## The public mental model
diff --git a/docs/channels/eve.mdx b/docs/channels/eve.mdx
index 95bf51698..d50105f66 100644
--- a/docs/channels/eve.mdx
+++ b/docs/channels/eve.mdx
@@ -34,7 +34,7 @@ The default eve channel inspects the agent, creates sessions, accepts callbacks
The session routes use only durable session IDs. Create a session explicitly, then put its returned ID in every follow-up, control, and stream path.
-`GET /eve/v1/health` is public and returns `{ ok: true, status: "ready", workflowId: string }`. `GET /eve/v1/info` uses the channel's auth policy and returns agent-info version 4. The TypeScript client validates both successful payloads: malformed health JSON throws `HealthResponseError`, malformed inspection JSON throws `AgentInfoResponseError`, and a non-success response from either route throws `ClientError`.
+`GET /eve/v1/health` is public and returns `{ ok: true, status: "ready", workflowId: string }`. `GET /eve/v1/info` uses the channel's auth policy and returns agent-info version 6. The TypeScript client validates both successful payloads: malformed health JSON throws `HealthResponseError`, malformed inspection JSON throws `AgentInfoResponseError`, and a non-success response from either route throws `ClientError`.
### Start and continue a session
diff --git a/docs/concepts/execution-model-and-durability.mdx b/docs/concepts/execution-model-and-durability.mdx
index 12cfa966d..869b9d134 100644
--- a/docs/concepts/execution-model-and-durability.mdx
+++ b/docs/concepts/execution-model-and-durability.mdx
@@ -56,7 +56,7 @@ that has not reached its next turn dispatch has not migrated yet.
Transparent rollback to the former execution model is unsupported. Retire and
restart affected sessions before rolling back.
-Nitro hosts the HTTP routes and workflow entrypoints. It does not supply the workflow state store or the sandbox runtime. Those are separate adapters: Workflow uses the active world implementation, and Sandbox uses the backend from `agent/sandbox` or `defaultBackend()`.
+Nitro hosts the HTTP routes and workflow entrypoints. It does not supply the workflow state store or the sandbox runtime. Those are separate adapters: Workflow uses the active world implementation, and Sandbox uses the backend from `agent/sandbox` or the default sandbox environment.
For advanced self-hosted deployments, the root `agent.ts` can select the installed Workflow world package to use with `experimental.workflow.world`:
diff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.md
index 9c35ee0da..b0e266449 100644
--- a/docs/concepts/sessions-runs-and-streaming.md
+++ b/docs/concepts/sessions-runs-and-streaming.md
@@ -301,7 +301,7 @@ Start with the [Client SDK](../guides/client/overview) guide. It covers basic us
## Inspect the agent over HTTP
-`GET /eve/v1/info` returns agent-info version 4, a JSON inspection snapshot of the effective compiled agent. It reports the selected config; active tools, instructions, memory slots, skills, channels, schedules, sandbox, connections, hooks, and instrumentation with explicit source ownership; dynamic resolvers separately from their session-specific output; local and remote agents in separate collections; prepared built-in effects; and shadowed or disabled source diagnostics. Memory tool wrappers include their selected memory-source dependency. Channel routes appear in the same effective order used by the HTTP host. Static instructions remain an ordered array whose entries expose `content` and `role`.
+`GET /eve/v1/info` returns agent-info version 6, a JSON inspection snapshot of the effective compiled agent. It reports the selected config; active tools, instructions, memory slots, skills, channels, schedules, sandbox, connections, hooks, and instrumentation with explicit source ownership; dynamic resolvers separately from their session-specific output; local and remote agents in separate collections; prepared built-in effects; and shadowed or disabled source diagnostics. Memory tool wrappers include their selected memory-source dependency. Channel routes appear in the same effective order used by the HTTP host. Static instructions remain an ordered array whose entries expose `content` and `role`. Sandbox inspection exposes the opaque `revisionHash` that identifies its compiler-discovered environment inputs.
The info route belongs to the selected `channels/eve.ts` source and uses its resolved auth policy. Without an authored replacement, eve selects the default channel source with Vercel OIDC, local development access, and the production placeholder. Replacing or disabling that source replaces or removes the info route too; no native fallback serves it.
diff --git a/docs/guides/client/overview.mdx b/docs/guides/client/overview.mdx
index fb50c75fa..1aba3568f 100644
--- a/docs/guides/client/overview.mdx
+++ b/docs/guides/client/overview.mdx
@@ -34,7 +34,7 @@ The client requires the successful response to match `{ ok: true, status: "ready
## Inspect an agent
-Use `info()` to inspect an agent. The client requires the complete agent-info version 4 response before returning it:
+Use `info()` to inspect an agent. The client requires the complete agent-info version 6 response before returning it:
```ts
const info = await client.info();
diff --git a/docs/guides/deployment/overview.md b/docs/guides/deployment/overview.md
index 2fa675a76..e9eb5f086 100644
--- a/docs/guides/deployment/overview.md
+++ b/docs/guides/deployment/overview.md
@@ -3,7 +3,7 @@ title: "Overview"
description: "Choose a deployment strategy and prepare an eve agent for production."
---
-Deploy eve to Vercel or run it as a Node service on your own infrastructure. Your deployment strategy determines the build output, workflow storage, sandbox backend, and routing. The agent’s filesystem-based configuration remains portable across these strategies.
+Deploy eve to Vercel or run it as a Node service on your own infrastructure. Your deployment strategy determines the build output, workflow storage, sandbox provider, and routing. The agent’s filesystem-based configuration remains portable across these strategies.
## Choose a deployment strategy
diff --git a/docs/guides/deployment/self-hosting.md b/docs/guides/deployment/self-hosting.md
index 71792125b..cb214a4fe 100644
--- a/docs/guides/deployment/self-hosting.md
+++ b/docs/guides/deployment/self-hosting.md
@@ -1,6 +1,6 @@
---
title: "Self-Host eve"
-description: "Run an eve agent as a Node service with your own workflow storage, sandbox backend, and routing."
+description: "Run an eve agent as a Node service with your own workflow storage, sandbox provider, and routing."
---
Self-host eve when you operate a Node service, container platform, or reverse proxy. You run eve’s Nitro server and choose the infrastructure that stores workflows and executes sandbox sessions.
@@ -46,11 +46,11 @@ The package must export a default factory or `createWorld()` function. Read cred
See [Workflow Worlds](https://workflow-sdk.dev/worlds) for the underlying Workflow software development kit (SDK) abstraction.
-## Select a sandbox backend
+## Select a sandbox provider
-`defaultBackend()` selects a local sandbox backend in availability order. You can instead select Docker, microsandbox, or a custom `SandboxBackend` adapter for your container, virtual machine, or isolation service.
+The default sandbox environment selects Docker, microsandbox, or just-bash according to local availability. You can select one explicitly or implement a custom provider with `defineSandboxProvider()` for your container, virtual machine, or isolation service.
-Don’t select `vercel()` unless the self-hosted process should create hosted Vercel sandboxes. See [Sandbox](../../sandbox) for backend configuration and selection order.
+Don’t select `VercelSandbox.environment()` unless the self-hosted process should create hosted Vercel sandboxes. See [Sandbox](../../sandbox) for provider configuration and selection order.
## Configure proxy routes
@@ -125,4 +125,4 @@ Use these guides to secure and observe the deployed agent:
- [Authentication](../auth-and-route-protection): configure the host’s route policy
- [Instrumentation](../../observability/instrumentation): export traces and diagnose runtime failures
-- [Sandbox](../../sandbox): select and secure a sandbox backend
+- [Sandbox](../../sandbox): select and secure a sandbox provider
diff --git a/docs/guides/deployment/vercel.mdx b/docs/guides/deployment/vercel.mdx
index 43f5bd547..bdd2316ec 100644
--- a/docs/guides/deployment/vercel.mdx
+++ b/docs/guides/deployment/vercel.mdx
@@ -27,26 +27,24 @@ A string model ID routes requests through the [Vercel AI Gateway](https://vercel
Add credentials for direct model providers, tools, and connections to the Vercel project environment. Add any signing keys or passwords required by your [route authentication policy](../auth-and-route-protection). Replace `placeholderAuth()` before a browser sends a production request.
-## Select the sandbox backend
+## Select the sandbox environment
-Leave the sandbox `backend` unset to use `defaultBackend()`. On Vercel, it selects Vercel Sandbox. You can also select the backend explicitly:
+The default environment selects Vercel Sandbox on Vercel. To select it explicitly:
```typescript
import { defineSandbox } from "eve/sandbox";
-import { vercel } from "eve/sandbox/vercel";
+import { VercelSandbox } from "eve/sandbox/vercel";
-export default defineSandbox({
- backend: vercel(),
-});
+export const environment = VercelSandbox.environment();
+export default defineSandbox(() => environment.open());
```
-See [Sandbox](../../sandbox) for resource limits, network policy, and lifecycle hooks.
+See [Sandbox](../../sandbox) for preparation, resource limits, network policy, and lifecycle.
<Callout type="info" title="Sandbox prewarming">
- During a Vercel build, eve automatically creates or reuses a sandbox template when your sandbox
- has `bootstrap()` or seed files. The build needs permission to create Vercel Sandbox templates,
- and a prewarm failure stops the deployment. See the [sandbox lifecycle](../../sandbox#lifecycle)
- for template and session setup.
+ During a Vercel build, eve creates or reuses a snapshot-backed template when an environment uses
+ `VercelSandbox.environment({prepare})` or has seed files. A prewarm failure stops the deployment.
+ See the [sandbox lifecycle](../../sandbox#lifecycle).
</Callout>
## Deploy the agent
@@ -137,7 +135,7 @@ Vercel uses the generated output to configure these services:
- **Web runtime**: serves health, session, stream, channel, callback, and schedule routes
- **Vercel Workflow**: persists and resumes durable runs, with optimistic replay preconditions enabled so stale event-log snapshots reload before they can commit
- **Vercel Cron**: invokes authored schedules
-- **Vercel Sandbox**: runs sandbox sessions selected by `defaultBackend()`
+- **Vercel Sandbox**: runs sandbox sessions selected by the default sandbox environment
## Verify the deployment
diff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.md
index bfc5b8d66..5d470b0ce 100644
--- a/docs/reference/typescript-api.md
+++ b/docs/reference/typescript-api.md
@@ -136,7 +136,7 @@ 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`, backends |
+| `eve/sandbox` | `defineSandbox`, provider environments, and sandbox session types |
| `eve/instrumentation` | `defineInstrumentation`, `disableInstrumentation`, `isChannel`, lifecycle provider types |
| `eve/instrumentation/otel` | `otel`, `otelIntegration`, `localTraces`, `agentRuns`, OpenTelemetry policy types |
| `eve/local-dev` | `getLocalDevCapability`, `LocalDevCapability` |
diff --git a/docs/sandbox.mdx b/docs/sandbox.mdx
deleted file mode 100644
index ffa6a3d9c..000000000
--- a/docs/sandbox.mdx
+++ /dev/null
@@ -1,342 +0,0 @@
----
-title: "Sandbox"
-description: "The agent's isolated bash environment, including built-in file tools, a seeded /workspace, backends, lifecycle, and network policy."
----
-
-The sandbox is the agent's isolated bash environment: a filesystem rooted at `/workspace` where it can run shell commands, execute scripts, and read or write files without ever touching your app runtime. Every eve agent has exactly one. The default `bash`, `read_file`, and `write_file` tools target it; you can also add the framework's `glob` and `grep` tools or access it from authored code.
-
-A working sandbox exists by default, with nothing to author. eve selects a framework-provided `defineSandbox({})` source for each local agent; `agent/sandbox.ts` or `agent/sandbox/sandbox.ts` replaces that source. Override it only to add setup, seed files, pick a backend, or lock down the network.
-
-The default sandbox is not a substitute for configuring network policy, credentials, retention, deletion, or other controls your application requires.
-
-## Using the sandbox
-
-The model already has shell and file access through the default tools:
-
-| Tool | Does |
-| -------------------------- | ----------------------------------- |
-| `bash` | run a shell command in the sandbox |
-| `read_file` / `write_file` | read/write files under `/workspace` |
-
-These tools run with `/workspace` as the working directory. The model-facing file tools accept both absolute paths and paths beginning with `$HOME/`; eve resolves the latter inside the sandbox before reading, writing, or searching. Any authored runtime function (a tool, a step, a model callback) can get a live sandbox handle with `ctx.getSandbox()`.
-
-```ts title="agent/tools/run_analysis.ts"
-import { defineTool } from "eve/tools";
-import { z } from "zod";
-
-export default defineTool({
- description: "Run a Python analysis script and return its output.",
- inputSchema: z.object({ script: z.string() }),
- async execute({ script }, ctx) {
- const sandbox = await ctx.getSandbox();
- await sandbox.writeTextFile({ path: "analysis/run.py", content: script });
- const result = await sandbox.run({ command: "python analysis/run.py" });
- if (result.exitCode !== 0) {
- throw new Error(
- `Analysis failed (exit ${result.exitCode}): ${result.stderr || result.stdout}`,
- );
- }
- return { stdout: result.stdout };
- },
-});
-```
-
-`ctx.getSandbox()` takes no arguments, is async, and only works inside authored runtime execution.
-
-`sandbox.run()` resolves with `{ exitCode, stdout, stderr }` when the process exits, including a nonzero exit. Check `exitCode` before reporting success or using generated files. Throw from a tool to report a failed operation to the model, and throw from `bootstrap` to prevent eve from caching an incomplete setup. The built-in `bash` tool returns all three fields so the model can interpret command results itself.
-
-`/workspace` is one namespace across every backend, so `/workspace/foo` points at the same file whether the backend is local or Vercel. When you need to interpolate a path into a generated command, `sandbox.resolvePath("repo/build.py")` anchors a relative path to its absolute `/workspace/repo/build.py` form.
-
-The handle does more than `run` and `writeTextFile`. In every method, relative paths resolve from `/workspace` and absolute paths pass through untouched:
-
-| Method | Does |
-| ---------------------------------------- | ----------------------------------------------------------------------------------------------- |
-| `run({ command })` | run one command, block until it exits, return `{ exitCode, stdout, stderr }` |
-| `spawn(options)` | launch a long-running process (server, watcher) and return a `SandboxProcess` handle |
-| `readTextFile` / `writeTextFile` | read/write a UTF-8 (or specified encoding) file; `readTextFile` supports 1-based line ranges |
-| `readBinaryFile` / `writeBinaryFile` | read/write raw bytes (images, archives, anything non-text) |
-| `readFile` / `writeFile` | stream a file in/out as bytes |
-| `removePath({ path, force, recursive })` | delete one file or directory; `force` ignores missing paths, `recursive` removes non-empty dirs |
-| `resolvePath(path)` | anchor a relative path to its absolute `/workspace/...` form |
-| `setNetworkPolicy(policy)` | change egress policy mid-turn (backend-dependent; see [Network policy](#network-policy)) |
-
-Since `run` blocks until the command exits, use `spawn` when the process should keep running while the agent does other work:
-
-```ts
-const sandbox = await ctx.getSandbox();
-const server = await sandbox.spawn({ command: "python -m http.server 8000" });
-// ...do other work against the server...
-await server.kill();
-```
-
-A `SandboxProcess` exposes `stdout`/`stderr` byte streams, `wait()` (resolves with the exit code), and `kill()` (idempotent).
-
-`sandbox.id` is a stable per-session identifier that persists across reconnects to the same logical session. Use it as the cache key for per-session state that must outlive individual step executions.
-
-The option types (`SandboxSpawnOptions`, `SandboxReadBinaryFileOptions`, `SandboxWriteBinaryFileOptions`, and so on) are named exports from `eve/sandbox`, alongside `SandboxProcess`.
-
-## Inbound attachments
-
-Before the first model step, eve writes byte-backed AI SDK `file` parts under
-`/workspace/attachments` and stores a sandbox reference in session history.
-For provider calls, images up to 3 MiB and PDFs up to 20 MiB are restored as
-bytes; other files become text references to their sandbox paths. Unresolved
-remote URLs and legacy AI SDK `image` parts are not staged.
-
-## Seeding `/workspace`
-
-Mount authored files into the sandbox at session start by placing them under `agent/sandbox/workspace/`. This requires the folder layout (`agent/sandbox/sandbox.ts`), not the top-level shorthand:
-
-```text
-agent/sandbox/
- sandbox.ts ← optional override (see below)
- workspace/
- schema.sql ← lands at /workspace/schema.sql
- scripts/run.sh ← lands at /workspace/scripts/run.sh
-```
-
-Every file under `workspace/` mirrors into the sandbox cwd with its structure intact, and eve lists the top-level entries to the model in the prompt automatically. `agent/skills/` files are materialized separately under `$HOME/.agents/skills/`, so `agent/sandbox/workspace/skills/...` is an ordinary workspace subtree when you choose to author one.
-
-## Overriding the sandbox
-
-To add setup, seed files, or pick a backend, author `defineSandbox`. There are two layouts:
-
-- `agent/sandbox.ts`: shorthand. Use it when you need only a definition, no seeded files.
-- `agent/sandbox/sandbox.ts`: folder layout. Use it when you also seed `agent/sandbox/workspace/**`. If both exist, the folder layout wins.
-
-```ts title="agent/sandbox/sandbox.ts"
-import { defineSandbox } from "eve/sandbox";
-import { vercel } from "eve/sandbox/vercel";
-
-export default defineSandbox({
- backend: vercel({ resources: { vcpus: 2 } }),
- revalidationKey: () => "repo-bootstrap-v1",
- async bootstrap({ use }) {
- const sandbox = await use();
- const result = await sandbox.run({ command: "sudo apt-get install -y jq" });
- if (result.exitCode !== 0) {
- throw new Error(
- `Sandbox setup failed (exit ${result.exitCode}): ${result.stderr || result.stdout}`,
- );
- }
- },
- async onSession({ use }) {
- await use({ networkPolicy: "deny-all" });
- },
-});
-```
-
-`defineSandbox` and `defaultBackend` live on `eve/sandbox`. Omit `backend` and the runtime falls back to `defaultBackend()` (see [Backends](#backends)).
-
-### Sharing a parent's sandbox
-
-Sandbox definitions use two distinct forms. Pass an object to give an agent or subagent an independent sandbox. Passing a callback to `defineSandbox` opts a declared subagent into sharing: return `parent.sandbox` to select the dispatching agent's exact live sandbox. A raw function export remains a zero-argument definition factory.
-
-```ts title="agent/subagents/reviewer/sandbox.ts"
-import { defineSandbox } from "eve/sandbox";
-
-export default defineSandbox(({ parent }) => {
- if (parent === null) throw new Error("reviewer must run as a child");
- return parent.sandbox;
-});
-```
-
-The parent and child then see the same files, processes, `/workspace`, and sandbox home. Nested children that also select `parent.sandbox` keep using the same owning sandbox rather than creating another one. The owning sandbox's `bootstrap` and `onSession` hooks remain authoritative; the child cannot add its own sandbox hooks or backend configuration.
-
-An inheriting child must not declare managed files under its own `sandbox/workspace/` or `skills/` directories, including dynamic skills. Eve rejects that configuration before execution. Remove the child resources when the shared workspace is sufficient, or give the child its own sandbox when it needs independently seeded files or skills.
-
-The built-in `agent` self-delegation path continues to share the root agent's sandbox automatically.
-
-## Backends
-
-The backend decides where the sandbox runs. eve ships four pinned factories from nested `eve/sandbox/*` imports plus an availability-aware default from `eve/sandbox`:
-
-| Backend | Runs the sandbox |
-| ------------------ | ---------------------------------------------------------------------------------------------- |
-| `vercel()` | on [Vercel Sandbox](https://vercel.com/docs/sandbox). |
-| `docker()` | locally in a Docker container, driven through the `docker` CLI. |
-| `microsandbox()` | locally in a lightweight [microsandbox](https://www.npmjs.com/package/microsandbox) VM. |
-| `justbash()` | locally in the pure-JS `just-bash` interpreter (no daemon or VM, but no real binaries either). |
-| `defaultBackend()` | picks the best available: Vercel Sandbox on hosted Vercel → Docker → microsandbox → just-bash. |
-
-Configuring a pinned factory uses that backend unconditionally. `docker()` always requires a reachable Docker daemon, and `vercel()` always creates hosted sandboxes (including from local dev, with Vercel credentials).
-
-With `backend` omitted, eve uses `defaultBackend()`, which resolves on first use in priority order:
-
-1. **Vercel Sandbox** when deploying on Vercel (`process.env.VERCEL` is set), since local container/VM runtimes can't run there.
-2. **Docker** when a daemon is reachable through a Docker-compatible `docker` CLI (Docker Desktop, OrbStack, Colima, Podman via its docker-compatible CLI; override the binary with `EVE_DOCKER_PATH`).
-3. **microsandbox** when the host supports it: macOS on Apple Silicon, or glibc Linux with KVM enabled.
-4. **just-bash** as the dependency-free fallback.
-
-By default, Docker and microsandbox pull `ghcr.io/vercel/eve` while Vercel Sandbox pulls `vcr.vercel.com/vercel/eve/base`. Each image tag matches the installed eve version without build metadata: a commit tarball version such as `0.56.0+git.4c27b3e37fa36d84` uses image tag `0.56.0`. Set `EVE_SANDBOX_IMAGE_TAG` to replace the version-derived tag for these default images. An explicit `image` passed to `docker()`, `microsandbox()`, or `vercel()` takes precedence. A snapshot `source` on `vercel()` takes precedence over its `image` because Vercel Sandbox treats them as mutually exclusive.
-
-On every backend, authored commands run as the non-root `vercel-sandbox` user through a non-interactive `bash -lc` login shell. `/workspace` and `$HOME` are writable, `$HOME/.local/bin` is on `PATH` for user-scoped executables, and system paths such as `/usr/local` stay root-owned. Use passwordless `sudo` when setup genuinely needs system-wide changes; `sudo` resets the environment, so pass through variables like `NPM_CONFIG_PREFIX` explicitly if a privileged step depends on them.
-
-`defaultBackend()` also accepts a keyed bag so each inner backend gets its own typed create options:
-
-```ts
-import { defaultBackend, defineSandbox } from "eve/sandbox";
-
-export default defineSandbox({
- backend: defaultBackend({
- vercel: { networkPolicy: "deny-all", resources: { vcpus: 4 } },
- docker: { networkPolicy: "deny-all" },
- microsandbox: { memoryMiB: 2048 },
- }),
-});
-```
-
-### Docker
-
-`docker()` drives the Docker CLI directly. By default, it uses the `ghcr.io/vercel/eve` image tag matching the installed eve version without build metadata. eve creates `/workspace` and verifies Bash during framework setup, before authored bootstrap code runs. Configure it through `docker({ image, env, pullPolicy, networkPolicy })`, and install authored runtime tools in sandbox bootstrap or provide them through a custom image. Templates are committed as local Docker images and reused across sessions when the sandbox source, seed files, `revalidationKey`, and Docker backend options still match. Sessions run as long-lived containers whose filesystems persist `/workspace` changes across turns for the same durable session. `eve dev` prunes stale template images in the background.
-
-### microsandbox
-
-`microsandbox()` runs each sandbox in a lightweight local VM with snapshot-backed templates, a `vercel-sandbox` user, and a firewall capable of domain-level network policies and credential brokering. It is the closest local match to hosted Vercel Sandbox. By default, it uses the `ghcr.io/vercel/eve` image tag matching the installed eve version without build metadata. During framework setup, before authored bootstrap code runs, eve verifies Bash and creates `/workspace` and the sandbox user. Install authored runtime tools in sandbox bootstrap or provide them through a custom image. Supported hosts are macOS on Apple Silicon, or Linux (glibc) with KVM. The `microsandbox` npm package and its VM runtime are not bundled with eve, so `eve dev` installs both automatically when missing (disable with `setup: { autoInstall: false }`); production processes fail with actionable install errors instead.
-
-### just-bash
-
-`justbash()` needs no daemon or VM, but commands run in a simulated bash with a virtual filesystem under `.eve/sandbox-cache/`, with no real binaries (`git`, `node`, package managers) and no network isolation. The `just-bash` package is an optional peer dependency, so `eve dev` installs it into your application automatically when missing (disable with `autoInstall: false`); production processes fail with an actionable install error instead.
-
-Pass `customCommands` to expose a `just-bash` `CustomCommand` inside each live sandbox session. The command participates in shell pipelines, redirections, and exit-code handling like a built-in command:
-
-```ts title="agent/sandbox.ts"
-import { defineSandbox } from "eve/sandbox";
-import { justbash } from "eve/sandbox/just-bash";
-import { decodeBytesToUtf8, defineCommand } from "just-bash";
-
-const uppercase = defineCommand("uppercase", async (_args, context) => ({
- stdout: decodeBytesToUtf8(context.stdin).toUpperCase(),
- stderr: "",
- exitCode: 0,
-}));
-
-export default defineSandbox({
- backend: justbash({ customCommands: [uppercase] }),
-});
-```
-
-Custom commands are registered on live and reopened sessions, not during template prewarming. They run trusted host application code and create an explicit bridge from the sandbox to that code. Adapters can use this extension point to expose application APIs such as a Capable App's CLI; the outer eve `bash` tool does not automatically provide per-command Capable approvals.
-
-You can also write your own backend. A `SandboxBackend` is an adapter object with a `name`, a `create`, and an optional `prewarm`. It can point at your own container runner, VM pool, internal sandbox service, or another isolation layer, as long as it returns the `SandboxSession` operations eve needs. Handles returned by `create` implement `delete()`, `stop()`, and `shutdown()`. See the `SandboxBackend*` types on `eve/sandbox`.
-
-## Lifecycle
-
-There are two hooks, scoped differently:
-
-- **`bootstrap({ use })`** is template-scoped and runs once when the template is built. Put reusable setup here that every later session inherits, such as cloning a baseline repo, installing dependencies, or seeding files. Call `use()` to get a `SandboxSession`. Only template filesystem state and supported backend metadata carry into later sessions; config like network policy does not. If external inputs affect what bootstrap produces, set `revalidationKey: () => string` so eve knows when to rebuild the template (authored sandbox source and seed contents are already tracked for you).
-- **`onSession({ use, ctx })`** is durable-session-scoped and runs once per session (and again if a sandbox definition change replaces the session's sandbox). Put per-session setup here, including network policy, resources, timeout, per-user credentials, and one-time markers. `ctx` contains only the active session metadata, so it can identify the current principal without exposing runtime lifecycle operations while the sandbox is initializing. Call `use(opts?)` to get a `SandboxSession`; `opts` flow to the backend's update path after create.
-
-If you require a network policy or other configuration for every session, configure it on the backend factory or in `onSession`; do not rely on bootstrap-only configuration.
-
-```ts
-import { defineSandbox } from "eve/sandbox";
-import { vercel } from "eve/sandbox/vercel";
-
-export default defineSandbox({
- backend: vercel(),
- async onSession({ use, ctx }) {
- const sandbox = await use({ networkPolicy: "deny-all" });
- const user = ctx.session.auth.current;
- if (user === null) return;
- await sandbox.writeTextFile({ path: "SESSION_USER.txt", content: `${user.principalId}\n` });
- },
-});
-```
-
-Sessions are persistent, and how the underlying runtime idles out depends on the backend. On the Vercel backend, the VM times out after a period of inactivity (default 30 minutes); eve preserves the filesystem and resumes the sandbox on the next message while the persisted sandbox remains available. The Docker backend keeps a long-lived container per durable session and persists `/workspace` across turns without that timeout, and the just-bash backend stores its virtual filesystem under `.eve/sandbox-cache/`.
-
-Authored runtime callbacks can stop compute sooner through the handle returned
-by `ctx.getSandbox()`:
-
-```ts
-const sandbox = await ctx.getSandbox();
-await sandbox.stop();
-```
-
-Every built-in backend uses its native lifecycle operation without deleting the
-durable session. Treat the stop as the end of sandbox work in the current
-callback. On the next callback, `ctx.getSandbox()` reopens the same Docker
-container, microsandbox VM or snapshot, or just-bash filesystem and environment.
-Vercel can also automatically resume the same handle on its next I/O operation,
-just as it would after an inactivity timeout. No separate reconnect step or
-stop-specific state is needed. Lifecycle `use()` calls return the I/O-only
-`SandboxSession` because bootstrap and session initialization do not own runtime
-teardown.
-
-### Delete a sandbox
-
-Permanently delete the current session sandbox from an authored runtime callback:
-
-```ts
-const sandbox = await ctx.getSandbox();
-await sandbox.delete();
-```
-
-eve stops compute first, deletes the physical sandbox and its disposable backend state, and clears the saved reconnect state. It preserves reusable template state that contains `bootstrap` and seeded workspace files.
-
-The durable eve session remains active. The next call to `ctx.getSandbox()` provisions a fresh workspace from the current sandbox definition and runs `onSession` again. Files and other workspace changes from the deleted sandbox are not restored.
-
-Backend behavior differs:
-
-- **Vercel Sandbox**: stops the persistent sandbox, deletes its record, and asks Vercel to delete snapshots that no other sandbox uses. Snapshot cleanup runs asynchronously.
-- **microsandbox**: stops and removes the session VM and its persisted state snapshot
-- **Docker and just-bash**: stop compute and discard their session runtime state
-
-Only the session that owns a shared sandbox can delete it. Deleting the owner's sandbox affects every parent or child currently using it. If the backend rejects deletion, eve preserves the current reconnect state so you can retry.
-
-Custom backend handles implement the same boundary in `delete()`: remove the session runtime and disposable persisted state without deleting reusable templates.
-
-Session sandboxes are keyed per durable session, not per deployment, so redeploying your app does not by itself discard them. A definition change to the authored sandbox source, workspace seed content, or `revalidationKey` replaces the sandbox on the next turn and runs `onSession` again.
-
-For sandboxes with `bootstrap`, unrelated agent changes preserve the template and session sandbox keys even when there are no skill or workspace seed files. You do not need to add a seed file or `revalidationKey` solely to preserve reuse across those changes.
-
-Reattachment still depends on the backend retaining its physical sandbox state. If a persisted Vercel sandbox is missing or its saved filesystem snapshot is no longer available, eve deletes the unusable record and creates a replacement from the current template when one is configured. Files and other changes made after the original sandbox was created are not restored automatically. Because the durable session still has the same sandbox key, `onSession` does not run again for this replacement. Persist important artifacts outside the sandbox, and do not rely on `onSession` as the only place that applies security-critical configuration.
-
-When the eve server stops, no sandbox compute outlives it. `eve dev` stops the sandboxes it started when the dev server closes, and a self-hosted production server stops every open sandbox on shutdown (`SIGTERM`/`SIGINT`). Session state persists across the stop — the next server start reattaches each durable session from its stopped container, VM, or snapshot. Custom `SandboxBackend` adapters implement `stop()` for authored runtime calls and `shutdown()` for server teardown. Both stop the underlying compute while keeping the session reattachable from persisted state where the backend supports it; authored `stop()` failures reject, while process-wide shutdown collects and logs failures without blocking teardown.
-
-## Network policy
-
-Egress rules go on the backend factory or in `onSession`'s `use()`. There are three forms:
-
-```ts
-networkPolicy: "allow-all"; // default
-networkPolicy: "deny-all"; // block all egress, including DNS
-
-networkPolicy: {
- allow: ["ai-gateway.vercel.sh", "*.github.com"],
- subnets: { deny: ["10.0.0.0/8"] },
-};
-```
-
-Default egress is `allow-all`. For non-public, sensitive, regulated, or production workloads, configure `deny-all` or an explicit allow-list before running untrusted tools or handling sensitive data.
-
-Set it on the factory (`vercel({ networkPolicy: "deny-all" })`) and it applies before authored `bootstrap` code runs; framework-owned base setup may briefly keep egress open to install required packages. Set it in `onSession`'s `use()` to override per-session. A provider-loss replacement with the same sandbox key does not rerun `onSession`, so enforce the security-critical baseline on the factory. If `bootstrap` needs network access, give the factory only the destinations it needs, then narrow the policy further in `onSession`. To change the policy mid-turn, call `sandbox.setNetworkPolicy(...)` on the live handle.
-
-Domain-level allow-lists and credential brokering are supported by `vercel()` and `microsandbox()`. The Docker backend honors only `"allow-all"` and `"deny-all"` (at creation and via `setNetworkPolicy`); the just-bash backend rejects `setNetworkPolicy` entirely.
-
-## Credential brokering
-
-Secrets never enter the sandbox. Instead, the network policy's per-domain `transform` injects credentials at the firewall, so a header can authenticate egress to a host while the secret stays out of the sandbox process entirely:
-
-```ts
-async onSession({ use }) {
- await use({
- networkPolicy: {
- allow: {
- "github.com": [{ transform: [{ headers: { authorization: "Basic your_base64_credentials_here" } }] }],
- "*": [],
- },
- },
- });
-}
-```
-
-The `"*": []` catch-all keeps general egress open while the `transform` applies only to `github.com`. For mid-turn brokering, call `setNetworkPolicy` with the same shape. The [Vercel Sandbox docs](https://vercel.com/docs/sandbox) cover the brokering mechanism itself.
-
-## What to read next
-
-- [Subagents](./subagents): each subagent gets its own sandbox, independent of its parent.
-- [Tools](./tools): authored tools run in the app runtime (full `process.env`); only sandbox tools run in the sandbox.
-- [Security model](./concepts/security-model): the app-runtime/sandbox trust boundary in full.
-- [Vercel Sandbox](https://vercel.com/docs/sandbox): platform docs, including credential brokering and persistence limits.
diff --git a/docs/sandbox/default.mdx b/docs/sandbox/default.mdx
new file mode 100644
index 000000000..d9e923c2d
--- /dev/null
+++ b/docs/sandbox/default.mdx
@@ -0,0 +1,17 @@
+---
+title: "Default Sandbox"
+description: "Let eve select the sandbox provider for the current environment."
+---
+
+`DefaultSandbox.environment()` preserves eve's standard behavior without exposing provider-specific live creation options.
+
+```ts
+import { DefaultSandbox, defineSandbox } from "eve/sandbox";
+
+export const environment = DefaultSandbox.environment();
+export default defineSandbox(() => environment.open());
+```
+
+On Vercel, it selects [Vercel Sandbox](/docs/sandbox/vercel). Elsewhere, it tries [Docker](/docs/sandbox/docker), [microsandbox](/docs/sandbox/microsandbox), and [just-bash](/docs/sandbox/just-bash), in that order, according to host support.
+
+Use a provider directly when you need its image, VM, network, compute, or mount options.
diff --git a/docs/sandbox/docker.mdx b/docs/sandbox/docker.mdx
new file mode 100644
index 000000000..e1d8fe732
--- /dev/null
+++ b/docs/sandbox/docker.mdx
@@ -0,0 +1,29 @@
+---
+title: "Docker Sandbox"
+description: "Create local persistent containers from an image or Dockerfile."
+---
+
+Docker environments can use eve's default image, an existing OCI image, or `agent/sandbox/Dockerfile`.
+
+```ts
+import { defineSandbox } from "eve/sandbox";
+import { DockerSandbox } from "eve/sandbox/docker";
+
+export const environment = DockerSandbox.image("ghcr.io/acme/agent@sha256:...");
+
+export default defineSandbox(() => environment.open({ networkPolicy: "deny-all" }));
+```
+
+Use `DockerSandbox.environment()` for the default image or `DockerSandbox.dockerfile()` for the colocated Dockerfile convention.
+
+## Environment options
+
+Image, pull policy, environment variables, and `prepare` belong to the reusable environment. During preparation, eve starts a temporary container, hydrates managed resources, runs authored preparation, and commits the result as the recorded template image.
+
+## Live container options
+
+Pass `networkPolicy` to `open()`. Docker supports only `"allow-all"` and `"deny-all"`. The policy applies to the live container, not the prepared image.
+
+A session-owned container keeps writable `/workspace` state in its container filesystem. A stopped container restarts with that state.
+
+See the [sandbox overview](/docs/sandbox) for managed workspace, skills, parent inheritance, and custom providers.
diff --git a/docs/sandbox/index.mdx b/docs/sandbox/index.mdx
new file mode 100644
index 000000000..0fd2fd5dd
--- /dev/null
+++ b/docs/sandbox/index.mdx
@@ -0,0 +1,216 @@
+---
+title: "Sandbox"
+description: "Configure the isolated filesystem and command environment used by an eve agent."
+---
+
+Every eve agent has one sandbox rooted at `/workspace`. The built-in `bash`, `read_file`, and `write_file` tools use it. Without an authored sandbox file, eve selects the best available environment automatically.
+
+## Use the sandbox
+
+Authored tools and callbacks access the live sandbox with `ctx.getSandbox()`:
+
+```ts title="agent/tools/run_analysis.ts"
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+
+export default defineTool({
+ description: "Run a Python script.",
+ inputSchema: z.object({ script: z.string() }),
+ async execute({ script }, ctx) {
+ const sandbox = await ctx.getSandbox();
+ await sandbox.writeTextFile({ path: "analysis.py", content: script });
+ const result = await sandbox.run({ command: "python analysis.py" });
+ if (result.exitCode !== 0) throw new Error(result.stderr);
+ return result.stdout;
+ },
+});
+```
+
+Relative paths resolve under `/workspace`. `run()` returns `{ exitCode, stdout, stderr }`; a nonzero exit code does not throw automatically. Use `spawn()` for a long-running process.
+
+## Define an environment
+
+A sandbox module exports an environment and returns a sandbox from `defineSandbox()`:
+
+```ts title="agent/sandbox.ts"
+import { DefaultSandbox, defineSandbox } from "eve/sandbox";
+
+export const environment = DefaultSandbox.environment();
+export default defineSandbox(() => environment.open());
+```
+
+`environment.open()` starts the persistent sandbox owned by the current eve session. The `defineSandbox()` selector runs until initialization succeeds, then eve checkpoints the selected provider and its state. Later workflow steps and process restarts call the provider's `resume()` directly without rerunning the selector or `environment.open()`.
+
+Pass options for the live sandbox to `open()`, then configure the returned sandbox before returning it. This initialization runs once for a successfully started durable sandbox:
+
+```ts
+import { defineSandbox } from "eve/sandbox";
+import { VercelSandbox } from "eve/sandbox/vercel";
+
+export const environment = VercelSandbox.environment();
+
+export default defineSandbox(async ({ session }) => {
+ const sandbox = await environment.open({ networkPolicy: "deny-all" });
+ await sandbox.writeTextFile({ path: ".eve/session", content: session.id });
+ return sandbox;
+});
+```
+
+The environment export is required because `eve build` prepares immutable environment inputs before a session exists.
+
+### Prepare a reusable environment
+
+Use the environment's `prepare` option for setup every new sandbox inherits:
+
+```ts
+import { defineSandbox } from "eve/sandbox";
+import { VercelSandbox } from "eve/sandbox/vercel";
+
+export const environment = VercelSandbox.environment({
+ prepare: async (sandbox) => {
+ const result = await sandbox.run({
+ command: "sudo apt-get update && sudo apt-get install -y jq",
+ });
+ if (result.exitCode !== 0) throw new Error(result.stderr);
+ },
+});
+
+export default defineSandbox(() => environment.open());
+```
+
+eve runs `prepare` while creating a reusable provider artifact, not once for each live session sandbox. Vercel captures a snapshot; Docker captures an image; microsandbox captures a VM snapshot; and just-bash captures a filesystem template.
+
+At runtime, eve passes the recorded artifact directly to the provider when it creates a live sandbox. Runtime does not rebuild or repair a missing artifact. A missing image, snapshot, or template fails with rebuild or redeploy guidance.
+
+### 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.
+
+### Share a parent sandbox
+
+A declared subagent can use its dispatching parent's sandbox explicitly:
+
+```ts title="agent/subagents/reviewer/sandbox.ts"
+import { defineParentSandbox } from "eve/sandbox";
+
+export default defineParentSandbox();
+```
+
+An inheriting subagent cannot declare its own managed workspace or skill files.
+
+## Managed workspace and skills
+
+Use the sandbox directory for authored workspace seeds:
+
+```text
+agent/sandbox/
+ sandbox.ts
+ workspace/
+ schema.sql
+```
+
+Files under `agent/sandbox/workspace/` seed writable `/workspace`. eve copies the seed when it prepares a new environment generation. Existing live sandbox state is not overwritten by later seed changes.
+
+Agent skills are compiled into a separate resource tree and exposed at `$HOME/.agents/skills`. These are stable paths across every built-in provider, so instructions and tools can refer to `/workspace` and `$HOME/.agents/skills`. Do not refer to a concrete home directory or `/eve/resources`, which is provider-internal staging.
+
+Providers receive both trees with explicit metadata:
+
+```ts
+interface SandboxProviderResources {
+ source:
+ | { kind: "none" }
+ | { kind: "inline"; key: string }
+ | { kind: "materialized"; key: string; path: string }
+ | { kind: "reference"; key: string };
+ workspace?: SandboxProviderResourceTree;
+ skills?: SandboxProviderResourceTree;
+}
+
+interface SandboxProviderResourceTree {
+ key: string;
+ files: ResourceFile[];
+ mountPath: string;
+ targetPath: string;
+}
+```
+
+Docker and microsandbox mount the compiled trees read-only under `/eve/resources`, copy workspace seeds into writable `/workspace`, and expose skills read-only where possible. Vercel's snapshot environment writes workspace and skill contents before capturing its snapshot. Custom providers decide whether to upload, mount, or write each tree, but must expose the final target paths before authored preparation runs.
+
+## 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 },
+ { remoteId: string; version: 1 },
+ SandboxSession
+>({
+ name: "acme",
+ environment(options) {
+ const client = createAcmeClient(options);
+
+ return {
+ 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 remote = await client.open({
+ identity: sessionIdentity(ctx.session.id, artifact, liveOptions),
+ networkPolicy: liveOptions?.networkPolicy,
+ templateId: artifact.templateId,
+ });
+ return {
+ handle: createHandle(remote),
+ state: { remoteId: remote.id, version: 1 },
+ };
+ },
+
+ async resume(_ctx, artifact, state) {
+ const remote = await client.resume({ id: state.remoteId, templateId: artifact.templateId });
+ return createHandle(remote);
+ },
+ };
+ },
+});
+```
+
+`prepare()` returns the complete JSON-serializable artifact. Core calls `start()` once for a new durable sandbox session and persists its minimal JSON-compatible state. Process restarts call `resume()` with only the current context, that state, and the target deployment's exact artifact. Provider handles implement `onSessionStop()`, `onRuntimeShutdown()`, and `onSessionDelete()`.
+
+Open options belong to `start()` and are not serialized or passed to `resume()`. A provider must put any immutable option-derived data needed for reconnection in its session state. With the current immutable-state contract, `resume()` reconnects existing native state and fails if it is gone rather than recreating callback side effects. A custom provider may define start-only callback fields, but built-in providers initialize the sandbox in `defineSandbox()` after `open()`.
+
+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.
+
+## Providers
+
+| Provider | Use it for |
+| ------------------------------------------ | --------------------------------------------------------------------------------------- |
+| [Default](/docs/sandbox/default) | Automatic provider selection with eve's standard behavior. |
+| [Vercel](/docs/sandbox/vercel) | Snapshot-backed persistent Vercel Sandboxes, domain network policies, and Drive mounts. |
+| [Docker](/docs/sandbox/docker) | Local containers from the default image, an existing OCI image, or a Dockerfile. |
+| [microsandbox](/docs/sandbox/microsandbox) | Local lightweight VMs from an OCI image or Dockerfile. |
+| [just-bash](/docs/sandbox/just-bash) | A pure-JavaScript shell and virtual filesystem without native process isolation. |
+
+## Lifecycle
+
+Session-owned sandboxes persist across turns and deployments while their provider state remains available. `sandbox.stop()` stops compute without deleting persisted state; a later access resumes that state directly. `sandbox.delete()` clears provider state, so the next `ctx.getSandbox()` reruns the selector and starts a fresh sandbox from the current environment.
+
+Changing sandbox source, preparation code, Dockerfile content, environment options, workspace resources, or skills produces a new environment generation. Existing durable sessions retain their recorded sandbox state; new sessions use the current generation.
+
+## What to read next
+
+- [Subagents](/docs/subagents) explains delegation and sandbox ownership.
+- [Security model](/docs/concepts/security-model) describes the app-runtime and sandbox trust boundary.
+- [Vercel Sandbox](https://vercel.com/docs/sandbox) documents hosted sandbox behavior.
diff --git a/docs/sandbox/just-bash.mdx b/docs/sandbox/just-bash.mdx
new file mode 100644
index 000000000..63210443e
--- /dev/null
+++ b/docs/sandbox/just-bash.mdx
@@ -0,0 +1,18 @@
+---
+title: "just-bash Sandbox"
+description: "Use a pure-JavaScript shell and virtual filesystem."
+---
+
+`JustBashSandbox.environment()` provides a shell and filesystem without starting a container or VM.
+
+```ts
+import { defineSandbox } from "eve/sandbox";
+import { JustBashSandbox } from "eve/sandbox/just-bash";
+
+export const environment = JustBashSandbox.environment();
+export default defineSandbox(() => environment.open());
+```
+
+just-bash can prepare and persist its virtual filesystem. It cannot use OCI images or Dockerfiles, does not run native processes, and provides no network isolation. The session does not expose `setNetworkPolicy()`.
+
+See the [sandbox overview](/docs/sandbox) for managed workspace, skills, parent inheritance, and custom providers.
diff --git a/docs/sandbox/meta.json b/docs/sandbox/meta.json
new file mode 100644
index 000000000..e82cb0bb0
--- /dev/null
+++ b/docs/sandbox/meta.json
@@ -0,0 +1,5 @@
+{
+ "title": "Sandbox",
+ "defaultOpen": false,
+ "pages": ["index", "default", "vercel", "docker", "microsandbox", "just-bash"]
+}
diff --git a/docs/sandbox/microsandbox.mdx b/docs/sandbox/microsandbox.mdx
new file mode 100644
index 000000000..4dfbea6f0
--- /dev/null
+++ b/docs/sandbox/microsandbox.mdx
@@ -0,0 +1,31 @@
+---
+title: "microsandbox"
+description: "Create local lightweight VMs from an OCI image or Dockerfile."
+---
+
+microsandbox environments use eve's default image, an existing OCI image, or `agent/sandbox/Dockerfile`.
+
+```ts
+import { defineSandbox } from "eve/sandbox";
+import { MicrosandboxSandbox } from "eve/sandbox/microsandbox";
+
+export const environment = MicrosandboxSandbox.dockerfile({
+ setup: { autoInstall: false },
+});
+
+export default defineSandbox(() => environment.open({ networkPolicy: "deny-all" }));
+```
+
+Supported hosts are macOS on Apple Silicon and Linux with glibc and KVM.
+
+## Environment options
+
+Image, CPU, memory, pull policy, environment variables, VM setup, and `prepare` belong to the reusable environment. `eve build` builds a Dockerfile image when present, prepares a VM, and records its snapshot and image references.
+
+## Live VM options
+
+Pass `networkPolicy` to `open()`. The policy applies to the live VM, not the prepared snapshot. microsandbox accepts domain policies and credential transforms.
+
+Session creation uses the recorded snapshot and image directly. Writable VM state persists through the provider's session snapshot lifecycle.
+
+See the [sandbox overview](/docs/sandbox) for managed workspace, skills, parent inheritance, and custom providers.
diff --git a/docs/sandbox/vercel.mdx b/docs/sandbox/vercel.mdx
new file mode 100644
index 000000000..93d9a0904
--- /dev/null
+++ b/docs/sandbox/vercel.mdx
@@ -0,0 +1,106 @@
+---
+title: "Vercel Sandbox"
+description: "Create snapshot-backed persistent sandboxes on Vercel."
+---
+
+`VercelSandbox.environment()` prepares a reusable Vercel Sandbox snapshot and creates persistent session sandboxes from its recorded snapshot ID.
+
+```ts
+import { defineSandbox } from "eve/sandbox";
+import { VercelSandbox } from "eve/sandbox/vercel";
+
+export const environment = VercelSandbox.environment({
+ prepare: async (sandbox) => {
+ await sandbox.run({ command: "pnpm install --frozen-lockfile" });
+ },
+});
+
+export default defineSandbox(() =>
+ environment.open({
+ networkPolicy: {
+ allow: {
+ "api.github.com": [],
+ },
+ },
+ resources: { vcpus: 4 },
+ }),
+);
+```
+
+## Snapshot preparation
+
+eve creates a temporary persistent Vercel Sandbox during build, installs the base runtime, writes managed workspace and skill files, runs the authored `prepare` callback, and captures a snapshot. The build artifact records the snapshot ID.
+
+When a live session sandbox does not exist, eve creates it directly from that snapshot ID. Runtime does not need to look up the temporary template Sandbox.
+
+## Initialize after open
+
+Initialize session-specific state after `open()` and before returning the sandbox. This selector writes a configuration file into the persistent `/workspace` filesystem:
+
+```ts
+import { defineSandbox } from "eve/sandbox";
+import { VercelSandbox } from "eve/sandbox/vercel";
+
+export const environment = VercelSandbox.environment();
+
+export default defineSandbox(async ({ session }) => {
+ const sandbox = await environment.open();
+ await sandbox.writeTextFile({
+ content: JSON.stringify({ sessionId: session.id, workspace: "analysis" }),
+ path: ".eve/session.json",
+ });
+ return sandbox;
+});
+```
+
+The selector runs until initialization succeeds. Later workflow steps and process restarts resume the same provider state without rerunning the selector, so the file is not rewritten at each boundary.
+
+You can also configure the live sandbox and run setup commands before returning it:
+
+```ts
+export default defineSandbox(async () => {
+ const sandbox = await environment.open();
+ await sandbox.setNetworkPolicy("deny-all");
+ const result = await sandbox.run({ command: "mkdir -p .cache/app" });
+ if (result.exitCode !== 0) throw new Error(result.stderr);
+ return sandbox;
+});
+```
+
+Use the environment's `prepare` callback for immutable setup that every new session should inherit. Use post-open initialization for state that belongs only to one durable session.
+
+## Network policy
+
+Pass the initial policy to `open()`. It applies to the new live Vercel Sandbox, not to the environment definition:
+
+```ts
+return environment.open({
+ networkPolicy: {
+ allow: {
+ "api.example.com": [
+ {
+ transform: [{ headers: { authorization: `Bearer ${token}` } }],
+ },
+ ],
+ },
+ },
+});
+```
+
+Credential transforms inject headers at the network boundary so the secret does not enter the sandbox process. The dedicated Vercel environment returns a session where `setNetworkPolicy()` is required, so you can update the policy directly after `open()` without a capability check:
+
+```ts
+const sandbox = await environment.open();
+await sandbox.setNetworkPolicy("deny-all");
+return sandbox;
+```
+
+## Live sandbox options
+
+`open()` also accepts Vercel compute resources, timeout, and Drive mounts. Configure project credentials and custom fetch behavior on the environment, not in `open()`, because resume does not reconstruct start-only options.
+
+Initialize the returned sandbox directly in `defineSandbox()`. If initialization fails, eve deletes the newly started sandbox and retries the selector on the next access. After initialization succeeds, the provider persists only immutable JSON-compatible state. If the named Vercel Sandbox later disappears, resume fails rather than recreating initialization side effects.
+
+eve owns the persistent sandbox identity and prepared snapshot source.
+
+See the [sandbox overview](/docs/sandbox) for managed workspace, skills, parent inheritance, and custom providers.
diff --git a/docs/subagents/index.mdx b/docs/subagents/index.mdx
index 390238f6a..19c0935e2 100644
--- a/docs/subagents/index.mdx
+++ b/docs/subagents/index.mdx
@@ -216,7 +216,7 @@ A declared subagent inherits nothing from the root's authored slots. Discovery t
| Tools | Inherited except root-only | Own `tools/` |
| Connections | Inherited | Own `connections/` |
| Skills | Inherited | Own `skills/` |
-| Sandbox | Shared with parent | Own `sandbox/`, else framework default |
+| Sandbox | Reuses the parent sandbox | Own `sandbox/`, else framework default |
| Hooks | Inherited | Own `hooks/` |
| Extensions | Inherited contributions | Own `extensions/` |
| State | Fresh | Fresh |
@@ -225,7 +225,7 @@ A declared subagent inherits nothing from the root's authored slots. Discovery t
For a declared subagent this means authoring or mounting anything the child needs. When two subagents need the same procedure, package the skill in a [workspace extension](./extensions#use-an-extension-in-a-workspace) and mount that extension in each subagent. Share typed helpers through `lib/`. The sandbox does not inherit from the parent; eve selects the default sandbox source unless the subagent authors `subagents/<id>/sandbox.ts` or seeds files via `subagents/<id>/sandbox/workspace/`.
-The root built-in `agent` tool is the exception. Its children share the root's sandbox and tools because they are copies of the same agent working on the same files.
+The root built-in `agent` tool is the exception. Its children reuse the root's sandbox and tools because they are copies of the same agent working on the same files.
`defineState` is never shared, for either kind. Each child starts with fresh durable state.
diff --git a/docs/tutorial/run-analysis.mdx b/docs/tutorial/run-analysis.mdx
index 90131f26c..8fc3b5543 100644
--- a/docs/tutorial/run-analysis.mdx
+++ b/docs/tutorial/run-analysis.mdx
@@ -34,11 +34,10 @@ Python needs a sandbox that runs real binaries. For local development, start a D
The default eve images for Docker, microsandbox, and Vercel Sandbox include Python, but not matplotlib. Add this definition alongside `workspace/` to install matplotlib in a virtual environment. It uses the same environment for installation and chart execution, without changing the system Python:
```ts title="agent/sandbox/sandbox.ts"
-import { defineSandbox } from "eve/sandbox";
+import { DefaultSandbox, defineSandbox } from "eve/sandbox";
-export default defineSandbox({
- async bootstrap({ use }) {
- const sandbox = await use();
+export const environment = DefaultSandbox.environment({
+ prepare: async (sandbox) => {
const commands = [
"sudo apt-get update && sudo apt-get install -y python3 python3-venv",
"python3 -m venv /workspace/.venv",
@@ -55,9 +54,11 @@ export default defineSandbox({
}
},
});
+
+export default defineSandbox(() => environment.open());
```
-Bootstrap runs when eve builds the sandbox template, and sessions inherit the installed environment. The first build needs network access to Ubuntu package repositories and PyPI. Keep the default network policy while following this example; a custom `deny-all` or allow-list policy must permit these downloads during bootstrap. The same definition uses Vercel Sandbox after deployment to Vercel.
+Preparation runs when eve builds the sandbox template, and sessions inherit the installed environment. The first build needs network access to Ubuntu package repositories and PyPI. Keep the default network policy while following this example; a custom `deny-all` or allow-list policy must permit these downloads during preparation. The same definition uses Vercel Sandbox after deployment to Vercel.
Restart `npm run dev` after adding the definition. Before asking for a chart, send this message in the TUI:
diff --git a/e2e/README.md b/e2e/README.md
index 0c7831693..3caa4e9da 100644
--- a/e2e/README.md
+++ b/e2e/README.md
@@ -166,7 +166,9 @@ matrices from the registry:
- `model_matrix` — fixture × model legs for `e2e-local.yml`. The first
registry model is the default that every fixture runs on; the rest run only
on fixtures with `"e2e": { "modelMatrix": "full" }` in package.json.
- A fixture can add a narrowly scoped leg with `e2e.additionalModels` entries
+ A fixture can set `e2e.localOnly: true` when it requires local-runner hardware
+ or daemons and must not enter world deployment matrices. A fixture can add a
+ narrowly scoped leg with `e2e.additionalModels` entries
shaped as `{ "name": "short-check-name", "id": "provider/model" }`.
`e2e.optionalModels` can name selected model legs that should still run and
report failures without blocking the aggregate check.
diff --git a/e2e/fixtures/agent-microsandbox-dockerfile/.gitignore b/e2e/fixtures/agent-microsandbox-dockerfile/.gitignore
new file mode 100644
index 000000000..0ee2c2487
--- /dev/null
+++ b/e2e/fixtures/agent-microsandbox-dockerfile/.gitignore
@@ -0,0 +1,2 @@
+.eve/
+.output/
diff --git a/e2e/fixtures/agent-microsandbox-dockerfile/agent/agent.ts b/e2e/fixtures/agent-microsandbox-dockerfile/agent/agent.ts
new file mode 100644
index 000000000..35edd7163
--- /dev/null
+++ b/e2e/fixtures/agent-microsandbox-dockerfile/agent/agent.ts
@@ -0,0 +1,8 @@
+import { e2eAgentConfig } from "@eve-e2e/config";
+import { defineAgent } from "eve";
+
+import { respond } from "./mock-responder.js";
+
+export default defineAgent({
+ ...e2eAgentConfig({ mock: respond }),
+});
diff --git a/e2e/fixtures/agent-microsandbox-dockerfile/agent/instructions.md b/e2e/fixtures/agent-microsandbox-dockerfile/agent/instructions.md
new file mode 100644
index 000000000..c40d11a9f
--- /dev/null
+++ b/e2e/fixtures/agent-microsandbox-dockerfile/agent/instructions.md
@@ -0,0 +1 @@
+Follow explicit bash directives and return the requested command output.
diff --git a/e2e/fixtures/agent-microsandbox-dockerfile/agent/mock-responder.ts b/e2e/fixtures/agent-microsandbox-dockerfile/agent/mock-responder.ts
new file mode 100644
index 000000000..a3b5d2e52
--- /dev/null
+++ b/e2e/fixtures/agent-microsandbox-dockerfile/agent/mock-responder.ts
@@ -0,0 +1,18 @@
+import type { MockModelRequest, MockModelResponse } from "eve/evals";
+
+const BASH_DIRECTIVE = /run the bash command `([^`]+)`/iu;
+
+export function respond(request: MockModelRequest): MockModelResponse | string {
+ const message = request.lastUserMessage ?? "";
+ const command = BASH_DIRECTIVE.exec(message)?.[1];
+ if (command === undefined) return `Mock reply: ${message}`;
+
+ const result = [...request.toolResults].reverse().find(({ name }) => name === "bash");
+ if (result === undefined) {
+ return { toolCalls: [{ input: { command }, name: "bash" }] };
+ }
+ if (typeof result.output === "object" && result.output !== null && "stdout" in result.output) {
+ return String((result.output as { readonly stdout: unknown }).stdout).trim();
+ }
+ return String(result.output ?? "");
+}
diff --git a/e2e/fixtures/agent-microsandbox-dockerfile/agent/sandbox/Dockerfile b/e2e/fixtures/agent-microsandbox-dockerfile/agent/sandbox/Dockerfile
new file mode 100644
index 000000000..fe0d70e75
--- /dev/null
+++ b/e2e/fixtures/agent-microsandbox-dockerfile/agent/sandbox/Dockerfile
@@ -0,0 +1,5 @@
+FROM ghcr.io/vercel/eve:latest
+
+USER root
+RUN printf '%s\n' 'microsandbox-dockerfile-ok-P6N' > /usr/local/share/eve-dockerfile-marker
+USER vercel-sandbox
diff --git a/e2e/fixtures/agent-microsandbox-dockerfile/agent/sandbox/sandbox.ts b/e2e/fixtures/agent-microsandbox-dockerfile/agent/sandbox/sandbox.ts
new file mode 100644
index 000000000..c262b8ec4
--- /dev/null
+++ b/e2e/fixtures/agent-microsandbox-dockerfile/agent/sandbox/sandbox.ts
@@ -0,0 +1,8 @@
+import { defineSandbox } from "eve/sandbox";
+import { MicrosandboxSandbox } from "eve/sandbox/microsandbox";
+
+export const environment = MicrosandboxSandbox.dockerfile({
+ setup: { autoInstall: false },
+});
+
+export default defineSandbox(() => environment.open());
diff --git a/e2e/fixtures/agent-microsandbox-dockerfile/agent/sandbox/workspace/workspace-marker.txt b/e2e/fixtures/agent-microsandbox-dockerfile/agent/sandbox/workspace/workspace-marker.txt
new file mode 100644
index 000000000..6fdf4176a
--- /dev/null
+++ b/e2e/fixtures/agent-microsandbox-dockerfile/agent/sandbox/workspace/workspace-marker.txt
@@ -0,0 +1 @@
+microsandbox-workspace-ok-W7R
diff --git a/e2e/fixtures/agent-microsandbox-dockerfile/agent/skills/mounted-skill/SKILL.md b/e2e/fixtures/agent-microsandbox-dockerfile/agent/skills/mounted-skill/SKILL.md
new file mode 100644
index 000000000..98cbe4cba
--- /dev/null
+++ b/e2e/fixtures/agent-microsandbox-dockerfile/agent/skills/mounted-skill/SKILL.md
@@ -0,0 +1,5 @@
+---
+description: Verifies that microsandbox receives the compiled read-only skill tree.
+---
+
+microsandbox-skill-ok-S8K
diff --git a/e2e/fixtures/agent-microsandbox-dockerfile/agent/tools/bash.ts b/e2e/fixtures/agent-microsandbox-dockerfile/agent/tools/bash.ts
new file mode 100644
index 000000000..6757ca643
--- /dev/null
+++ b/e2e/fixtures/agent-microsandbox-dockerfile/agent/tools/bash.ts
@@ -0,0 +1,5 @@
+import { defineTool } from "eve/tools";
+import { never } from "eve/tools/approval";
+import { bash } from "eve/tools/bash";
+
+export default defineTool({ ...bash, approval: never() });
diff --git a/e2e/fixtures/agent-microsandbox-dockerfile/evals/dockerfile.eval.ts b/e2e/fixtures/agent-microsandbox-dockerfile/evals/dockerfile.eval.ts
new file mode 100644
index 000000000..30052fefb
--- /dev/null
+++ b/e2e/fixtures/agent-microsandbox-dockerfile/evals/dockerfile.eval.ts
@@ -0,0 +1,23 @@
+import { defineEval } from "eve/evals";
+import { includes } from "eve/evals/expect";
+
+const DOCKERFILE_MARKER = "microsandbox-dockerfile-ok-P6N";
+const WORKSPACE_MARKER = "microsandbox-workspace-ok-W7R";
+const SKILL_MARKER = "microsandbox-skill-ok-S8K";
+
+export default defineEval({
+ description: "Microsandbox: a Dockerfile image boots with mounted workspace and skills.",
+ async test(t) {
+ const result = await t.send(
+ "Run the bash command `cat /usr/local/share/eve-dockerfile-marker " +
+ "/workspace/workspace-marker.txt $HOME/.agents/skills/mounted-skill/SKILL.md` " +
+ "and reply with the command output verbatim.",
+ );
+
+ t.succeeded();
+ t.calledTool("bash", { count: 1 });
+ t.check(result.message, includes(DOCKERFILE_MARKER));
+ t.check(result.message, includes(WORKSPACE_MARKER));
+ t.check(result.message, includes(SKILL_MARKER));
+ },
+});
diff --git a/e2e/fixtures/agent-microsandbox-dockerfile/evals/evals.config.ts b/e2e/fixtures/agent-microsandbox-dockerfile/evals/evals.config.ts
new file mode 100644
index 000000000..040237dc9
--- /dev/null
+++ b/e2e/fixtures/agent-microsandbox-dockerfile/evals/evals.config.ts
@@ -0,0 +1,4 @@
+import { e2eJudgeModel } from "@eve-e2e/config";
+import { defineEvalConfig } from "eve/evals";
+
+export default defineEvalConfig({ judge: { model: e2eJudgeModel() } });
diff --git a/e2e/fixtures/agent-microsandbox-dockerfile/package.json b/e2e/fixtures/agent-microsandbox-dockerfile/package.json
new file mode 100644
index 000000000..eea8525b1
--- /dev/null
+++ b/e2e/fixtures/agent-microsandbox-dockerfile/package.json
@@ -0,0 +1,26 @@
+{
+ "name": "agent-microsandbox-dockerfile",
+ "version": "0.0.0",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "build": "eve build",
+ "typecheck": "tsc",
+ "test:e2e": "eve eval --strict"
+ },
+ "dependencies": {
+ "@eve-e2e/config": "workspace:*",
+ "@workflow/world-postgres": "catalog:",
+ "eve": "workspace:*",
+ "microsandbox": "0.5.5",
+ "zod": "catalog:"
+ },
+ "devDependencies": {
+ "@types/node": "catalog:",
+ "typescript": "catalog:"
+ },
+ "e2e": {
+ "modelMatrix": "default",
+ "worlds": []
+ }
+}
diff --git a/e2e/fixtures/agent-microsandbox-dockerfile/tsconfig.json b/e2e/fixtures/agent-microsandbox-dockerfile/tsconfig.json
new file mode 100644
index 000000000..f3b17fbf4
--- /dev/null
+++ b/e2e/fixtures/agent-microsandbox-dockerfile/tsconfig.json
@@ -0,0 +1,7 @@
+{
+ "extends": "../../../tsconfig.json",
+ "compilerOptions": {
+ "noEmit": true
+ },
+ "include": ["agent/**/*.ts", "evals/**/*.ts"]
+}
diff --git a/e2e/fixtures/agent-task-reporting/agent/sandbox.ts b/e2e/fixtures/agent-task-reporting/agent/sandbox.ts
index 319677b16..329ae8886 100644
--- a/e2e/fixtures/agent-task-reporting/agent/sandbox.ts
+++ b/e2e/fixtures/agent-task-reporting/agent/sandbox.ts
@@ -1,10 +1,8 @@
import { defineSandbox } from "eve/sandbox";
-import { justbash } from "eve/sandbox/just-bash";
+import { JustBashSandbox } from "eve/sandbox/just-bash";
-// This eval exercises background-task delivery, not shell or filesystem behavior.
-// Keep external sandbox provisioning out of the experiment.
-export default defineSandbox({
- backend: justbash({
- filesystem: ({ justBash }) => new justBash.InMemoryFs(),
- }),
+export const environment = JustBashSandbox.environment({
+ filesystem: ({ justBash }) => new justBash.InMemoryFs(),
});
+
+export default defineSandbox(() => environment.open());
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/sandbox/sandbox.ts b/e2e/fixtures/agent-tools-sandbox/agent/sandbox/sandbox.ts
index b625825a2..8e1032a00 100644
--- a/e2e/fixtures/agent-tools-sandbox/agent/sandbox/sandbox.ts
+++ b/e2e/fixtures/agent-tools-sandbox/agent/sandbox/sandbox.ts
@@ -1,47 +1,42 @@
-import { defaultBackend, defineSandbox } from "eve/sandbox";
-import { vercel } from "eve/sandbox/vercel";
+import { DefaultSandbox, defineSandbox, type SandboxSession } from "eve/sandbox";
+import { VercelSandbox } from "eve/sandbox/vercel";
/**
* Sandbox lifecycle fixture exercising the surfaces an agent author relies
* on. The matching evals live under `evals/sandbox/` and assert each piece
- * end-to-end through a real backend.
+ * end-to-end through a real provider.
*
- * - `bootstrap` runs once per sandbox template. It writes a known marker
- * file into the workspace AND installs a custom CLI (`eve-greet`) onto the
- * PATH, the way an author would provision tooling every later session
- * inherits. The CLI is a Python script, so it also proves the base image's
- * real Python runtime executes bootstrap-authored code.
- * - `onSession` runs once per live session. It writes a per-session marker
- * so an eval can prove session-scoped setup ran on top of the shared
- * template.
+ * - `prepare()` runs once per sandbox environment generation. It writes a
+ * marker and installs a custom CLI (`eve-greet`) that every later session
+ * inherits. The CLI also proves the base image can execute Python.
+ * - The selector writes a marker and starts a loopback server once when the
+ * durable session first opens its sandbox.
*
- * Backend is left as the framework default so this fixture works both
- * locally (where `defaultBackend()` resolves to `docker()`) and on Vercel
- * deployments (where it resolves to `vercel()`). Both run the published eve
+ * The default environment keeps this fixture portable between local providers
+ * and Vercel Sandbox. Both run the published eve
* base image: GHCR locally and VCR on Vercel. CI sets `EVE_SANDBOX_IMAGE_TAG`
* to `latest` so release PRs can run before their versioned image exists. The
- * image ships Python, Node, and git; the bootstrap below assumes
+ * image ships Python, Node, and git; the preparation below assumes
* that real-binary environment and is not meant to run against the
* dependency-free `just-bash` fallback.
*
- * `EVE_TEST_AUTHOR_SNAPSHOT_ID`, when set, overrides the backend with
- * `vercel({ source: { type: "snapshot", snapshotId } })` so the
- * sandbox-author-snapshot smoke test can verify that an author-supplied
- * snapshot is honored as the template base layer while bootstrap still
- * runs on top.
+ * `EVE_TEST_AUTHOR_SNAPSHOT_ID`, when set, overrides the provider with
+ * `VercelSandbox.environment({ prepare })` with a snapshot source so the author-snapshot
+ * smoke test can verify that an author-supplied snapshot remains the base
+ * layer while environment preparation runs on top.
*/
export const SANDBOX_MARKER_PATH = "/workspace/smoke-marker.txt";
-export const SANDBOX_MARKER_TOKEN = "sandbox-bootstrap-ok-J3Q";
+export const SANDBOX_MARKER_TOKEN = "sandbox-preparation-ok-J3Q";
/**
- * Custom CLI installed during bootstrap. The base image puts the sandbox
- * user's npm global prefix on PATH, so the same install works across backends.
+ * Custom CLI installed during preparation. The base image puts the sandbox
+ * user's npm global prefix on PATH, so the same install works across providers.
*/
const SANDBOX_CLI_DIRECTORY_PATH = "/home/vercel-sandbox/.local/bin";
export const SANDBOX_CLI_PATH = `${SANDBOX_CLI_DIRECTORY_PATH}/eve-greet`;
export const SANDBOX_CLI_TOKEN = "eve-greet-cli-ok-R7M";
-/** Per-session marker written by `onSession` (live session, not the template). */
+/** Per-session marker written by the selector, not environment preparation. */
export const SANDBOX_SESSION_MARKER_PATH = "/workspace/session-marker.txt";
export const SANDBOX_SESSION_MARKER_TOKEN = "sandbox-onsession-ok-X5T";
@@ -134,56 +129,45 @@ const FANOUT_SERVER_SCRIPT = [
].join("\n");
const authorSnapshotId = process.env.EVE_TEST_AUTHOR_SNAPSHOT_ID;
-const backend =
- authorSnapshotId !== undefined
- ? vercel({ source: { snapshotId: authorSnapshotId, type: "snapshot" } })
- : defaultBackend();
+const prepareEnvironment = async (sandbox: SandboxSession) => {
+ await sandbox.writeTextFile({ path: SANDBOX_MARKER_PATH, content: SANDBOX_MARKER_TOKEN });
+ const mkdir = await sandbox.run({ command: `mkdir -p ${SANDBOX_CLI_DIRECTORY_PATH}` });
+ if (mkdir.exitCode !== 0)
+ throw new Error(`prepare: failed to create CLI directory: ${mkdir.stderr}`);
+ await sandbox.writeTextFile({ path: SANDBOX_CLI_PATH, content: CLI_SCRIPT });
+ const chmod = await sandbox.run({ command: `chmod +x ${SANDBOX_CLI_PATH}` });
+ if (chmod.exitCode !== 0) throw new Error(`prepare: chmod failed: ${chmod.stderr}`);
+};
-export default defineSandbox({
- backend,
- // Bump when the bootstrap output changes so the reusable template snapshot
- // is rebuilt rather than served stale.
- revalidationKey: () => "agent-tools-sandbox-bootstrap-v3",
- async bootstrap({ use }) {
- const sandbox = await use();
- await sandbox.writeTextFile({
- path: SANDBOX_MARKER_PATH,
- content: SANDBOX_MARKER_TOKEN,
- });
- // Install a custom CLI onto the PATH and make it executable. Later
- // sessions inherit it from the template without re-running bootstrap.
- const mkdir = await sandbox.run({ command: `mkdir -p ${SANDBOX_CLI_DIRECTORY_PATH}` });
- if (mkdir.exitCode !== 0) {
- throw new Error(`bootstrap: failed to create CLI directory: ${mkdir.stderr}`);
- }
- await sandbox.writeTextFile({ path: SANDBOX_CLI_PATH, content: CLI_SCRIPT });
- const chmod = await sandbox.run({ command: `chmod +x ${SANDBOX_CLI_PATH}` });
- if (chmod.exitCode !== 0) {
- throw new Error(`bootstrap: chmod of ${SANDBOX_CLI_PATH} failed: ${chmod.stderr}`);
- }
- },
- async onSession({ use }) {
- const sandbox = await use();
- await sandbox.writeTextFile({
- path: SANDBOX_SESSION_MARKER_PATH,
- content: SANDBOX_SESSION_MARKER_TOKEN,
- });
- await sandbox.writeTextFile({ path: FANOUT_SERVER_PATH, content: FANOUT_SERVER_SCRIPT });
- const startServer = await sandbox.run({
- command: [
- `if ! curl -fsS http://127.0.0.1:${FANOUT_SERVER_PORT}/health >/dev/null; then`,
- ` nohup python3 ${FANOUT_SERVER_PATH} >${FANOUT_SERVER_LOG_PATH} 2>&1 &`,
- "fi",
- "for attempt in $(seq 1 50); do",
- ` if curl -fsS http://127.0.0.1:${FANOUT_SERVER_PORT}/health >/dev/null; then exit 0; fi`,
- " sleep 0.1",
- "done",
- `cat ${FANOUT_SERVER_LOG_PATH} >&2`,
- "exit 1",
- ].join("\n"),
- });
- if (startServer.exitCode !== 0) {
- throw new Error(`Fanout server failed to start: ${startServer.stderr}`);
- }
- },
+export const environment =
+ authorSnapshotId === undefined
+ ? DefaultSandbox.environment({ prepare: prepareEnvironment })
+ : VercelSandbox.environment({
+ prepare: prepareEnvironment,
+ source: { snapshotId: authorSnapshotId, type: "snapshot" },
+ });
+
+export default defineSandbox(async () => {
+ const sandbox = await environment.open();
+ await sandbox.writeTextFile({
+ path: SANDBOX_SESSION_MARKER_PATH,
+ content: SANDBOX_SESSION_MARKER_TOKEN,
+ });
+ await sandbox.writeTextFile({ path: FANOUT_SERVER_PATH, content: FANOUT_SERVER_SCRIPT });
+ const startServer = await sandbox.run({
+ command: [
+ `if ! curl -fsS http://127.0.0.1:${FANOUT_SERVER_PORT}/health >/dev/null; then`,
+ ` nohup python3 ${FANOUT_SERVER_PATH} >${FANOUT_SERVER_LOG_PATH} 2>&1 &`,
+ "fi",
+ "for attempt in $(seq 1 50); do",
+ ` if curl -fsS http://127.0.0.1:${FANOUT_SERVER_PORT}/health >/dev/null; then exit 0; fi`,
+ " sleep 0.1",
+ "done",
+ `cat ${FANOUT_SERVER_LOG_PATH} >&2`,
+ "exit 1",
+ ].join("\n"),
+ });
+ if (startServer.exitCode !== 0)
+ throw new Error(`Fanout server failed to start: ${startServer.stderr}`);
+ return sandbox;
});
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
new file mode 100644
index 000000000..e6c30d888
--- /dev/null
+++ b/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/agent.ts
@@ -0,0 +1,15 @@
+import { e2eSubagentConfig } from "@eve-e2e/config";
+import { defineAgent } from "eve";
+import type { MockModelRequest, MockModelResponse } from "eve/evals";
+
+export default defineAgent({
+ description: "Verifies custom sandbox provider session capabilities.",
+ ...e2eSubagentConfig({ mock: respond }),
+});
+
+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);
+}
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
new file mode 100644
index 000000000..d013fd0aa
--- /dev/null
+++ b/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/sandbox.ts
@@ -0,0 +1,89 @@
+import { defineSandbox, type SandboxSession } from "eve/sandbox";
+import { defineSandboxProvider } 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 };
+
+const provider = defineSandboxProvider<undefined, undefined, null, CustomState, CustomSession>({
+ name: "custom-provider-session",
+ environment() {
+ return {
+ async prepare() {
+ return null;
+ },
+ async resume(_context, _artifact, state) {
+ return createHandle(state.marker);
+ },
+ async start(context) {
+ const marker = `${CUSTOM_PROVIDER_TOKEN}:${context.session.id}`;
+ return {
+ handle: createHandle(marker),
+ state: { marker, version: 1 },
+ };
+ },
+ };
+ },
+});
+
+export const environment = provider.environment();
+
+export default defineSandbox(async () => {
+ const sandbox = await environment.open();
+ await sandbox.writeTextFile({ content: await sandbox.probe(), path: "/workspace/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: "" };
+ },
+ async spawn() {
+ throw new Error("spawn is not used by this fixture.");
+ },
+ async writeBinaryFile({ content, path }: { content: Uint8Array; path: string }) {
+ files.set(resolvePath(path), content);
+ },
+ 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 writeTextFile({ content, path }: { content: string; path: string }) {
+ files.set(resolvePath(path), Buffer.from(content));
+ },
+ } satisfies CustomSession;
+ return {
+ sandbox: Object.freeze(session),
+ async onRuntimeShutdown() {},
+ async onSessionDelete() {},
+ async onSessionStop() {},
+ };
+}
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/tools/verify-provider-session.ts b/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/tools/verify-provider-session.ts
new file mode 100644
index 000000000..fea879509
--- /dev/null
+++ b/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/tools/verify-provider-session.ts
@@ -0,0 +1,11 @@
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+
+export default defineTool({
+ description: "Reads the marker initialized through the custom provider session method.",
+ inputSchema: z.object({}),
+ async execute(_input, ctx) {
+ const sandbox = await ctx.getSandbox();
+ return await sandbox.readTextFile({ path: "/workspace/probe.txt" });
+ },
+});
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/subagents/deny-all/agent.ts b/e2e/fixtures/agent-tools-sandbox/agent/subagents/deny-all/agent.ts
new file mode 100644
index 000000000..123e3d539
--- /dev/null
+++ b/e2e/fixtures/agent-tools-sandbox/agent/subagents/deny-all/agent.ts
@@ -0,0 +1,9 @@
+import { e2eSubagentConfig } from "@eve-e2e/config";
+import { defineAgent } from "eve";
+
+import { respond } from "../../lib/mock-responder.js";
+
+export default defineAgent({
+ description: "Runs commands in an independent sandbox opened with deny-all networking.",
+ ...e2eSubagentConfig({ mock: respond }),
+});
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/subagents/deny-all/sandbox.ts b/e2e/fixtures/agent-tools-sandbox/agent/subagents/deny-all/sandbox.ts
new file mode 100644
index 000000000..54aad554b
--- /dev/null
+++ b/e2e/fixtures/agent-tools-sandbox/agent/subagents/deny-all/sandbox.ts
@@ -0,0 +1,9 @@
+import { defineSandbox } from "eve/sandbox";
+import { DockerSandbox } from "eve/sandbox/docker";
+import { VercelSandbox } from "eve/sandbox/vercel";
+
+export const environment = process.env.VERCEL
+ ? VercelSandbox.environment()
+ : DockerSandbox.environment();
+
+export default defineSandbox(() => environment.open({ networkPolicy: "deny-all" }));
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/subagents/shared-sandbox/agent.ts b/e2e/fixtures/agent-tools-sandbox/agent/subagents/parent-sandbox/agent.ts
similarity index 73%
rename from e2e/fixtures/agent-tools-sandbox/agent/subagents/shared-sandbox/agent.ts
rename to e2e/fixtures/agent-tools-sandbox/agent/subagents/parent-sandbox/agent.ts
index a49bb5fe6..4e267b2d2 100644
--- a/e2e/fixtures/agent-tools-sandbox/agent/subagents/shared-sandbox/agent.ts
+++ b/e2e/fixtures/agent-tools-sandbox/agent/subagents/parent-sandbox/agent.ts
@@ -4,6 +4,6 @@ import { defineAgent } from "eve";
import { respond } from "../../lib/mock-responder.js";
export default defineAgent({
- description: "Runs sandbox commands in the root agent's shared workspace.",
+ description: "Runs sandbox commands in the root agent's inherited workspace.",
...e2eSubagentConfig({ mock: respond }),
});
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/subagents/parent-sandbox/sandbox.ts b/e2e/fixtures/agent-tools-sandbox/agent/subagents/parent-sandbox/sandbox.ts
new file mode 100644
index 000000000..65cd14faa
--- /dev/null
+++ b/e2e/fixtures/agent-tools-sandbox/agent/subagents/parent-sandbox/sandbox.ts
@@ -0,0 +1,2 @@
+import { defineParentSandbox } from "eve/sandbox";
+export default defineParentSandbox();
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/subagents/shared-sandbox/sandbox.ts b/e2e/fixtures/agent-tools-sandbox/agent/subagents/shared-sandbox/sandbox.ts
deleted file mode 100644
index 9deecea73..000000000
--- a/e2e/fixtures/agent-tools-sandbox/agent/subagents/shared-sandbox/sandbox.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { defineSandbox } from "eve/sandbox";
-
-export default defineSandbox(({ parent }) => {
- if (parent === null) throw new Error("shared-sandbox must run as a child");
- return parent.sandbox;
-});
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/tools/bash.ts b/e2e/fixtures/agent-tools-sandbox/agent/tools/bash.ts
index f4b438707..71f9fa66a 100644
--- a/e2e/fixtures/agent-tools-sandbox/agent/tools/bash.ts
+++ b/e2e/fixtures/agent-tools-sandbox/agent/tools/bash.ts
@@ -3,7 +3,7 @@ import { never } from "eve/tools/approval";
import { bash } from "eve/tools/bash";
/**
- * Bash tool exposed to the model for the sandbox-bootstrap smoke
+ * Bash tool exposed to the model for sandbox preparation smoke
* test. `approval: never()` keeps the smoke test single-turn
* and avoids tripping the HITL machinery already exercised by
* `tool-approval.ts` / `tool-denial.ts`.
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/tools/network-probe.ts b/e2e/fixtures/agent-tools-sandbox/agent/tools/network-probe.ts
index cb9daf80a..9ecf116be 100644
--- a/e2e/fixtures/agent-tools-sandbox/agent/tools/network-probe.ts
+++ b/e2e/fixtures/agent-tools-sandbox/agent/tools/network-probe.ts
@@ -7,7 +7,7 @@ import { z } from "zod";
* and reports whether it was blocked.
*
* The assertion the eval gates on is self-contained: under `deny-all` the
- * sandbox has no egress at all (the Docker backend detaches every network, the
+ * sandbox has no egress at all (the Docker provider detaches every network, the
* Vercel firewall blocks the request), so `curl` fails without depending on
* any external host being reachable. `blocked` plus a network-failure `stderr`
* signature distinguishes a policy block from `curl` being missing.
@@ -18,6 +18,9 @@ export default defineTool({
inputSchema: z.object({}),
async execute(_input, ctx) {
const sandbox = await ctx.getSandbox();
+ if (sandbox.setNetworkPolicy === undefined) {
+ throw new Error("The selected sandbox provider does not support mutable network policies.");
+ }
await sandbox.setNetworkPolicy("deny-all");
const result = await sandbox.run({
command: "curl -sS --max-time 5 -o /dev/null https://example.com",
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/tools/run_python.ts b/e2e/fixtures/agent-tools-sandbox/agent/tools/run_python.ts
index 80f55b8e1..02c331586 100644
--- a/e2e/fixtures/agent-tools-sandbox/agent/tools/run_python.ts
+++ b/e2e/fixtures/agent-tools-sandbox/agent/tools/run_python.ts
@@ -6,7 +6,7 @@ import { z } from "zod";
* `ctx.getSandbox()` runtime API — the headline authored-sandbox path from
* the docs. It writes a generated script with `writeTextFile`, executes it
* with `run`, and returns the parsed result, exercising `getSandbox`,
- * `writeTextFile`, and `run` together against a real backend.
+ * `writeTextFile`, and `run` together against a real provider.
*
* The computation is deterministic given its input (the sum of the supplied
* integers) so the eval can assert an exact value while still proving the
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/bootstrap.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/bootstrap.eval.ts
deleted file mode 100644
index 54fd503ce..000000000
--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/bootstrap.eval.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { defineEval } from "eve/evals";
-
-import { BOOTSTRAP_MARKER_PATH, BOOTSTRAP_MARKER_TOKEN } from "./shared";
-
-// The prompt directs the model to run the backticked `bash` command; a
-// non-error result containing the marker token proves the bootstrap-written
-// file is visible inside the sandbox.
-export default defineEval({
- tags: ["real-model"],
- description: "Sandbox smoke: `defineSandbox({ bootstrap })` runs before the first bash call.",
- async test(t) {
- await t.send(
- `Run the bash command \`cat ${BOOTSTRAP_MARKER_PATH}\` and reply with the file contents verbatim.`,
- );
-
- t.succeeded();
- t.calledTool("bash", {
- output: new RegExp(BOOTSTRAP_MARKER_TOKEN),
- });
- },
-});
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/cli-install.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/cli-install.eval.ts
index 4323c0b89..c3ae4bd7c 100644
--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/cli-install.eval.ts
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/cli-install.eval.ts
@@ -2,13 +2,13 @@ import { defineEval } from "eve/evals";
import { SANDBOX_CLI_NAME, SANDBOX_CLI_TOKEN } from "./shared";
-// `bootstrap` installed a custom Python CLI onto the PATH. Invoking it by
-// name (no path) through the `bash` tool proves the bootstrap-provisioned
-// tooling is both on the PATH and executable in later sessions, and that the
-// base image's Python runtime ran the bootstrap-authored script.
+// Environment preparation installed a custom Python CLI onto the PATH. Invoking it by
+// name through the `bash` tool proves the prepared tooling is executable in
+// later sessions and that the base image's Python runtime ran the script.
export default defineEval({
tags: ["real-model"],
- description: "Sandbox: a custom CLI installed in `bootstrap` is on the PATH for later sessions.",
+ description:
+ "Sandbox: a custom CLI installed during preparation is on the PATH for later sessions.",
async test(t) {
await t.send(
`Run the bash command \`${SANDBOX_CLI_NAME} sandbox\` and reply with its output verbatim.`,
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/custom-provider-session.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/custom-provider-session.eval.ts
new file mode 100644
index 000000000..fbf648851
--- /dev/null
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/custom-provider-session.eval.ts
@@ -0,0 +1,33 @@
+import { defineEval } from "eve/evals";
+import { includes } from "eve/evals/expect";
+
+const TOKEN = "custom-provider-session-ok-P7M";
+
+export default defineEval({
+ description: "Sandbox: custom provider session methods survive framework lifecycle wrapping.",
+ timeoutMs: 60_000,
+ async test(t) {
+ const turn = await t.send(
+ "Ask the `custom-provider` subagent with message: Verify the custom provider session marker.",
+ );
+ turn.expectOk();
+ const sessionId = turn.sessionId;
+ if (sessionId === undefined) throw new Error("Custom provider turn has no session id.");
+ const completed = await t.target
+ .watchTurn(sessionId, { startIndex: requireStreamIndex(turn.session) })
+ .result();
+ completed.expectOk();
+
+ t.succeeded();
+ t.calledSubagent("custom-provider", { count: 1, status: "completed" });
+ t.check(completed.message, includes(TOKEN));
+ },
+});
+
+function requireStreamIndex(session: {
+ readonly state?: { readonly streamIndex?: number };
+}): number {
+ const streamIndex = session.state?.streamIndex;
+ if (streamIndex === undefined) throw new Error("Custom provider turn has no stream index.");
+ return streamIndex;
+}
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/hook-stop.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/hook-stop.eval.ts
index 49601bfae..82d40df1e 100644
--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/hook-stop.eval.ts
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/hook-stop.eval.ts
@@ -6,7 +6,7 @@ const STOP_SANDBOX_MARKER_PATH = "/workspace/stopped-by-hook.txt";
// The first response activates an authored hook that writes a marker and
// stops compute. Reading that marker on the next turn proves the configured
-// backend reopens the same durable sandbox state.
+// provider reopens the same durable sandbox state.
export default defineEval({
description: "Sandbox: an authored hook can stop compute and the next turn reopens it.",
async test(t) {
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/network-policy.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/network-policy.eval.ts
index 66ccb58ac..f9565d08e 100644
--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/network-policy.eval.ts
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/network-policy.eval.ts
@@ -19,7 +19,7 @@ function isBlocked(value: unknown): boolean {
// `network-probe` applies a deny-all policy to the live sandbox mid-turn and
// then attempts egress. Asserting the probe came back blocked proves
-// `setNetworkPolicy("deny-all")` actually severs egress on the active backend.
+// `setNetworkPolicy("deny-all")` actually severs egress on the active provider.
export default defineEval({
tags: ["real-model"],
description: "Sandbox: setNetworkPolicy('deny-all') blocks sandbox egress mid-turn.",
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/open-network-policy.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/open-network-policy.eval.ts
new file mode 100644
index 000000000..08feb6e83
--- /dev/null
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/open-network-policy.eval.ts
@@ -0,0 +1,34 @@
+import { defineEval } from "eve/evals";
+import { includes } from "eve/evals/expect";
+
+export default defineEval({
+ description: "Sandbox: an open-time deny-all policy applies before authored commands run.",
+ timeoutMs: 60_000,
+ async test(t) {
+ const turn = await t.send(
+ "Ask the `deny-all` subagent with message: " +
+ "Run the bash command `curl -sS --max-time 5 -o /dev/null https://example.com || echo blocked-egress` " +
+ "and reply with the command output verbatim.",
+ );
+ turn.expectOk();
+ const sessionId = turn.sessionId;
+ if (sessionId === undefined) throw new Error("Deny-all sandbox turn has no session id.");
+ const completed = t.target.watchTurn(sessionId, {
+ startIndex: requireStreamIndex(turn.session),
+ });
+ const child = await completed.result();
+ child.expectOk();
+
+ t.succeeded();
+ t.calledSubagent("deny-all", { count: 1, status: "completed" });
+ t.check(child.message, includes("blocked-egress"));
+ },
+});
+
+function requireStreamIndex(session: {
+ readonly state?: { readonly streamIndex?: number };
+}): number {
+ const streamIndex = session.state?.streamIndex;
+ if (streamIndex === undefined) throw new Error("Deny-all sandbox turn has no stream index.");
+ return streamIndex;
+}
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/subagent-sharing.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/parent-inheritance.eval.ts
similarity index 93%
rename from e2e/fixtures/agent-tools-sandbox/evals/sandbox/subagent-sharing.eval.ts
rename to e2e/fixtures/agent-tools-sandbox/evals/sandbox/parent-inheritance.eval.ts
index 2aa3966e5..aad36eb5b 100644
--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/subagent-sharing.eval.ts
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/parent-inheritance.eval.ts
@@ -17,7 +17,7 @@ export default defineEval({
parentWrite.expectOk();
const childTurn = await conversation.send(
- `Ask the \`shared-sandbox\` subagent with message: ` +
+ `Ask the \`parent-sandbox\` subagent with message: ` +
`Run the bash command \`cat ${PARENT_PATH} && printf %s ${CHILD_TOKEN} > ${CHILD_PATH}\` ` +
"and reply with the command output verbatim.",
);
@@ -36,7 +36,7 @@ export default defineEval({
);
t.succeeded();
- t.calledSubagent("shared-sandbox", { status: "completed", count: 1 });
+ t.calledSubagent("parent-sandbox", { status: "completed", count: 1 });
t.check(parentRead.message, includes(CHILD_TOKEN));
},
});
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/preparation.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/preparation.eval.ts
new file mode 100644
index 000000000..dbc9bf94a
--- /dev/null
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/preparation.eval.ts
@@ -0,0 +1,22 @@
+import { defineEval } from "eve/evals";
+
+import { PREPARATION_MARKER_PATH, PREPARATION_MARKER_TOKEN } from "./shared";
+
+// The prompt directs the model to run the backticked `bash` command; a
+// non-error result containing the marker token proves the preparation-written
+// file is visible inside the sandbox.
+export default defineEval({
+ tags: ["real-model"],
+ description:
+ "Sandbox smoke: `VercelSandbox.environment({ prepare })` runs before the first bash call.",
+ async test(t) {
+ await t.send(
+ `Run the bash command \`cat ${PREPARATION_MARKER_PATH}\` and reply with the file contents verbatim.`,
+ );
+
+ t.succeeded();
+ t.calledTool("bash", {
+ output: new RegExp(PREPARATION_MARKER_TOKEN),
+ });
+ },
+});
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/redeploy.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/redeploy.eval.ts
index 363b3c845..ba2bbcc49 100644
--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/redeploy.eval.ts
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/redeploy.eval.ts
@@ -26,10 +26,9 @@ import type { EveEvalContext } from "eve/evals";
// t1' push a deployment update that adds a skill — skills materialize into
// the sandbox workspace resources, so the sandbox version hash rotates
// for anything executing the new code
-// t3 session A no longer sees the file: its next request runs on the new
-// deployment, whose changed sandbox resources rotate the sandbox key
-// t4 a NEW session B adopts the new deployment: the added skill loads and
-// shapes the reply
+// t3 a new session B adopts the changed sandbox resources and does not see
+// session A's file
+// t4 session B loads the added skill and follows its instructions
//
// Requires EVE_E2E_REDEPLOY_ALIAS plus Vercel credentials and a linked
// fixture directory (the e2e-vercel workflow provides all three); skips
@@ -114,9 +113,11 @@ export default defineEval({
await deployToAlias(t, alias, "skill");
await waitForAliasToServe(t, `"${SKILL_NAME}"`);
- // t3: the next request is accepted by the new deployment. Its changed
- // sandbox resources rotate the versioned key, so the old file is absent.
- const probe = await session.send(
+ // Direct provider resume intentionally rejects session A because its
+ // immutable artifact generation no longer matches this deployment. A
+ // fresh session adopts the changed resources and starts clean.
+ const adopted = await t.session();
+ const probe = await adopted.send(
`Run the bash command \`test -f ${FILE_PATH} && echo present || echo absent\` ` +
"and reply with the command output verbatim.",
);
@@ -124,9 +125,6 @@ export default defineEval({
probe.calledTool("bash", { output: /absent/ });
probe.messageIncludes("absent");
- // t4: a fresh session adopts the new deployment — the added skill is
- // advertised and usable.
- const adopted = await t.session();
const skill = await adopted.send(
`Load the \`${SKILL_NAME}\` skill and follow its instructions exactly.`,
);
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/session-setup.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/session-setup.eval.ts
index 2ec5ea892..4d5fff8ce 100644
--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/session-setup.eval.ts
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/session-setup.eval.ts
@@ -8,13 +8,13 @@ import {
} from "./shared";
// Two session-scoped setup surfaces in one bash call:
-// 1. `onSession` wrote SESSION_MARKER_PATH into this live session.
+// 1. The sandbox selector wrote SESSION_MARKER_PATH into this live session.
// 2. `agent/sandbox/workspace/seed-data.txt` was mounted at WORKSPACE_SEED_PATH.
// A single `cat` of both files proving both tokens appear shows session-scoped
// setup and workspace seeding both landed on top of the shared template.
export default defineEval({
tags: ["real-model"],
- description: "Sandbox: onSession marker and seeded workspace file are both present per session.",
+ description: "Sandbox: selector setup and the seeded workspace file are present per session.",
async test(t) {
await t.send(
`Run the bash command \`cat ${SESSION_MARKER_PATH} ${WORKSPACE_SEED_PATH}\` ` +
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/shared.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/shared.ts
index 6e1f0dafb..c7664f208 100644
--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/shared.ts
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/shared.ts
@@ -3,15 +3,15 @@
// prove the corresponding surface actually ran. Kept in sync by hand because
// the agent tree is compiled/deployed independently of the eval tree.
-/** Written by `bootstrap` into the reusable template snapshot. */
-export const BOOTSTRAP_MARKER_PATH = "/workspace/smoke-marker.txt";
-export const BOOTSTRAP_MARKER_TOKEN = "sandbox-bootstrap-ok-J3Q";
+/** Written by `prepare()` into the reusable environment snapshot. */
+export const PREPARATION_MARKER_PATH = "/workspace/smoke-marker.txt";
+export const PREPARATION_MARKER_TOKEN = "sandbox-preparation-ok-J3Q";
-/** Custom CLI installed on the PATH by `bootstrap`. */
+/** Custom CLI installed on the PATH by environment preparation. */
export const SANDBOX_CLI_NAME = "eve-greet";
export const SANDBOX_CLI_TOKEN = "eve-greet-cli-ok-R7M";
-/** Written by `onSession` into each live session (not the template). */
+/** Written by the selector into each live session (not the template). */
export const SESSION_MARKER_PATH = "/workspace/session-marker.txt";
export const SESSION_MARKER_TOKEN = "sandbox-onsession-ok-X5T";
diff --git a/packages/eve/extension-contracts/reports/channel/v29.json b/packages/eve/extension-contracts/reports/channel/v29.json
new file mode 100644
index 000000000..5fd5e66b7
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/channel/v29.json
@@ -0,0 +1,21 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "channel",
+ "epoch": 29,
+ "sha256": "cc5d7186384e361ce6d796c2c85369756c4e8828075e1637850e832c2afb6093",
+ "exports": [
+ "DELETE",
+ "GET",
+ "HEAD",
+ "OPTIONS",
+ "PATCH",
+ "POST",
+ "PUT",
+ "WS",
+ "createWebSocketUpgradeServer",
+ "defineChannel",
+ "disableRoute",
+ "isChannel",
+ "isDisabledRouteSentinel"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/connection/v24.json b/packages/eve/extension-contracts/reports/connection/v24.json
new file mode 100644
index 000000000..0ecbd2302
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/connection/v24.json
@@ -0,0 +1,16 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "connection",
+ "epoch": 24,
+ "sha256": "fc4ee10b9b02b038dd302900b38c6a58d5ab87b0f658d7fde1a9bce15bf292e1",
+ "exports": [
+ "ConnectionAuthorizationFailedError",
+ "ConnectionAuthorizationRequiredError",
+ "defineDynamic",
+ "defineInteractiveAuthorization",
+ "defineMcpClientConnection",
+ "defineOpenAPIConnection",
+ "isConnectionAuthorizationFailedError",
+ "isConnectionAuthorizationRequiredError"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v52.json b/packages/eve/extension-contracts/reports/dynamicTool/v52.json
new file mode 100644
index 000000000..1800f8550
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicTool/v52.json
@@ -0,0 +1,16 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicTool",
+ "epoch": 52,
+ "sha256": "4ee54458d953ee5f36eb012ee93fda76dd769aaf6881a892926a229a412e5ae9",
+ "exports": [
+ "DynamicToolEntry",
+ "DynamicToolEvents",
+ "DynamicToolResult",
+ "DynamicToolSet",
+ "auto",
+ "defineDurableCallback",
+ "defineDurableSchema",
+ "defineDynamic"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/hook/v25.json b/packages/eve/extension-contracts/reports/hook/v25.json
new file mode 100644
index 000000000..1f96f7cdc
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/hook/v25.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "hook",
+ "epoch": 25,
+ "sha256": "c173d3ad99d947937b3cee37f281db7bfbceb60bd41155cb4441d2db0dc19155",
+ "exports": ["defineHook"]
+}
diff --git a/packages/eve/extension-contracts/reports/state/v7.json b/packages/eve/extension-contracts/reports/state/v7.json
new file mode 100644
index 000000000..fd06b6e8e
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/state/v7.json
@@ -0,0 +1,15 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "state",
+ "epoch": 7,
+ "sha256": "d672c41f4478990dbfe7c7b0526882643d8b18ecd6342138bafc67e9b0141bb4",
+ "exports": [
+ "Session",
+ "SessionAuth",
+ "SessionAuthContext",
+ "SessionContext",
+ "SessionParent",
+ "SessionTurn",
+ "defineState"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/tool/v54.json b/packages/eve/extension-contracts/reports/tool/v54.json
new file mode 100644
index 000000000..15fc33fc3
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/tool/v54.json
@@ -0,0 +1,27 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "tool",
+ "epoch": 54,
+ "sha256": "6e02d3836a9946d1a918e9c2f21bd6921fb8e1dd1b8e156d70162bd4c3682b82",
+ "exports": [
+ "AgentRouterInput",
+ "AgentRouterTool",
+ "WorkflowStepToolContext",
+ "WorkflowTool",
+ "WorkflowToolInput",
+ "WorkflowToolOptions",
+ "agentRouter",
+ "defaultWebSearch",
+ "defineTool",
+ "defineWorkflowTool",
+ "disableTool",
+ "evaluate",
+ "isDisabledToolSentinel",
+ "isWebSearchToolDefinition",
+ "toolOutput",
+ "toolOutputPart",
+ "toolResultFrom",
+ "webSearch",
+ "workflow"
+ ]
+}
diff --git a/packages/eve/package.json b/packages/eve/package.json
index 2919013c0..084ce5807 100644
--- a/packages/eve/package.json
+++ b/packages/eve/package.json
@@ -256,6 +256,11 @@
"import": "./dist/src/public/sandbox/index.js",
"default": "./dist/src/public/sandbox/index.js"
},
+ "./sandbox/provider": {
+ "types": "./dist/src/public/sandbox/provider.d.ts",
+ "import": "./dist/src/public/sandbox/provider.js",
+ "default": "./dist/src/public/sandbox/provider.js"
+ },
"./sandbox/docker": {
"types": "./dist/src/public/sandbox/docker.d.ts",
"import": "./dist/src/public/sandbox/docker.js",
diff --git a/packages/eve/src/cli/commands/build.ts b/packages/eve/src/cli/commands/build.ts
index 1b414a550..27dad7991 100644
--- a/packages/eve/src/cli/commands/build.ts
+++ b/packages/eve/src/cli/commands/build.ts
@@ -50,13 +50,15 @@ export function registerBuildCommand(input: {
const projectContext = await input.applicationContext.resolveAgent();
if (projectContext.kind === "workspace") {
- if (options.profile !== undefined || options.skipSandboxPrewarm === true) {
+ if (options.profile !== undefined) {
throw new Error(
- "Workspace builds do not support --profile or --skip-sandbox-prewarm. Run those options from an individual agent directory.",
+ "Workspace builds do not support --profile. Run it from an individual agent directory.",
);
}
const { buildAgentWorkspace } = await import("#internal/vercel/build-agent-workspace.js");
- const outputDir = await buildAgentWorkspace(projectContext.workspace);
+ const outputDir = await buildAgentWorkspace(projectContext.workspace, {
+ skipSandboxPrewarm: options.skipSandboxPrewarm,
+ });
input.logger.log(
renderCliTaggedLine(theme, {
message: `built output at ${outputDir}`,
diff --git a/packages/eve/src/cli/commands/info.test.ts b/packages/eve/src/cli/commands/info.test.ts
index b4338b801..438539b25 100644
--- a/packages/eve/src/cli/commands/info.test.ts
+++ b/packages/eve/src/cli/commands/info.test.ts
@@ -68,6 +68,7 @@ async function makeCompiledState(): Promise<CompileAgentResult> {
discoveryManifestPath: `${APP_ROOT}/.eve/discovery/agent-discovery-manifest.json`,
discoveryDirectoryPath: `${APP_ROOT}/.eve/discovery`,
moduleMapPath: `${APP_ROOT}/.eve/compile/module-map.mjs`,
+ sandboxPreparedArtifactsPath: `${APP_ROOT}/.eve/compile/sandbox-prepared-artifacts.json`,
},
project: { agentRoot: AGENT_ROOT, appRoot: APP_ROOT, layout: "nested" },
};
diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.ts
index ef5680b31..1b6c9a4da 100644
--- a/packages/eve/src/cli/dev/tui/terminal-renderer.ts
+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.ts
@@ -1549,7 +1549,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
}
const status = subagentToolStatus(update.status);
- // Subagents share the session's sandbox, so their reads and writes feed
+ // Subagents reuse the session's sandbox, so their reads and writes feed
// the same file-content cache and their write blocks diff the same way.
const presentation =
update.status === "preparing"
diff --git a/packages/eve/src/client/agent-info-schema.ts b/packages/eve/src/client/agent-info-schema.ts
index 8cbe0f0db..736565395 100644
--- a/packages/eve/src/client/agent-info-schema.ts
+++ b/packages/eve/src/client/agent-info-schema.ts
@@ -212,12 +212,9 @@ const memory = source
const sandbox = source
.extend({
- backendKind: z.string().optional(),
- description: z.string().optional(),
- hasBootstrap: z.boolean(),
- hasOnSession: z.boolean(),
- revalidationKey: z.string().optional(),
- sourceHash: z.string().optional(),
+ provider: z.string().optional(),
+ environmentExportName: z.string().optional(),
+ revisionHash: z.string(),
})
.strict();
@@ -272,7 +269,7 @@ const compositionDiagnostic = z
})
.strict();
-/** Runtime contract for the authoritative `/eve/v1/info` v4 response. */
+/** Runtime contract for the authoritative `/eve/v1/info` v5 response. */
export const AgentInfoResultSchema = z
.object({
agent: z
@@ -314,7 +311,7 @@ export const AgentInfoResultSchema = z
skills: z.object({ dynamic: z.array(dynamicResolver), static: z.array(skill) }).strict(),
subagents: z.object({ local: z.array(subagent), total: z.number() }).strict(),
tools: z.object({ dynamic: z.array(dynamicResolver), static: z.array(tool) }).strict(),
- version: z.literal(4),
+ version: z.literal(5),
workspace: z.object({ resourceRoot: z.unknown(), rootEntries: z.array(z.string()) }).strict(),
})
.strict()
diff --git a/packages/eve/src/compiler/artifacts.ts b/packages/eve/src/compiler/artifacts.ts
index 4bdc3887f..1cfaf90f2 100644
--- a/packages/eve/src/compiler/artifacts.ts
+++ b/packages/eve/src/compiler/artifacts.ts
@@ -22,6 +22,7 @@ import {
import { createCompiledModuleMapSource } from "#compiler/module-map.js";
import { compileAgentManifest } from "#compiler/normalize-manifest.js";
import { materializeWorkspaceResources } from "#compiler/workspace-resources.js";
+import { createSandboxPreparedArtifactsManifest } from "#shared/sandbox-prepared-artifacts.js";
/**
* Stable diagnostics artifact kind emitted by the compiler.
@@ -55,6 +56,7 @@ export interface CompilerArtifactPaths {
discoveryManifestPath: string;
discoveryDirectoryPath: string;
moduleMapPath: string;
+ sandboxPreparedArtifactsPath: string;
}
/**
@@ -156,6 +158,7 @@ function resolveCompilerArtifactPathsAt(
discoveryManifestPath: join(discoveryDirectoryPath, "agent-discovery-manifest.json"),
discoveryDirectoryPath,
moduleMapPath: join(compileDirectoryPath, "module-map.mjs"),
+ sandboxPreparedArtifactsPath: join(compileDirectoryPath, "sandbox-prepared-artifacts.json"),
};
}
@@ -261,6 +264,9 @@ export async function writeCompilerArtifacts(
paths: publishedPaths,
});
const metadataJson = serializeArtifactJson(metadata);
+ const sandboxPreparedArtifactsJson = serializeArtifactJson(
+ createSandboxPreparedArtifactsManifest([]),
+ );
await mkdir(paths.discoveryDirectoryPath, {
recursive: true,
@@ -274,6 +280,7 @@ export async function writeCompilerArtifacts(
writeFile(paths.discoveryManifestPath, discoveryManifestJson),
writeFile(paths.moduleMapPath, moduleMapSource),
writeFile(paths.compileMetadataPath, metadataJson),
+ writeFile(paths.sandboxPreparedArtifactsPath, sandboxPreparedArtifactsJson),
]);
return {
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index 8c093c6ef..156a9e880 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -22,8 +22,8 @@ interface ExtensionCapabilityContract {
const EXTENSION_CAPABILITY_CONTRACTS = {
extension: { current: 1, supported: [1], dropped: {} },
tool: {
- current: 53,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 53],
+ current: 54,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 54],
dropped: {
14: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
15: "TaskExec replaces stageEffect with send",
@@ -58,12 +58,13 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
50: "Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.",
51: "Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.",
52: "Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.",
+ 53: "Sandbox sessions no longer expose core identity and mutable networking is provider-specific.",
},
},
dynamicTool: {
- current: 51,
+ current: 52,
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, 51,
+ 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,
],
dropped: {
21: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
@@ -92,11 +93,12 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
48: "Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.",
49: "Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.",
50: "Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.",
+ 51: "Sandbox sessions no longer expose core identity and mutable networking is provider-specific.",
},
},
channel: {
- current: 28,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 27, 28],
+ current: 29,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 29],
dropped: {
12: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
19: "Continuation rekey was removed; channel extensions must use additive continuation.alias instead.",
@@ -107,6 +109,8 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
24: "Task views no longer expose executor bindings; background work is owned by workflow runs.",
25: "Task views no longer expose executor bindings; background work is owned by workflow runs.",
26: "Task views no longer expose executor bindings; background work is owned by workflow runs.",
+ 27: "Sandbox sessions no longer expose core identity and mutable networking is provider-specific.",
+ 28: "Sandbox sessions no longer expose core identity and mutable networking is provider-specific.",
},
},
schedule: {
@@ -128,16 +132,17 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
connection: {
- current: 23,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23],
+ current: 24,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24],
dropped: {
9: "Dynamic connection resolvers no longer receive conversation or channel continuation data",
10: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
+ 23: "Sandbox sessions no longer expose core identity and mutable networking is provider-specific.",
},
},
hook: {
- current: 24,
- supported: [10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24],
+ current: 25,
+ supported: [10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 25],
dropped: {
1: "Model identity moved from session.started runtime metadata to step.started call attribution.",
2: "Model identity moved from session.started runtime metadata to step.started call attribution.",
@@ -149,6 +154,7 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
8: "Model identity moved from session.started runtime metadata to step.started call attribution.",
9: "Model identity moved from session.started runtime metadata to step.started call attribution.",
16: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
+ 24: "Sandbox sessions no longer expose core identity and mutable networking is provider-specific.",
},
},
skill: { current: 1, supported: [1], dropped: {} },
@@ -168,7 +174,13 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
config: { current: 1, supported: [1], dropped: {} },
- state: { current: 6, supported: [1, 2, 3, 4, 5, 6], dropped: {} },
+ state: {
+ current: 7,
+ supported: [1, 2, 3, 4, 5, 7],
+ dropped: {
+ 6: "Sandbox sessions no longer expose core identity and mutable networking is provider-specific.",
+ },
+ },
} as const satisfies Record<string, ExtensionCapabilityContract>;
/** One independently versioned extension-facing contract. */
diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.ts
index 306509330..c6ce21b87 100644
--- a/packages/eve/src/compiler/manifest.ts
+++ b/packages/eve/src/compiler/manifest.ts
@@ -55,7 +55,7 @@ export const ROOT_COMPILED_AGENT_NODE_ID = "__root__";
/**
* Current compiled manifest schema version.
*/
-export const COMPILED_AGENT_MANIFEST_VERSION = 50;
+export const COMPILED_AGENT_MANIFEST_VERSION = 51;
/**
* Compiled channel entry preserved in the compiled manifest.
@@ -725,21 +725,13 @@ const compiledScheduleDefinitionSchema = z.discriminatedUnion("sourceKind", [
const compiledSandboxDefinitionSchema = z
.object({
- /**
- * Stable name of the authored backend (`"local"`, `"vercel"`,
- * `"local-just-bash"`, or a custom backend's name), captured at
- * compile time so build pipelines can make backend-aware decisions
- * (for example including the optional just-bash engine package in
- * hosted output). Absent when the definition omits `backend` or the
- * backend's name could not be resolved at compile time.
- */
- backendName: z.string().optional(),
- description: z.string().optional(),
+ /** Stable provider name from the exported environment. */
+ providerName: z.string().optional(),
+ environmentExportName: z.string().optional(),
inheritsParent: z.boolean().optional(),
exportName: z.string().optional(),
logicalPath: z.string(),
- revalidationKey: z.string().optional(),
- sourceHash: z.string(),
+ revisionHash: z.string(),
sourceId: z.string(),
sourceKind: z.literal("module"),
})
diff --git a/packages/eve/src/compiler/normalize-helpers.ts b/packages/eve/src/compiler/normalize-helpers.ts
index 66bd316a7..c6c66c8bd 100644
--- a/packages/eve/src/compiler/normalize-helpers.ts
+++ b/packages/eve/src/compiler/normalize-helpers.ts
@@ -13,7 +13,7 @@ import {
} from "#compiler/source-graph.js";
import type { CompiledBindingNamespaceLoader } from "#compiler/load-binding-namespace.js";
-const SANDBOX_PARENT_DEFINITION_MARKER = Symbol.for("eve.sandbox-parent-definition");
+const SANDBOX_SELECTOR_MARKER = Symbol.for("eve.sandbox-selector");
/**
* Shared compile-time context threaded through every per-primitive
@@ -74,12 +74,12 @@ export async function loadModuleBackedDefinition(input: {
const moduleNamespace = await input.loadNamespace(input.source.sourceId);
const exportValue = getAuthoredModuleExport(moduleNamespace, input.source);
- // defineSandbox marks parent selectors so they remain distinguishable from
- // zero-argument module factories without relying on JavaScript function arity.
+ // Sandbox selectors execute only when a runtime session opens its environment.
+ // Keep them distinguishable from zero-argument definition factories at compile time.
if (
input.kind === "sandbox" &&
typeof exportValue === "function" &&
- Reflect.get(exportValue, SANDBOX_PARENT_DEFINITION_MARKER) === true
+ Reflect.get(exportValue, SANDBOX_SELECTOR_MARKER) === true
) {
return exportValue;
}
@@ -89,7 +89,7 @@ export async function loadModuleBackedDefinition(input: {
} catch (error) {
if (input.kind === "sandbox" && typeof exportValue === "function") {
throw new Error(
- `Failed to execute the sandbox export "${input.source.exportName ?? "default"}" from "${input.displayPath ?? input.source.logicalPath}" as a zero-argument definition factory. Parent-sharing callbacks must be passed to defineSandbox(...): ${toErrorMessage(error)}`,
+ `Failed to execute the sandbox export "${input.source.exportName ?? "default"}" from "${input.displayPath ?? input.source.logicalPath}" as a zero-argument definition factory. Runtime selectors must be passed to defineSandbox(...): ${toErrorMessage(error)}`,
);
}
throw new Error(
diff --git a/packages/eve/src/compiler/normalize-sandbox.scenario.test.ts b/packages/eve/src/compiler/normalize-sandbox.scenario.test.ts
index 8f68e5968..33fd6878c 100644
--- a/packages/eve/src/compiler/normalize-sandbox.scenario.test.ts
+++ b/packages/eve/src/compiler/normalize-sandbox.scenario.test.ts
@@ -1,64 +1,53 @@
import { join } from "node:path";
-
import { describe, expect, it } from "vitest";
-
import { compileAgentManifest } from "#compiler/normalize-manifest.js";
import { discoverAgent } from "#discover/discover-agent.js";
import { useScenarioApp } from "#internal/testing/scenario-app.js";
-
describe("sandbox compilation", () => {
const scenarioApp = useScenarioApp();
-
- it("preserves zero-argument sandbox definition factories", async () => {
+ it("compiles an exported environment and selector", async () => {
const app = await scenarioApp({
files: {
- "agent/sandbox.ts": "export default () => ({ description: 'factory sandbox' });\n",
+ "agent/sandbox.ts": [
+ 'import { DefaultSandbox, defineSandbox } from "eve/sandbox";',
+ "export const environment = DefaultSandbox.environment();",
+ "export default defineSandbox(() => environment.open());",
+ ].join("\n"),
},
- name: "sandbox-definition-factory",
+ installDependencies: true,
+ name: "sandbox-environment",
});
-
const discovered = await discoverAgent({
agentRoot: join(app.appRoot, "agent"),
appRoot: app.appRoot,
});
const manifest = await compileAgentManifest(discovered.manifest);
-
expect(manifest.sandbox).toMatchObject({
- description: "factory sandbox",
+ environmentExportName: "environment",
inheritsParent: undefined,
});
});
-
- it("compiles managed child resources alongside the parent selector for runtime rejection", async () => {
+ it("compiles managed child resources for runtime rejection", async () => {
const app = await scenarioApp({
files: {
"agent/subagents/foo/agent.ts":
- "export default { description: 'foo', model: 'openai/gpt-5.4' };\n",
+ "export default { description: 'foo', model: 'openai/gpt-5.4' };",
"agent/subagents/foo/description.md": "foo\n",
- "agent/subagents/foo/sandbox/sandbox.ts": [
- 'import { defineSandbox } from "eve/sandbox";',
- "export default defineSandbox((...args) => args[0].parent.sandbox);",
- "",
- ].join("\n"),
+ "agent/subagents/foo/sandbox/sandbox.ts":
+ 'import { defineParentSandbox } from "eve/sandbox"; export default defineParentSandbox();',
"agent/subagents/foo/sandbox/workspace/bar.txt": "child seed\n",
},
installDependencies: true,
name: "inherited-sandbox-child-resources",
});
-
const discovered = await discoverAgent({
agentRoot: join(app.appRoot, "agent"),
appRoot: app.appRoot,
});
- const manifest = await compileAgentManifest(discovered.manifest);
- const child = manifest.subagents[0]!.agent;
+ const child = (await compileAgentManifest(discovered.manifest)).subagents[0]!.agent;
expect(child).toMatchObject({
sandbox: { inheritsParent: true },
workspaceResourceRoot: { rootEntries: ["bar.txt"] },
});
- expect(child.bindings[child.sandbox.sourceId]?.usage).toEqual({
- compile: true,
- runtimeEntry: false,
- });
});
});
diff --git a/packages/eve/src/compiler/normalize-sandbox.test.ts b/packages/eve/src/compiler/normalize-sandbox.test.ts
index 5c740a40c..da245e685 100644
--- a/packages/eve/src/compiler/normalize-sandbox.test.ts
+++ b/packages/eve/src/compiler/normalize-sandbox.test.ts
@@ -1,44 +1,35 @@
import { describe, expect, it } from "vitest";
+import { defineParentSandbox, defineSandbox } from "#public/definitions/sandbox.js";
+import { defineSandboxProvider } from "#shared/sandbox-provider.js";
+
+const provider = defineSandboxProvider({
+ name: "test",
+ environment: () => ({
+ async prepare() {
+ return null;
+ },
+ async resume() {
+ throw new Error("unused");
+ },
+ async start() {
+ throw new Error("unused");
+ },
+ }),
+});
-import { resolveParentSandboxSelector } from "#compiler/normalize-sandbox.js";
-import { defineSandbox } from "#public/definitions/sandbox.js";
-
-describe("resolveParentSandboxSelector", () => {
- it("recognizes a callback that returns parent.sandbox", async () => {
- const selector = ({ parent }: { parent: { sandbox: unknown } }) => parent.sandbox;
-
- await expect(resolveParentSandboxSelector(selector, "invalid sandbox")).resolves.toBe(true);
- });
-
- it("supports marked rest-parameter callbacks without relying on function arity", async () => {
- const selector = defineSandbox((...args) => {
- if (args[0].parent === null) throw new Error("parent required");
- return args[0].parent.sandbox;
- });
-
- expect(selector.length).toBe(0);
- await expect(resolveParentSandboxSelector(selector, "invalid sandbox")).resolves.toBe(true);
- });
-
- it("rejects callbacks that return anything else", async () => {
- await expect(
- resolveParentSandboxSelector((_context: unknown) => ({ nope: true }), "invalid sandbox"),
- ).rejects.toThrow(
- "The callback passed to defineSandbox(...) must return parent.sandbox. Export a sandbox definition object for an independent sandbox.",
- );
+describe("sandbox definitions", () => {
+ it("marks selectors", () => {
+ const environment = provider.environment();
+ expect(
+ Reflect.get(
+ defineSandbox(() => environment.open()),
+ Symbol.for("eve.sandbox-selector"),
+ ),
+ ).toBe(true);
});
-
- it("reports authored callback errors", async () => {
- await expect(
- resolveParentSandboxSelector(() => {
- throw new Error("authored failure");
- }, "invalid sandbox"),
- ).rejects.toThrow(
- "The callback passed to defineSandbox(...) threw while selecting parent.sandbox: authored failure",
+ it("marks parent selection", () => {
+ expect(Reflect.get(defineParentSandbox(), Symbol.for("eve.sandbox-parent-definition"))).toBe(
+ true,
);
});
-
- it("leaves object definitions unchanged", async () => {
- await expect(resolveParentSandboxSelector({}, "invalid sandbox")).resolves.toBe(false);
- });
});
diff --git a/packages/eve/src/compiler/normalize-sandbox.ts b/packages/eve/src/compiler/normalize-sandbox.ts
index a06fae222..6bddc26dc 100644
--- a/packages/eve/src/compiler/normalize-sandbox.ts
+++ b/packages/eve/src/compiler/normalize-sandbox.ts
@@ -1,138 +1,42 @@
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
-
-import type { SandboxSourceRef } from "#discover/manifest.js";
-import { normalizeSandboxDefinition } from "#internal/authored-definition/sandbox.js";
import type { CompiledSandboxDefinition } from "#compiler/manifest.js";
-import {
- loadModuleBackedDefinition,
- type ModuleBackedDefinitionLoadOptions,
-} from "#compiler/normalize-helpers.js";
-import { toErrorMessage } from "#shared/errors.js";
+import type { ModuleBackedDefinitionLoadOptions } from "#compiler/normalize-helpers.js";
+import type { SandboxSourceRef } from "#discover/manifest.js";
+import { getAuthoredModuleExport } from "#internal/authored-module.js";
+import { getBoundSandboxEnvironment, isSandboxEnvironment } from "#shared/sandbox-environment.js";
+
+const PARENT = Symbol.for("eve.sandbox-parent-definition");
+const SELECTOR = Symbol.for("eve.sandbox-selector");
-/**
- * Compiles one authored sandbox module into the normalized sandbox
- * definition stored on the compiled agent manifest.
- */
export async function compileSandboxDefinition(
_agentRoot: string,
source: SandboxSourceRef,
options: ModuleBackedDefinitionLoadOptions,
): Promise<CompiledSandboxDefinition> {
- const message = `Expected the sandbox export "${source.exportName ?? "default"}" from "${source.logicalPath}" to match the public eve shape.`;
- const loaded = await loadModuleBackedDefinition({
- binding: options.binding,
- kind: "sandbox",
- loadNamespace: options.loadNamespace,
- source,
- });
- const inheritsParent = await resolveParentSandboxSelector(loaded, message);
- const normalized = normalizeSandboxDefinition(inheritsParent ? {} : loaded, message);
- const revalidationKey =
- normalized.revalidationKey === undefined
- ? undefined
- : await resolveSandboxRevalidationKey({
- message,
- revalidationKey: normalized.revalidationKey,
- source,
- });
-
+ const namespace = await options.loadNamespace(source.sourceId);
+ const selector = getAuthoredModuleExport(namespace, source);
+ if (typeof selector !== "function" || Reflect.get(selector, SELECTOR) !== true)
+ throw new Error(`Expected sandbox "${source.logicalPath}" to default-export defineSandbox().`);
+ const inheritsParent = Reflect.get(selector, PARENT) === true;
+ const candidate = isSandboxEnvironment(namespace.environment)
+ ? namespace.environment
+ : getBoundSandboxEnvironment(selector);
+ if (!inheritsParent && candidate === undefined)
+ throw new Error(`Sandbox "${source.logicalPath}" must export an environment.`);
+ const authoredSource =
+ options.binding.backing.kind === "programmatic"
+ ? (options.binding.backing.semanticRevision ?? options.binding.backing.revision)
+ : await readFile(options.binding.backing.sourcePath);
+ const revision = createHash("sha256").update("sandbox-source\0").update(authoredSource);
return {
- backendName: resolveCompiledBackendName(normalized.backend),
- description: normalized.description,
- inheritsParent: inheritsParent || undefined,
+ providerName: candidate?.provider,
+ environmentExportName: isSandboxEnvironment(namespace.environment) ? "environment" : undefined,
exportName: source.exportName,
+ inheritsParent: inheritsParent || undefined,
logicalPath: source.logicalPath,
- revalidationKey,
- sourceHash: await resolveSandboxSourceHash(options.binding),
+ revisionHash: revision.digest("hex"),
sourceId: source.sourceId,
sourceKind: "module",
};
}
-
-/**
- * Captures the authored backend's stable name into the manifest.
- *
- * Reading `.name` forces a lazily-wrapped backend factory exactly once
- * at compile time; a factory that throws here is tolerated (it already
- * fails at runtime, where the error surfaces with full context) and
- * simply leaves the name unrecorded.
- */
-const PARENT_SANDBOX_VALUE = Object.freeze({ __eveSandboxParentValue: Symbol("parent") });
-
-export async function resolveParentSandboxSelector(
- value: unknown,
- message: string,
-): Promise<boolean> {
- if (typeof value !== "function") {
- return false;
- }
-
- let selected: unknown;
- try {
- selected = await value({ parent: { sandbox: PARENT_SANDBOX_VALUE } });
- } catch (error) {
- throw new Error(
- `${message} The callback passed to defineSandbox(...) threw while selecting parent.sandbox: ${toErrorMessage(error)}`,
- );
- }
-
- if (selected !== PARENT_SANDBOX_VALUE) {
- throw new Error(
- `${message} The callback passed to defineSandbox(...) must return parent.sandbox. Export a sandbox definition object for an independent sandbox.`,
- );
- }
- return true;
-}
-
-function resolveCompiledBackendName(
- backend: { readonly name: string } | undefined,
-): string | undefined {
- if (backend === undefined) {
- return undefined;
- }
- try {
- return backend.name;
- } catch {
- return undefined;
- }
-}
-
-async function resolveSandboxRevalidationKey(input: {
- readonly message: string;
- readonly revalidationKey: () => Promise<string> | string;
- readonly source: SandboxSourceRef;
-}): Promise<string> {
- let resolved: unknown;
- try {
- resolved = await input.revalidationKey();
- } catch (error) {
- throw new Error(
- `${input.message} Failed to execute the "revalidationKey" function from "${input.source.logicalPath}": ${toErrorMessage(error)}`,
- );
- }
-
- if (typeof resolved !== "string") {
- throw new Error(`${input.message} The "revalidationKey" function must return a string.`);
- }
-
- if (resolved.trim().length === 0) {
- throw new Error(
- `${input.message} The "revalidationKey" function must return a non-empty string.`,
- );
- }
-
- return resolved;
-}
-
-async function resolveSandboxSourceHash(
- binding: ModuleBackedDefinitionLoadOptions["binding"],
-): Promise<string> {
- if (binding.backing.kind === "programmatic") {
- return createHash("sha256")
- .update(binding.backing.semanticRevision ?? binding.backing.revision)
- .digest("hex");
- }
- const content = await readFile(binding.backing.sourcePath);
- return createHash("sha256").update(content).digest("hex");
-}
diff --git a/packages/eve/src/compiler/workspace-resources.ts b/packages/eve/src/compiler/workspace-resources.ts
index 8a6cd9849..83ed04f1c 100644
--- a/packages/eve/src/compiler/workspace-resources.ts
+++ b/packages/eve/src/compiler/workspace-resources.ts
@@ -94,6 +94,10 @@ async function materializeNode<TManifest extends CompiledAgentResources>(input:
await mkdir(nodeRoot, { recursive: true });
const workspaceRoot = join(nodeRoot, RESOURCE_WORKSPACE_DIRECTORY);
+ await Promise.all([
+ mkdir(workspaceRoot, { recursive: true }),
+ mkdir(join(nodeRoot, RESOURCE_SKILLS_DIRECTORY), { recursive: true }),
+ ]);
for (const workspace of input.manifest.sandboxWorkspaces) {
await copyDirectoryContents({
sourcePath: workspace.sourcePath,
diff --git a/packages/eve/src/context/accessors.integration.test.ts b/packages/eve/src/context/accessors.integration.test.ts
index 1e260849f..e70c374f1 100644
--- a/packages/eve/src/context/accessors.integration.test.ts
+++ b/packages/eve/src/context/accessors.integration.test.ts
@@ -98,7 +98,6 @@ describe("buildCallbackContext – getSandbox", () => {
await live.run({ command: "echo ready" });
expect(sandbox.commandLog).toEqual(["echo ready"]);
- expect(live.id).toBe(sandboxId);
});
it("passes file operations through the expanded session surface", async () => {
diff --git a/packages/eve/src/context/build-callback-context.test.ts b/packages/eve/src/context/build-callback-context.test.ts
new file mode 100644
index 000000000..40a3d5393
--- /dev/null
+++ b/packages/eve/src/context/build-callback-context.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { withRuntimeSandboxLifecycle } from "#context/build-callback-context.js";
+
+describe("withRuntimeSandboxLifecycle", () => {
+ it("preserves custom methods and private receivers on frozen provider sessions", async () => {
+ class CustomSession {
+ readonly #token = "custom-session-ok";
+ probe() {
+ return this.#token;
+ }
+ }
+ const target = Object.freeze(new CustomSession());
+ const deleteSandbox = vi.fn(async () => {});
+ const stop = vi.fn(async () => {});
+
+ const session = withRuntimeSandboxLifecycle(
+ target as never,
+ deleteSandbox,
+ stop,
+ ) as CustomSession & {
+ delete(): Promise<void>;
+ stop(): Promise<void>;
+ };
+
+ expect(session.probe()).toBe("custom-session-ok");
+ await session.delete();
+ await session.stop();
+ expect(deleteSandbox).toHaveBeenCalledTimes(1);
+ expect(stop).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/eve/src/context/build-callback-context.ts b/packages/eve/src/context/build-callback-context.ts
index 99abe4e66..3d5c969e2 100644
--- a/packages/eve/src/context/build-callback-context.ts
+++ b/packages/eve/src/context/build-callback-context.ts
@@ -61,25 +61,30 @@ export function buildCallbackContext(): SessionContext {
};
}
-function withRuntimeSandboxLifecycle(
- sandbox: SandboxSession,
+export function withRuntimeSandboxLifecycle<Session extends SandboxSession>(
+ sandbox: Session,
deleteSandbox: RuntimeSandboxSession["delete"],
stop: () => Promise<void>,
-): RuntimeSandboxSession {
- return {
- delete: deleteSandbox,
- id: sandbox.id,
- readBinaryFile: (options) => sandbox.readBinaryFile(options),
- readFile: (options) => sandbox.readFile(options),
- readTextFile: (options) => sandbox.readTextFile(options),
- removePath: (options) => sandbox.removePath(options),
- resolvePath: (path) => sandbox.resolvePath(path),
- run: (options) => sandbox.run(options),
- setNetworkPolicy: (policy) => sandbox.setNetworkPolicy(policy),
- spawn: (options) => sandbox.spawn(options),
- stop,
- writeBinaryFile: (options) => sandbox.writeBinaryFile(options),
- writeFile: (options) => sandbox.writeFile(options),
- writeTextFile: (options) => sandbox.writeTextFile(options),
- };
+): Session & Pick<RuntimeSandboxSession, "delete" | "stop"> {
+ return new Proxy(Object.create(null) as object, {
+ get(_proxyTarget, property) {
+ if (property === "delete") return deleteSandbox;
+ if (property === "stop") return stop;
+ const value = Reflect.get(sandbox, property, sandbox);
+ return typeof value === "function" ? value.bind(sandbox) : value;
+ },
+ getOwnPropertyDescriptor(_proxyTarget, property) {
+ if (property === "delete" || property === "stop") {
+ return { configurable: true, enumerable: true, writable: false };
+ }
+ const descriptor = Reflect.getOwnPropertyDescriptor(sandbox, property);
+ return descriptor === undefined ? undefined : { ...descriptor, configurable: true };
+ },
+ has(_proxyTarget, property) {
+ return property === "delete" || property === "stop" || Reflect.has(sandbox, property);
+ },
+ ownKeys() {
+ return [...new Set([...Reflect.ownKeys(sandbox), "delete", "stop"])];
+ },
+ }) as Session & Pick<RuntimeSandboxSession, "delete" | "stop">;
}
diff --git a/packages/eve/src/context/providers/sandbox.test.ts b/packages/eve/src/context/providers/sandbox.test.ts
index e5449e90e..452aefa8d 100644
--- a/packages/eve/src/context/providers/sandbox.test.ts
+++ b/packages/eve/src/context/providers/sandbox.test.ts
@@ -87,7 +87,7 @@ describe("sandboxProvider", () => {
);
});
- it("tags sandbox backend resources with agent, channel, and session id", async () => {
+ it("passes the owning session identity to sandbox access", async () => {
const ctx = new ContextContainer();
const registry: RuntimeSandboxRegistry = createStubSandboxRegistry();
@@ -100,11 +100,7 @@ describe("sandboxProvider", () => {
expect(ensureSandboxAccess).toHaveBeenCalledWith(
expect.objectContaining({
ownsSandbox: true,
- tags: {
- agent: "weather-agent",
- channel: "slack",
- sessionId: "session_1",
- },
+ sessionId: "session_1",
}),
);
});
diff --git a/packages/eve/src/context/providers/sandbox.ts b/packages/eve/src/context/providers/sandbox.ts
index c1f7ad81b..2afbe1c16 100644
--- a/packages/eve/src/context/providers/sandbox.ts
+++ b/packages/eve/src/context/providers/sandbox.ts
@@ -1,15 +1,9 @@
import { ensureSandboxAccess } from "#execution/sandbox/ensure.js";
import type { HarnessSession } from "#harness/types.js";
import type { SandboxAccess, SandboxState } from "#sandbox/state.js";
-import { type ChannelAdapter, getAdapterKind } from "#channel/adapter.js";
import type { ContextContainer } from "#context/container.js";
-import { contextStorage } from "#context/container.js";
import { SandboxKey, SessionIdKey } from "#context/keys.js";
-import {
- BundleKey,
- ChannelKey,
- type CompiledBundle,
-} from "#runtime/sessions/runtime-context-keys.js";
+import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
import { getActiveRuntimeNode } from "#context/node.js";
import type { FrameworkContextProvider } from "#context/provider.js";
@@ -25,25 +19,20 @@ export const sandboxProvider: FrameworkContextProvider<SandboxAccess> = {
const channel = ctx.get(ChannelKey);
const adapterState = channel?.state as Record<string, unknown> | undefined;
const parentSandboxState = adapterState?.parentSandboxState as SandboxState | undefined;
- const inheritsParent = registry.sandbox?.definition.inheritsParent === true;
- const sharedSandboxSessionId = adapterState?.sandboxSessionId as string | undefined;
- const sharesSandbox = inheritsParent || sharedSandboxSessionId !== undefined;
- const sandboxSessionId = sharesSandbox ? (sharedSandboxSessionId ?? sessionId) : sessionId;
+ const inheritsParent = registry.sandbox?.definition.kind === "parent";
+ const ownerSandboxSessionId = adapterState?.sandboxSessionId as string | undefined;
+ const reusesOwnerSandbox = inheritsParent || ownerSandboxSessionId !== undefined;
+ const sandboxSessionId = reusesOwnerSandbox ? (ownerSandboxSessionId ?? sessionId) : sessionId;
return {
value: await ensureSandboxAccess({
compiledArtifactsSource: bundle.compiledArtifactsSource,
nodeId: node.nodeId,
- ownsSandbox: !sharesSandbox,
+ ownsSandbox: !reusesOwnerSandbox,
registry,
- runOnSession: async (callback) => await contextStorage.run(ctx, callback),
sessionId: sandboxSessionId,
- state: session.sandboxState ?? (sharesSandbox ? parentSandboxState : undefined) ?? null,
- tags: {
- agent: resolveTagAgentName({ bundle, node }),
- channel: resolveTagChannelKind(channel),
- sessionId,
- },
+ state:
+ session.sandboxState ?? (reusesOwnerSandbox ? parentSandboxState : undefined) ?? null,
}),
};
},
@@ -53,27 +42,3 @@ export const sandboxProvider: FrameworkContextProvider<SandboxAccess> = {
return { ...session, sandboxState: state };
},
};
-
-function resolveTagAgentName(input: {
- readonly bundle: CompiledBundle;
- readonly node: ReturnType<typeof getActiveRuntimeNode>;
-}): string {
- const partialNode = input.node as {
- readonly agent?: { readonly config?: { readonly name?: string } };
- readonly nodeId?: string;
- };
- const partialBundle = input.bundle as {
- readonly resolvedAgent?: { readonly config?: { readonly name?: string } };
- };
-
- return (
- partialNode.agent?.config?.name ??
- partialBundle.resolvedAgent?.config?.name ??
- partialNode.nodeId ??
- "unknown"
- );
-}
-
-function resolveTagChannelKind(channel: ChannelAdapter | undefined): string {
- return channel === undefined ? "unknown" : getAdapterKind(channel);
-}
diff --git a/packages/eve/src/context/session-context.ts b/packages/eve/src/context/session-context.ts
index 596ef0a94..cae3cd5c4 100644
--- a/packages/eve/src/context/session-context.ts
+++ b/packages/eve/src/context/session-context.ts
@@ -8,7 +8,7 @@ export type { SessionAuth, SessionParent, SessionTurn };
* Shared runtime context available to all authored callbacks that run
* inside the ALS-scoped harness step (tools, hooks, channel events).
*
- * Non-ALS callbacks (schedule `run`, sandbox `bootstrap`/`onSession`,
+ * Non-ALS callbacks (schedule `run` and provider environment preparation,
* instrumentation `setup`) do not receive this context. They get
* domain-specific arguments instead.
*/
diff --git a/packages/eve/src/discover/sandbox.integration.test.ts b/packages/eve/src/discover/sandbox.integration.test.ts
index 68551cd97..53236040a 100644
--- a/packages/eve/src/discover/sandbox.integration.test.ts
+++ b/packages/eve/src/discover/sandbox.integration.test.ts
@@ -51,6 +51,25 @@ describe("discoverSandboxSource (memory)", () => {
expect(result.sandboxWorkspace).toBeNull();
});
+ it("accepts a Dockerfile without a sandbox module or workspace", async () => {
+ const project = buildMemoryAgentProject({
+ agentFiles: {
+ "sandbox/Dockerfile": "FROM ghcr.io/vercel/eve:latest\n",
+ },
+ });
+
+ const rootEntries = await readSortedDirectoryEntries(project.source, project.agentRoot);
+ const result = await discoverSandboxSource({
+ rootEntries,
+ rootPath: project.agentRoot,
+ source: project.source,
+ });
+
+ expect(result.diagnostics).toEqual([]);
+ expect(result.sandbox).toBeNull();
+ expect(result.sandboxWorkspace).toBeNull();
+ });
+
it("discovers a workspace folder without a sandbox module", async () => {
const project = buildMemoryAgentProject({
agentFiles: {
diff --git a/packages/eve/src/discover/sandbox.ts b/packages/eve/src/discover/sandbox.ts
index ec03bc830..04627c756 100644
--- a/packages/eve/src/discover/sandbox.ts
+++ b/packages/eve/src/discover/sandbox.ts
@@ -97,6 +97,9 @@ export async function discoverSandboxSource(input: {
(folderEntry) =>
folderEntry.name === SANDBOX_WORKSPACE_DIRECTORY_NAME && folderEntry.isDirectory(),
);
+ const hasDockerfile = folderEntries.some(
+ (folderEntry) => folderEntry.name === "Dockerfile" && folderEntry.isFile(),
+ );
if (sandboxModuleCandidates.length > 1) {
diagnostics.push(
@@ -119,13 +122,13 @@ export async function discoverSandboxSource(input: {
const hasModule = moduleFileName !== undefined;
const hasWorkspace = workspaceFolderEntry !== undefined;
- if (!hasModule && !hasWorkspace) {
+ if (!hasModule && !hasWorkspace && !hasDockerfile) {
diagnostics.push(
createDiscoverErrorDiagnostic({
code: DISCOVER_SANDBOX_FOLDER_EMPTY,
message:
- `Sandbox folder "sandbox/" contains neither a "sandbox.<ext>" definition ` +
- `nor a "workspace/" subdirectory. Add one or the other, or remove the folder.`,
+ `Sandbox folder "sandbox/" contains no "Dockerfile", "sandbox.<ext>" definition, ` +
+ `or "workspace/" subdirectory. Add one or remove the folder.`,
sourcePath: directoryPath,
}),
);
diff --git a/packages/eve/src/evals/target.ts b/packages/eve/src/evals/target.ts
index 59b33db26..03e0835c7 100644
--- a/packages/eve/src/evals/target.ts
+++ b/packages/eve/src/evals/target.ts
@@ -189,7 +189,7 @@ async function waitForTargetHealth(client: Client, url: string): Promise<void> {
}
function assertAgentInfoShape(info: AgentInfoResult, url: string): void {
- if (info.kind !== "eve-agent-info" || info.version !== 4) {
+ if (info.kind !== "eve-agent-info" || info.version !== 5) {
throw new Error(`Eval target ${url} returned an unrecognized /eve/v1/info payload.`);
}
}
diff --git a/packages/eve/src/execution/coordination-dispatch-shared.ts b/packages/eve/src/execution/coordination-dispatch-shared.ts
index e9881ae70..e761e65b7 100644
--- a/packages/eve/src/execution/coordination-dispatch-shared.ts
+++ b/packages/eve/src/execution/coordination-dispatch-shared.ts
@@ -171,7 +171,7 @@ export async function prepareActionDispatch<PlanEntry>(input: {
readonly requests: DispatchBatch["requests"];
readonly session: RuntimeSession;
}) => readonly PlanEntry[];
- readonly planSharesSandbox?: (input: {
+ readonly planReusesOwnerSandbox?: (input: {
readonly bundle: CompiledBundle;
readonly plan: readonly PlanEntry[];
}) => boolean;
@@ -193,7 +193,7 @@ export async function prepareActionDispatch<PlanEntry>(input: {
const adapter = ctx.require(ChannelKey);
// A corrupt handle store and rejected actions must resolve before sandbox
- // initialization, which can provision backend resources and run onSession.
+ // initialization, which can provision provider resources and run preparation.
getAgentHandleStore(durableSession.state);
const plan = input.plan({
bundle,
@@ -203,7 +203,7 @@ export async function prepareActionDispatch<PlanEntry>(input: {
});
const sandboxSessionId = resolveActiveSandboxSessionId(adapter.state, session.sessionId);
- if (input.planSharesSandbox?.({ bundle, plan }) === true) {
+ if (input.planReusesOwnerSandbox?.({ bundle, plan }) === true) {
try {
const scoped = await withContextScope(ctx, session, async (enrichedSession) => {
await ctx.require(SandboxKey).get();
diff --git a/packages/eve/src/execution/harness-tool-execution.integration.test.ts b/packages/eve/src/execution/harness-tool-execution.integration.test.ts
index af5f428c9..e95fbfede 100644
--- a/packages/eve/src/execution/harness-tool-execution.integration.test.ts
+++ b/packages/eve/src/execution/harness-tool-execution.integration.test.ts
@@ -184,17 +184,16 @@ describe("authored tool execution", () => {
const live = await ctx.getSandbox();
await live.writeTextFile({ content: "sandbox-note", path: "note.txt" });
const content = await live.readTextFile({ path: "note.txt" });
- return { content, id: live.id };
+ return { content };
},
});
const runtime = await createTestRuntime({ tools: [sandboxTool] });
const result = (await runtime.runAsSession({ sandbox }, async () =>
runtime.executeTool(sandboxTool, {}),
- )) as { content: string; id: string };
+ )) as { content: string };
expect(result.content).toBe("sandbox-note");
- expect(result.id).toBe("sbx_tool");
expect(sandbox.files.get("/workspace/note.txt")).toBe("sandbox-note");
});
diff --git a/packages/eve/src/execution/legacy-session/snapshot.test.ts b/packages/eve/src/execution/legacy-session/snapshot.test.ts
index e1efb681f..e87b81a24 100644
--- a/packages/eve/src/execution/legacy-session/snapshot.test.ts
+++ b/packages/eve/src/execution/legacy-session/snapshot.test.ts
@@ -9,7 +9,7 @@ describe("conversation import", () => {
history: [{ role: "user", content: "Alice chose blue." }],
agent: { system: "old prompt" },
limits: { maxInputTokensPerSession: 40 },
- sandboxState: { initialized: false, session: null },
+ sandboxState: { session: null },
state: {
"app.color": "blue",
"eve.runtime.pendingCoordinationBatch": { callId: "old" },
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 d6b7f1974..b885d62c6 100644
--- a/packages/eve/src/execution/sandbox/abort-bound-session.test.ts
+++ b/packages/eve/src/execution/sandbox/abort-bound-session.test.ts
@@ -21,7 +21,6 @@ function createRecordingSession(calls: RecordedCall[]): SandboxSession {
const commandResult: SandboxCommandResult = { exitCode: 0, stderr: "", stdout: "" };
return {
- id: "sbx_recording",
resolvePath: (path: string) => `/workspace/${path}`,
run: async (options) => {
record("run", options.abortSignal);
@@ -93,7 +92,7 @@ describe("bindSandboxAbortSignal", () => {
expect(new Set(calls.map((call) => call.abortSignal)).size).toBe(calls.length);
});
- it("does not accumulate backend listeners on the bound signal", async () => {
+ it("does not accumulate provider listeners on the bound signal", async () => {
const calls: RecordedCall[] = [];
const recordingSession = createRecordingSession(calls);
const listenerSession: SandboxSession = {
@@ -155,8 +154,6 @@ describe("bindSandboxAbortSignal", () => {
const calls: RecordedCall[] = [];
const session = createRecordingSession(calls);
const bound = bindSandboxAbortSignal(session, new AbortController().signal);
-
- expect(bound.id).toBe("sbx_recording");
expect(bound.resolvePath("nested/file.txt")).toBe("/workspace/nested/file.txt");
});
});
diff --git a/packages/eve/src/execution/sandbox/abort-bound-session.ts b/packages/eve/src/execution/sandbox/abort-bound-session.ts
index 8c32c73eb..a64958733 100644
--- a/packages/eve/src/execution/sandbox/abort-bound-session.ts
+++ b/packages/eve/src/execution/sandbox/abort-bound-session.ts
@@ -22,7 +22,7 @@ export function bindSandboxAbortSignal<TSession extends SandboxSession>(
const compose = (callSignal: AbortSignal | undefined): AbortSignal =>
AbortSignal.any(callSignal === undefined ? [abortSignal] : [abortSignal, callSignal]);
- return {
+ const bound = {
...session,
run: (options: SandboxRunOptions) =>
session.run({ ...options, abortSignal: compose(options.abortSignal) }),
@@ -42,5 +42,8 @@ export function bindSandboxAbortSignal<TSession extends SandboxSession>(
session.writeTextFile({ ...options, abortSignal: compose(options.abortSignal) }),
removePath: (options: SandboxRemovePathOptions) =>
session.removePath({ ...options, abortSignal: compose(options.abortSignal) }),
- } as TSession;
+ } satisfies SandboxSession;
+
+ // The spread retains provider-specific lifecycle methods not declared on SandboxSession.
+ return bound as TSession;
}
diff --git a/packages/eve/src/execution/sandbox/active-handles.test.ts b/packages/eve/src/execution/sandbox/active-handles.test.ts
index 8aca73bb8..67dc8fe3a 100644
--- a/packages/eve/src/execution/sandbox/active-handles.test.ts
+++ b/packages/eve/src/execution/sandbox/active-handles.test.ts
@@ -13,57 +13,57 @@ afterEach(() => {
describe("shutdownActiveSandboxHandles", () => {
it("shuts down every tracked handle and clears the registry", async () => {
- const first = { shutdown: vi.fn(async () => {}) };
- const second = { shutdown: vi.fn(async () => {}) };
- trackActiveSandboxHandle({ backendName: "docker", handle: first, sessionKey: "session-1" });
- trackActiveSandboxHandle({ backendName: "docker", handle: second, sessionKey: "session-2" });
+ const first = { onRuntimeShutdown: vi.fn(async () => {}) };
+ const second = { onRuntimeShutdown: vi.fn(async () => {}) };
+ trackActiveSandboxHandle({ providerName: "docker", handle: first, sessionId: "session-1" });
+ trackActiveSandboxHandle({ providerName: "docker", handle: second, sessionId: "session-2" });
await shutdownActiveSandboxHandles();
- expect(first.shutdown).toHaveBeenCalledTimes(1);
- expect(second.shutdown).toHaveBeenCalledTimes(1);
+ expect(first.onRuntimeShutdown).toHaveBeenCalledTimes(1);
+ expect(second.onRuntimeShutdown).toHaveBeenCalledTimes(1);
expect(countActiveSandboxHandles()).toBe(0);
});
it("replaces the tracked handle when the same session is reopened", async () => {
- const stale = { shutdown: vi.fn(async () => {}) };
- const fresh = { shutdown: vi.fn(async () => {}) };
- trackActiveSandboxHandle({ backendName: "docker", handle: stale, sessionKey: "session-1" });
- trackActiveSandboxHandle({ backendName: "docker", handle: fresh, sessionKey: "session-1" });
+ const stale = { onRuntimeShutdown: vi.fn(async () => {}) };
+ const fresh = { onRuntimeShutdown: vi.fn(async () => {}) };
+ trackActiveSandboxHandle({ providerName: "docker", handle: stale, sessionId: "session-1" });
+ trackActiveSandboxHandle({ providerName: "docker", handle: fresh, sessionId: "session-1" });
expect(countActiveSandboxHandles()).toBe(1);
await shutdownActiveSandboxHandles();
- expect(stale.shutdown).not.toHaveBeenCalled();
- expect(fresh.shutdown).toHaveBeenCalledTimes(1);
+ expect(stale.onRuntimeShutdown).not.toHaveBeenCalled();
+ expect(fresh.onRuntimeShutdown).toHaveBeenCalledTimes(1);
});
- it("tracks the same session key on different backends separately", async () => {
- const docker = { shutdown: vi.fn(async () => {}) };
- const vercel = { shutdown: vi.fn(async () => {}) };
- trackActiveSandboxHandle({ backendName: "docker", handle: docker, sessionKey: "session-1" });
- trackActiveSandboxHandle({ backendName: "vercel", handle: vercel, sessionKey: "session-1" });
+ it("tracks the same session key on different providers separately", async () => {
+ const docker = { onRuntimeShutdown: vi.fn(async () => {}) };
+ const vercel = { onRuntimeShutdown: vi.fn(async () => {}) };
+ trackActiveSandboxHandle({ providerName: "docker", handle: docker, sessionId: "session-1" });
+ trackActiveSandboxHandle({ providerName: "vercel", handle: vercel, sessionId: "session-1" });
await shutdownActiveSandboxHandles();
- expect(docker.shutdown).toHaveBeenCalledTimes(1);
- expect(vercel.shutdown).toHaveBeenCalledTimes(1);
+ expect(docker.onRuntimeShutdown).toHaveBeenCalledTimes(1);
+ expect(vercel.onRuntimeShutdown).toHaveBeenCalledTimes(1);
});
it("logs a failed shutdown and still shuts down the remaining handles", async () => {
const failing = {
- shutdown: vi.fn(async () => {
+ onRuntimeShutdown: vi.fn(async () => {
throw new Error("provider unreachable");
}),
};
- const healthy = { shutdown: vi.fn(async () => {}) };
- trackActiveSandboxHandle({ backendName: "docker", handle: failing, sessionKey: "session-1" });
- trackActiveSandboxHandle({ backendName: "docker", handle: healthy, sessionKey: "session-2" });
+ const healthy = { onRuntimeShutdown: vi.fn(async () => {}) };
+ trackActiveSandboxHandle({ providerName: "docker", handle: failing, sessionId: "session-1" });
+ trackActiveSandboxHandle({ providerName: "docker", handle: healthy, sessionId: "session-2" });
const log = vi.fn();
await expect(shutdownActiveSandboxHandles({ log })).resolves.toBeUndefined();
- expect(healthy.shutdown).toHaveBeenCalledTimes(1);
+ expect(healthy.onRuntimeShutdown).toHaveBeenCalledTimes(1);
expect(log).toHaveBeenCalledWith(expect.stringContaining("provider unreachable"));
});
});
diff --git a/packages/eve/src/execution/sandbox/active-handles.ts b/packages/eve/src/execution/sandbox/active-handles.ts
index 79f8f1bcc..d6d06cb8d 100644
--- a/packages/eve/src/execution/sandbox/active-handles.ts
+++ b/packages/eve/src/execution/sandbox/active-handles.ts
@@ -1,18 +1,18 @@
import { toErrorMessage } from "#shared/errors.js";
/**
- * The slice of `SandboxBackendHandle` the shutdown registry needs.
+ * The provider handle capability the shutdown registry needs.
* Structural so handles of any session-options generic register without
* variance friction.
*/
export interface ShutdownCapableSandboxHandle {
- shutdown(): Promise<void>;
+ onRuntimeShutdown(): Promise<void>;
}
/**
- * Process-level registry of live sandbox backend handles, keyed by
- * backend name and session key so repeated `create` calls for the same
- * session replace rather than accumulate entries.
+ * Process-level registry of live sandbox provider handles, keyed by
+ * provider name and durable session ID so a resumed handle replaces the
+ * previous handle for that session rather than accumulating entries.
*
* `ensureSandboxAccess` registers every handle it opens; the server
* shutdown path drains the registry so no sandbox compute outlives the
@@ -20,28 +20,27 @@ export interface ShutdownCapableSandboxHandle {
*/
const activeSandboxHandles = new Map<string, ShutdownCapableSandboxHandle>();
-function createActiveSandboxHandleKey(backendName: string, sessionKey: string): string {
- return `${backendName}\0${sessionKey}`;
+function createActiveSandboxHandleKey(providerName: string, sessionId: string): string {
+ return `${providerName}\0${sessionId}`;
}
/**
- * Registers a live sandbox handle for shutdown tracking. A handle
- * created later for the same backend and session key replaces the
- * previous entry.
+ * Registers a live sandbox handle for shutdown tracking. A later handle
+ * for the same provider and durable session replaces the previous entry.
*/
export function trackActiveSandboxHandle(input: {
- readonly backendName: string;
+ readonly providerName: string;
readonly handle: ShutdownCapableSandboxHandle;
- readonly sessionKey: string;
+ readonly sessionId: string;
}): void {
activeSandboxHandles.set(
- createActiveSandboxHandleKey(input.backendName, input.sessionKey),
+ createActiveSandboxHandleKey(input.providerName, input.sessionId),
input.handle,
);
}
/**
- * Stops every tracked sandbox by calling `shutdown()` on each handle in
+ * Stops every tracked sandbox by invoking its runtime-shutdown hook in
* parallel, then clears the registry. Failures are logged and never
* thrown so one misbehaving sandbox cannot block server shutdown.
*/
@@ -51,7 +50,7 @@ export async function shutdownActiveSandboxHandles(input?: {
const entries = [...activeSandboxHandles.entries()];
activeSandboxHandles.clear();
- const results = await Promise.allSettled(entries.map(([, handle]) => handle.shutdown()));
+ const results = await Promise.allSettled(entries.map(([, handle]) => handle.onRuntimeShutdown()));
for (const [index, result] of results.entries()) {
if (result.status === "rejected") {
diff --git a/packages/eve/src/execution/sandbox/bash.test.ts b/packages/eve/src/execution/sandbox/bash.test.ts
index 3febee27b..8556bb12b 100644
--- a/packages/eve/src/execution/sandbox/bash.test.ts
+++ b/packages/eve/src/execution/sandbox/bash.test.ts
@@ -41,7 +41,6 @@ describe("executeBashOnSandbox", () => {
function createTestSandboxSession(result: SandboxCommandResult): SandboxSession {
return {
- id: "test-sandbox",
readBinaryFile: async () => null,
readFile: async () => null,
readTextFile: async () => null,
diff --git a/packages/eve/src/execution/sandbox/bash.ts b/packages/eve/src/execution/sandbox/bash.ts
index 4ea926c3c..d0c5a0438 100644
--- a/packages/eve/src/execution/sandbox/bash.ts
+++ b/packages/eve/src/execution/sandbox/bash.ts
@@ -1,6 +1,6 @@
import type { SandboxSession } from "#shared/sandbox-session.js";
import { truncateTail } from "#execution/sandbox/truncate-output.js";
-import { isEveDevEnvironment } from "#internal/application/optional-package-install.js";
+import { isEveDevEnvironment } from "#internal/application/dev-environment.js";
const MAX_LOG_COMMAND_LENGTH = 240;
diff --git a/packages/eve/src/execution/sandbox/bindings/docker-cli.ts b/packages/eve/src/execution/sandbox/bindings/docker-cli.ts
index 4120d24a2..9a4356cec 100644
--- a/packages/eve/src/execution/sandbox/bindings/docker-cli.ts
+++ b/packages/eve/src/execution/sandbox/bindings/docker-cli.ts
@@ -56,11 +56,11 @@ export class DockerUnavailableError extends Error {
readonly hint =
"Install and start Docker Desktop, OrbStack, Colima, or another runtime exposing a " +
"Docker-compatible `docker` CLI (or point EVE_DOCKER_PATH at one, e.g. Podman). " +
- "Alternatively use microsandbox(), the dependency-free justbash(), " +
- "vercel(), or defaultSandbox() to pick by availability.";
+ "Alternatively use MicrosandboxSandbox, the dependency-free JustBashSandbox, " +
+ "VercelSandbox, or DefaultSandbox to pick by availability.";
constructor(cause?: unknown) {
- super("The Docker sandbox backend requires Docker, but the `docker` CLI was not found.", {
+ super("The Docker sandbox provider requires Docker, but the `docker` CLI was not found.", {
cause,
});
this.name = "DockerUnavailableError";
@@ -74,13 +74,13 @@ export class DockerDaemonUnavailableError extends Error {
/** Structured remediation, surfaced by the semantic-error catalog. */
readonly hint =
"Start Docker Desktop (or your Docker-compatible runtime) and retry. Alternatively use " +
- "microsandbox(), the dependency-free justbash() (installed automatically " +
- "by `eve dev`, or `pnpm add -D just-bash`), vercel(), or defaultSandbox() " +
+ "MicrosandboxSandbox, the dependency-free JustBashSandbox (installed automatically " +
+ "by `eve dev`, or `pnpm add -D just-bash`), VercelSandbox, or DefaultSandbox " +
"to pick by availability.";
constructor(detail: string) {
super(
- "The Docker sandbox backend requires a running Docker daemon, but it is not reachable. " +
+ "The Docker sandbox provider requires a running Docker daemon, but it is not reachable. " +
`Docker reported: ${detail}`,
);
this.name = "DockerDaemonUnavailableError";
@@ -111,7 +111,7 @@ let cachedLinuxDockerAvailability: boolean | undefined;
* containers, for `defaultSandbox()`'s availability chain. eve's Docker
* sandbox image is Linux-only, so a Windows-container daemon is not a
* compatible default even though it answers the Docker CLI. The result is
- * cached for the process lifetime: backend selection must be stable, and
+ * cached for the process lifetime: provider selection must be stable, and
* the probe costs a subprocess round-trip.
*/
export function isLinuxDockerDaemonAvailableSync(): boolean {
diff --git a/packages/eve/src/execution/sandbox/bindings/docker-container.ts b/packages/eve/src/execution/sandbox/bindings/docker-container.ts
index 0b24082cd..6ea62ca71 100644
--- a/packages/eve/src/execution/sandbox/bindings/docker-container.ts
+++ b/packages/eve/src/execution/sandbox/bindings/docker-container.ts
@@ -3,7 +3,6 @@ import type { DockerCli } from "#execution/sandbox/bindings/docker-cli.js";
import type { ResolvedDockerSandboxOptions } from "#execution/sandbox/bindings/docker-options.js";
import { expectDockerSuccess } from "#execution/sandbox/bindings/docker-utils.js";
import { withDevelopmentSandboxTags } from "#execution/sandbox/development-run.js";
-import type { SandboxBackendTags } from "#public/definitions/sandbox-backend.js";
import type { DockerSandboxNetworkPolicy } from "#public/sandbox/docker-sandbox.js";
import { WORKSPACE_ROOT } from "#runtime/workspace/types.js";
@@ -20,8 +19,9 @@ export async function startDockerContainer(input: {
readonly image: string;
readonly initialNetworkPolicy: DockerSandboxNetworkPolicy;
readonly options: ResolvedDockerSandboxOptions;
+ readonly resourcesPath?: string;
readonly role: "session" | "template-build";
- readonly tags?: SandboxBackendTags;
+ readonly tags?: Readonly<Record<string, string>>;
}): Promise<void> {
const args = [
"run",
@@ -43,6 +43,9 @@ export async function startDockerContainer(input: {
if (input.initialNetworkPolicy === "deny-all") {
args.push("--network", "none");
}
+ if (input.resourcesPath !== undefined) {
+ args.push("--mount", `type=bind,src=${input.resourcesPath},dst=/eve/resources,readonly`);
+ }
args.push(
"--workdir",
diff --git a/packages/eve/src/execution/sandbox/bindings/docker-network.ts b/packages/eve/src/execution/sandbox/bindings/docker-network.ts
index 22d16345c..0ae7e62ab 100644
--- a/packages/eve/src/execution/sandbox/bindings/docker-network.ts
+++ b/packages/eve/src/execution/sandbox/bindings/docker-network.ts
@@ -5,7 +5,7 @@ import type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";
/**
* Applies a coarse-grained run-time network policy by attaching or
* detaching the container's networks. Domain-level policies and
- * credential brokering require the firewall on the Vercel backend.
+ * credential brokering require the firewall on the Vercel provider.
*/
export async function setDockerNetworkPolicy(
cli: DockerCli,
@@ -14,9 +14,9 @@ export async function setDockerNetworkPolicy(
): Promise<void> {
if (policy !== "allow-all" && policy !== "deny-all") {
throw new Error(
- 'The local Docker sandbox backend supports only the "allow-all" and "deny-all" network ' +
- "policies. Domain-level allow-lists and credential brokering require the Vercel backend " +
- "(vercel()) or microsandbox().",
+ 'The local Docker sandbox provider supports only the "allow-all" and "deny-all" network ' +
+ "policies. Domain-level allow-lists and credential brokering require the Vercel provider " +
+ "(VercelSandbox) or MicrosandboxSandbox.",
);
}
@@ -28,9 +28,11 @@ export async function setDockerNetworkPolicy(
containerName,
]);
expectDockerSuccess(inspect, `inspect networks of sandbox container "${containerName}"`);
- const networks = Object.keys(
- JSON.parse(inspect.stdout.trim() === "" ? "{}" : inspect.stdout) as object,
- );
+ const networkSettings: unknown = JSON.parse(inspect.stdout.trim() === "" ? "{}" : inspect.stdout);
+ if (typeof networkSettings !== "object" || networkSettings === null) {
+ throw new Error(`Docker returned invalid network settings for "${containerName}".`);
+ }
+ const networks = Object.keys(networkSettings);
if (policy === "deny-all") {
for (const network of networks) {
diff --git a/packages/eve/src/execution/sandbox/bindings/docker-options.test.ts b/packages/eve/src/execution/sandbox/bindings/docker-options.test.ts
index 0dce9d54d..3763f5e49 100644
--- a/packages/eve/src/execution/sandbox/bindings/docker-options.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/docker-options.test.ts
@@ -8,12 +8,11 @@ import {
import { DEFAULT_EVE_SANDBOX_IMAGE } from "#execution/sandbox/bindings/eve-image.js";
describe("resolveDockerSandboxOptions", () => {
- it("defaults to eve's published sandbox runtime image with permissive networking", () => {
+ it("defaults to eve's published sandbox runtime image", () => {
expect(DEFAULT_DOCKER_SANDBOX_IMAGE).toBe(DEFAULT_EVE_SANDBOX_IMAGE);
expect(resolveDockerSandboxOptions()).toEqual({
env: {},
image: DEFAULT_DOCKER_SANDBOX_IMAGE,
- networkPolicy: "allow-all",
pullPolicy: "if-not-present",
});
});
@@ -23,13 +22,11 @@ describe("resolveDockerSandboxOptions", () => {
resolveDockerSandboxOptions({
env: { FOO: "bar" },
image: "ubuntu:26.04",
- networkPolicy: "deny-all",
pullPolicy: "never",
}),
).toEqual({
env: { FOO: "bar" },
image: "ubuntu:26.04",
- networkPolicy: "deny-all",
pullPolicy: "never",
});
});
@@ -39,21 +36,18 @@ describe("resolveDockerSandboxOptions", () => {
resolveDockerSandboxOptions({
env: { B: "2", A: "1" },
image: "ubuntu:26.04",
- networkPolicy: "allow-all",
}),
);
const second = createDockerSandboxOptionsHash(
resolveDockerSandboxOptions({
env: { A: "1", B: "2" },
image: "ubuntu:26.04",
- networkPolicy: "allow-all",
}),
);
const changed = createDockerSandboxOptionsHash(
resolveDockerSandboxOptions({
env: { A: "changed", B: "2" },
image: "ubuntu:26.04",
- networkPolicy: "allow-all",
}),
);
diff --git a/packages/eve/src/execution/sandbox/bindings/docker-options.ts b/packages/eve/src/execution/sandbox/bindings/docker-options.ts
index 52db13cd8..d0fae6785 100644
--- a/packages/eve/src/execution/sandbox/bindings/docker-options.ts
+++ b/packages/eve/src/execution/sandbox/bindings/docker-options.ts
@@ -2,25 +2,23 @@ import { createHash } from "node:crypto";
import { DEFAULT_EVE_SANDBOX_IMAGE } from "#execution/sandbox/bindings/eve-image.js";
import type {
- DockerSandboxCreateOptions,
- DockerSandboxNetworkPolicy,
+ DockerSandboxEnvironmentOptions,
DockerSandboxPullPolicy,
} from "#public/sandbox/docker-sandbox.js";
/**
- * Default base image for the Docker backend: eve's published sandbox
+ * Default base image for the Docker provider: eve's published sandbox
* runtime image.
*/
export const DEFAULT_DOCKER_SANDBOX_IMAGE = DEFAULT_EVE_SANDBOX_IMAGE;
/**
- * Fully-defaulted Docker backend options consumed by the backend
+ * Fully-defaulted Docker provider options consumed by the provider
* implementation.
*/
export interface ResolvedDockerSandboxOptions {
readonly env: Readonly<Record<string, string>>;
readonly image: string;
- readonly networkPolicy: DockerSandboxNetworkPolicy;
readonly pullPolicy: DockerSandboxPullPolicy;
}
@@ -28,12 +26,11 @@ export interface ResolvedDockerSandboxOptions {
* Applies defaults to `docker(opts)`.
*/
export function resolveDockerSandboxOptions(
- options: DockerSandboxCreateOptions = {},
+ options: DockerSandboxEnvironmentOptions = {},
): ResolvedDockerSandboxOptions {
return {
env: options.env ?? {},
image: options.image ?? DEFAULT_DOCKER_SANDBOX_IMAGE,
- networkPolicy: options.networkPolicy ?? "allow-all",
pullPolicy: options.pullPolicy ?? "if-not-present",
};
}
@@ -45,11 +42,16 @@ export function createDockerSandboxOptionsHash(options: ResolvedDockerSandboxOpt
.slice(0, 20);
}
-function dockerOptionsForHash(options: ResolvedDockerSandboxOptions): Record<string, unknown> {
+interface DockerTemplateOptions {
+ readonly env: Readonly<Record<string, string>>;
+ readonly image: string;
+ readonly pullPolicy: DockerSandboxPullPolicy;
+}
+
+function dockerOptionsForHash(options: ResolvedDockerSandboxOptions): DockerTemplateOptions {
return {
env: sortStringRecord(options.env),
image: options.image,
- networkPolicy: options.networkPolicy,
pullPolicy: options.pullPolicy,
};
}
diff --git a/packages/eve/src/execution/sandbox/bindings/docker-session.ts b/packages/eve/src/execution/sandbox/bindings/docker-session.ts
index 5f2769a5a..348d5202f 100644
--- a/packages/eve/src/execution/sandbox/bindings/docker-session.ts
+++ b/packages/eve/src/execution/sandbox/bindings/docker-session.ts
@@ -3,7 +3,7 @@ import { dirname as posixDirname } from "node:path/posix";
import type { DockerCli } from "#execution/sandbox/bindings/docker-cli.js";
import { expectDockerSuccess } from "#execution/sandbox/bindings/docker-utils.js";
-import { resolveWorkspacePath } from "#execution/sandbox/bindings/local-backend-utils.js";
+import { resolveWorkspacePath } from "#execution/sandbox/bindings/local-provider-utils.js";
import { shellQuote } from "#execution/sandbox/shell-quote.js";
import { bufferToStream, streamToBuffer } from "#execution/sandbox/stream-utils.js";
import { WORKSPACE_ROOT } from "#runtime/workspace/types.js";
@@ -51,7 +51,6 @@ const DOCKER_KILL_TREE_SCRIPT = [
export function createDockerInternalSession(input: {
readonly cli: DockerCli;
readonly containerIdentity: string;
- readonly id: string;
}): InternalSandboxSession {
const { cli, containerIdentity } = input;
@@ -72,7 +71,6 @@ export function createDockerInternalSession(input: {
}
return {
- id: input.id,
resolvePath: resolveWorkspacePath,
async spawn(options: SandboxSpawnOptions) {
const args = ["exec", "-w", resolveWorkspacePath(options.workingDirectory ?? WORKSPACE_ROOT)];
diff --git a/packages/eve/src/execution/sandbox/bindings/docker.integration.test.ts b/packages/eve/src/execution/sandbox/bindings/docker.integration.test.ts
index c37f13c80..953c25c3b 100644
--- a/packages/eve/src/execution/sandbox/bindings/docker.integration.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/docker.integration.test.ts
@@ -1,4 +1,4 @@
-import { readFile } from "node:fs/promises";
+import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
@@ -9,11 +9,7 @@ import {
type DockerCommandResult,
type DockerProcess,
} from "#execution/sandbox/bindings/docker-cli.js";
-import {
- createDockerSandboxBackend,
- DOCKER_TEMPLATE_IMAGE_REPOSITORY,
- pruneDockerSandboxTemplates,
-} from "#execution/sandbox/bindings/docker.js";
+import { createDockerSandboxProvider } from "#execution/sandbox/bindings/docker.js";
import { EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV } from "#execution/sandbox/development-run.js";
import {
createDockerSandboxOptionsHash,
@@ -21,10 +17,15 @@ import {
resolveDockerSandboxOptions,
} from "#execution/sandbox/bindings/docker-options.js";
import { dockerTemplateImageReference } from "#execution/sandbox/bindings/docker-templates.js";
-import type { DockerSandboxCreateOptions } from "#public/sandbox/docker-sandbox.js";
-import { SandboxTemplateNotProvisionedError } from "#public/definitions/sandbox-backend.js";
+import type {
+ DockerSandboxEnvironmentOptions,
+ DockerSandboxRuntimeOptions,
+} from "#public/sandbox/docker-sandbox.js";
+import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";
+import { createSandboxProviderHarness } from "#internal/testing/sandbox-provider-harness.js";
import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";
import { bufferToStream } from "#execution/sandbox/stream-utils.js";
+import { createSandboxProviderIdentity } from "#execution/sandbox/provider-identity.js";
const createScratchDirectory = useTemporaryDirectories();
@@ -98,12 +99,14 @@ function createFakeDockerCli(
function createEngine(input: {
readonly cli: DockerCli;
- readonly options?: DockerSandboxCreateOptions;
+ readonly options?: DockerSandboxEnvironmentOptions;
+ readonly runtimeOptions?: DockerSandboxRuntimeOptions;
}) {
- return createDockerSandboxBackend({
- createOptions: input.options,
- dockerCli: input.cli,
- });
+ return createSandboxProviderHarness(
+ createDockerSandboxProvider(input.options, input.cli),
+ input.runtimeOptions ?? {},
+ { preparedArtifact: () => ({ imageReference: TEMPLATE_IMAGE }) },
+ );
}
function findCall(
@@ -132,54 +135,57 @@ const TEMPLATE_IMAGE = dockerTemplateImageReference({
templateKey: TEMPLATE_KEY,
});
const SESSION_KEY = "eve-sbx-ses-local-session-1";
-
-function defaultDockerTemplateImageTag(templateKey: string): string {
- return dockerTemplateImageReference({
- optionsHash: DEFAULT_DOCKER_OPTIONS_HASH,
- templateKey,
- }).slice(`${DOCKER_TEMPLATE_IMAGE_REPOSITORY}:`.length);
-}
-
-describe("createDockerSandboxBackend prewarm", () => {
- it("reuses an existing template image without building", async () => {
+const PROVIDER_CONTAINER_NAME = `eve-sbx-${createSandboxProviderIdentity({
+ artifact: { imageReference: TEMPLATE_IMAGE },
+ environment: createDockerSandboxOptionsHash(resolveDockerSandboxOptions(undefined)),
+ open: {},
+ sessionId: SESSION_KEY,
+ version: 1,
+}).slice(0, 32)}`;
+
+describe("Docker provider prewarm", () => {
+ it("uses a colocated Dockerfile as the template base image", async () => {
const appRoot = await createScratchDirectory("eve-docker-sandbox-");
const { calls, cli } = createFakeDockerCli((args) => {
- if (isImageInspect(args, TEMPLATE_IMAGE)) {
- return { exitCode: 0, stdout: "sha256:abc\n" };
+ if (
+ args[0] === "image" &&
+ args[1] === "inspect" &&
+ String(args.at(-1)).startsWith("eve-sandbox-template:")
+ ) {
+ return { exitCode: 1, stderr: "No such image" };
}
return undefined;
});
+ await mkdir(join(appRoot, "sandbox"), { recursive: true });
+ await writeFile(join(appRoot, "sandbox", "Dockerfile"), "FROM node:24\n");
- const result = await createEngine({ cli }).prewarm({
- runtimeContext: { appRoot },
+ await createEngine({ cli }).prepare({
+ appRoot,
seedFiles: [],
- templateKey: TEMPLATE_KEY,
});
- expect(result).toEqual({ reused: true });
- expect(findCall(calls, (args) => args[0] === "run")).toBeUndefined();
- expect(findCall(calls, (args) => args[0] === "commit")).toBeUndefined();
- // The reuse touches the per-app marker so pruning sees the template
- // as active.
- await expect(
- readFile(
- join(
- appRoot,
- ".eve",
- "sandbox-cache",
- "docker",
- "templates",
- defaultDockerTemplateImageTag(TEMPLATE_KEY),
- ),
- "utf8",
- ),
- ).resolves.toContain(TEMPLATE_IMAGE);
+ expect(findCall(calls, (args) => args[0] === "build")?.args).toEqual([
+ "build",
+ "--file",
+ expect.stringMatching(/[\\/]dockerfiles[\\/][a-f0-9]{64}[\\/]Dockerfile$/u),
+ "--tag",
+ expect.stringMatching(/^eve-sandbox-dockerfile:/),
+ expect.stringMatching(/[\\/]dockerfiles[\\/][a-f0-9]{64}$/u),
+ ]);
+ expect(findCall(calls, (args) => args[0] === "pull")).toBeUndefined();
+ expect(findCall(calls, (args) => args[0] === "run")?.args).toContainEqual(
+ expect.stringMatching(/^eve-sandbox-dockerfile:/),
+ );
});
it("builds, seeds, commits, and cleans up when the template image is missing", async () => {
const appRoot = await createScratchDirectory("eve-docker-sandbox-");
const { calls, cli } = createFakeDockerCli((args) => {
- if (isImageInspect(args, TEMPLATE_IMAGE)) {
+ if (
+ args[0] === "image" &&
+ args[1] === "inspect" &&
+ String(args.at(-1)).startsWith("eve-sandbox-template:")
+ ) {
return { exitCode: 1, stderr: "No such image" };
}
if (isImageInspect(args, DEFAULT_DOCKER_SANDBOX_IMAGE)) {
@@ -188,13 +194,12 @@ describe("createDockerSandboxBackend prewarm", () => {
return undefined;
});
- const result = await createEngine({ cli }).prewarm({
- runtimeContext: { appRoot },
+ const result = await createEngine({ cli }).prepare({
+ appRoot,
seedFiles: [{ content: "# Weather skill\n", path: "/workspace/skills/weather.md" }],
- templateKey: TEMPLATE_KEY,
});
- expect(result).toEqual({ reused: false });
+ expect(result.imageReference).toMatch(/^eve-sandbox-template:/u);
const pull = findCall(calls, (args) => args[0] === "pull");
expect(pull?.args).toEqual(["pull", DEFAULT_DOCKER_SANDBOX_IMAGE]);
@@ -205,7 +210,7 @@ describe("createDockerSandboxBackend prewarm", () => {
expect(run?.args).toContain("/bin/sh");
expect(run?.args).toContain(`eve.sandbox.role=template-build`);
const buildContainerName = run?.args[run.args.indexOf("--name") + 1];
- expect(buildContainerName).toMatch(new RegExp(`^${TEMPLATE_KEY}-build-`));
+ expect(buildContainerName).toMatch(/^[a-f0-9]{24}-build-[a-f0-9]{8}$/u);
const baseSetup = findCall(
calls,
@@ -237,65 +242,47 @@ describe("createDockerSandboxBackend prewarm", () => {
const commit = findCall(calls, (args) => args[0] === "commit");
expect(commit?.args.at(-2)).toBe(fakeDockerContainerIdentity(buildContainerName!));
- expect(commit?.args.at(-1)).toBe(TEMPLATE_IMAGE);
+ expect(commit?.args.at(-1)).toMatch(/^eve-sandbox-template:/u);
const cleanup = findCall(calls, (args) => args[0] === "rm" && args[1] === "-f");
expect(cleanup?.args.at(-1)).toBe(buildContainerName);
});
- it("writes seed files before bootstrap and commits bootstrap outputs", async () => {
+ it("mounts compiled resources read-only while hydrating a writable template", async () => {
const appRoot = await createScratchDirectory("eve-docker-sandbox-");
- let seedWritten = false;
+ const resourcesPath = join(appRoot, "compiled-resources");
+ await mkdir(join(resourcesPath, "workspace"), { recursive: true });
+ await writeFile(join(resourcesPath, "workspace", "README.md"), "immutable seed");
const { calls, cli } = createFakeDockerCli((args) => {
- const command = args.at(-1) ?? "";
- if (isImageInspect(args, TEMPLATE_IMAGE)) {
- return { exitCode: 1, stderr: "No such image" };
- }
- if (args[0] === "exec" && args[1] === "-i" && command.includes("/workspace/seed.txt")) {
- seedWritten = true;
- }
if (
- args[0] === "exec" &&
- command.includes("if [ -e") &&
- command.includes("/workspace/seed.txt")
+ args[0] === "image" &&
+ args[1] === "inspect" &&
+ String(args.at(-1)).startsWith("eve-sandbox-template:")
) {
- return seedWritten ? { exitCode: 0, stdout: "authored seed" } : { exitCode: 43 };
+ return { exitCode: 1, stderr: "No such image" };
}
return undefined;
});
- await createEngine({ cli }).prewarm({
- bootstrap: async ({ use }) => {
- const sandbox = await use();
- await expect(sandbox.readTextFile({ path: "/workspace/seed.txt" })).resolves.toBe(
- "authored seed",
- );
- await sandbox.writeTextFile({
- content: "bootstrap output",
- path: "/workspace/bootstrap.txt",
- });
- },
- runtimeContext: { appRoot },
- seedFiles: [{ content: "authored seed", path: "/workspace/seed.txt" }],
- templateKey: TEMPLATE_KEY,
+ await createEngine({ cli }).prepare({
+ resourcesKey: "resources-hash",
+ resourcesPath,
+ appRoot,
+ seedFiles: [],
});
- const seedWriteIndex = calls.findIndex(
- ({ args }) =>
- args[0] === "exec" &&
- args[1] === "-i" &&
- (args.at(-1) ?? "").includes("/workspace/seed.txt"),
- );
- const bootstrapWriteIndex = calls.findIndex(
- ({ args }) =>
- args[0] === "exec" &&
- args[1] === "-i" &&
- (args.at(-1) ?? "").includes("/workspace/bootstrap.txt"),
+ const run = findCall(calls, (args) => args[0] === "run");
+ expect(run?.args).toContain(
+ `type=bind,src=${join(appRoot, "docker", "resources", "resources-hash")},dst=/eve/resources,readonly`,
);
- const commitIndex = calls.findIndex(({ args }) => args[0] === "commit");
- expect(seedWriteIndex).toBeGreaterThanOrEqual(0);
- expect(seedWriteIndex).toBeLessThan(bootstrapWriteIndex);
- expect(bootstrapWriteIndex).toBeLessThan(commitIndex);
+ expect(
+ findCall(
+ calls,
+ (args) =>
+ args[0] === "exec" &&
+ (args.at(-1) ?? "").includes("cp -a /eve/resources/workspace/. /workspace/"),
+ ),
+ ).toBeDefined();
});
it("fails with an actionable error when the daemon is unreachable", async () => {
@@ -308,44 +295,50 @@ describe("createDockerSandboxBackend prewarm", () => {
});
await expect(
- createEngine({ cli }).prewarm({
- runtimeContext: { appRoot },
+ createEngine({ cli }).prepare({
+ appRoot,
seedFiles: [],
- templateKey: TEMPLATE_KEY,
}),
).rejects.toThrow(DockerDaemonUnavailableError);
});
});
-describe("createDockerSandboxBackend create", () => {
+describe("Docker provider create", () => {
it("throws SandboxTemplateNotProvisionedError when the template image is missing", async () => {
const appRoot = await createScratchDirectory("eve-docker-sandbox-");
const { cli } = createFakeDockerCli((args) => {
if (isContainerInspect(args)) {
return { exitCode: 1, stderr: "No such container" };
}
- if (isImageInspect(args, TEMPLATE_IMAGE)) {
+ if (
+ args[0] === "image" &&
+ args[1] === "inspect" &&
+ String(args.at(-1)).startsWith("eve-sandbox-template:")
+ ) {
return { exitCode: 1, stderr: "No such image" };
}
return undefined;
});
await expect(
- createEngine({ cli }).create({
- runtimeContext: { appRoot },
- sessionKey: SESSION_KEY,
- templateKey: TEMPLATE_KEY,
+ createEngine({ cli }).openSession({
+ appRoot,
+ sandboxName: SESSION_KEY,
}),
).rejects.toThrow(SandboxTemplateNotProvisionedError);
});
- it("throws SandboxTemplateNotProvisionedError when a template-backed container fails to start", async () => {
+ it("preserves the container launch error when a template-backed container fails to start", async () => {
const appRoot = await createScratchDirectory("eve-docker-sandbox-");
const { cli } = createFakeDockerCli((args) => {
if (isContainerInspect(args)) {
return { exitCode: 1, stderr: "No such container" };
}
- if (isImageInspect(args, TEMPLATE_IMAGE)) {
+ if (
+ args[0] === "image" &&
+ args[1] === "inspect" &&
+ String(args.at(-1)).startsWith("eve-sandbox-template:")
+ ) {
return { exitCode: 0, stdout: "sha256:abc\n" };
}
if (args[0] === "run") {
@@ -355,12 +348,11 @@ describe("createDockerSandboxBackend create", () => {
});
await expect(
- createEngine({ cli }).create({
- runtimeContext: { appRoot },
- sessionKey: SESSION_KEY,
- templateKey: TEMPLATE_KEY,
+ createEngine({ cli }).openSession({
+ appRoot,
+ sandboxName: SESSION_KEY,
}),
- ).rejects.toThrow(SandboxTemplateNotProvisionedError);
+ ).rejects.toThrow("template-backed container failed to start");
});
it("creates a session container from the template image with labels and tags", async () => {
@@ -375,18 +367,14 @@ describe("createDockerSandboxBackend create", () => {
});
try {
- const handle = await createEngine({ cli }).create({
- runtimeContext: { appRoot },
- sessionKey: SESSION_KEY,
- tags: { agent: "weather" },
- templateKey: TEMPLATE_KEY,
+ const handle = await createEngine({ cli }).openSession({
+ appRoot,
+ sandboxName: SESSION_KEY,
});
const run = findCall(calls, (args) => args[0] === "run");
- expect(run?.args).toContain(SESSION_KEY);
+ expect(run?.args).toContain(PROVIDER_CONTAINER_NAME);
expect(run?.args).toContain("eve.sandbox.role=session");
- expect(run?.args).toContain("eve.sandbox.tag.agent=weather");
- expect(run?.args).toContain("eve.sandbox.tag.devRunId=dev-run-test");
expect(run?.args.at(-3)).toBe(TEMPLATE_IMAGE);
// No base setup against template-backed sessions — the template
@@ -395,20 +383,14 @@ describe("createDockerSandboxBackend create", () => {
findCall(calls, (args) => args[0] === "exec" && args.includes("/bin/sh")),
).toBeUndefined();
- await expect(handle.captureState()).resolves.toEqual({
- backendName: "docker",
- metadata: { containerName: SESSION_KEY },
- sessionKey: SESSION_KEY,
- });
-
// An authored stop releases the container; filesystem state survives
// for the next `create` to restart from.
- await handle.stop();
+ await handle.onSessionStop();
expect(findCall(calls, (args) => args[0] === "stop")?.args).toEqual([
"stop",
"-t",
"0",
- fakeDockerContainerIdentity(SESSION_KEY),
+ fakeDockerContainerIdentity(PROVIDER_CONTAINER_NAME),
]);
} finally {
if (previousRunId === undefined) {
@@ -428,13 +410,15 @@ describe("createDockerSandboxBackend create", () => {
return undefined;
});
- await createEngine({ cli }).create({
- runtimeContext: { appRoot },
- sessionKey: SESSION_KEY,
- templateKey: TEMPLATE_KEY,
+ await createEngine({ cli }).openSession({
+ appRoot,
+ sandboxName: SESSION_KEY,
});
- expect(findCall(calls, (args) => args[0] === "start")?.args).toEqual(["start", SESSION_KEY]);
+ expect(findCall(calls, (args) => args[0] === "start")?.args).toEqual([
+ "start",
+ PROVIDER_CONTAINER_NAME,
+ ]);
expect(findCall(calls, (args) => args[0] === "run")).toBeUndefined();
});
@@ -447,44 +431,21 @@ describe("createDockerSandboxBackend create", () => {
return undefined;
});
- await createEngine({ cli }).create({
- existingMetadata: { containerName: SESSION_KEY },
- runtimeContext: { appRoot },
- sessionKey: SESSION_KEY,
- templateKey: TEMPLATE_KEY,
+ const engine = createEngine({ cli });
+ const { state } = await engine.start({ appRoot, sandboxName: SESSION_KEY });
+ await engine.openSession({
+ existing: state,
+ appRoot,
+ sandboxName: SESSION_KEY,
});
expect(findCall(calls, (args) => args[0] === "start")).toBeUndefined();
expect(findCall(calls, (args) => args[0] === "run")).toBeUndefined();
});
- it("creates from the base image and applies base setup when no template exists", async () => {
- const appRoot = await createScratchDirectory("eve-docker-sandbox-");
- const { calls, cli } = createFakeDockerCli((args) => {
- if (isContainerInspect(args)) {
- return { exitCode: 1, stderr: "No such container" };
- }
- return undefined;
- });
-
- await createEngine({ cli }).create({
- runtimeContext: { appRoot },
- sessionKey: SESSION_KEY,
- templateKey: null,
- });
-
- const run = findCall(calls, (args) => args[0] === "run");
- expect(run?.args.at(-3)).toBe(DEFAULT_DOCKER_SANDBOX_IMAGE);
- expect(
- findCall(calls, (args) => args[0] === "exec" && args.includes("/bin/sh"))?.args.at(-1),
- ).toContain("mkdir -p /workspace");
- });
-});
-
-describe("docker session primitives", () => {
async function createRunningSessionHandle(input: {
readonly respond?: (args: readonly string[]) => FakeResponse | undefined;
- readonly options?: DockerSandboxCreateOptions;
+ readonly options?: DockerSandboxEnvironmentOptions;
}) {
const appRoot = await createScratchDirectory("eve-docker-sandbox-");
const { calls, cli, killedStreams } = createFakeDockerCli((args) => {
@@ -493,10 +454,9 @@ describe("docker session primitives", () => {
}
return input.respond?.(args);
});
- const handle = await createEngine({ cli, options: input.options }).create({
- runtimeContext: { appRoot },
- sessionKey: SESSION_KEY,
- templateKey: TEMPLATE_KEY,
+ const handle = await createEngine({ cli, options: input.options }).openSession({
+ appRoot,
+ sandboxName: SESSION_KEY,
});
return { calls, handle, killedStreams };
}
@@ -511,7 +471,7 @@ describe("docker session primitives", () => {
},
});
- const result = await handle.session.run({
+ const result = await handle.sandbox.run({
command: 'echo "$DEPLOY_ENV"',
env: { DEPLOY_ENV: "staging" },
});
@@ -526,7 +486,7 @@ describe("docker session primitives", () => {
"/workspace",
"-e",
"DEPLOY_ENV=staging",
- fakeDockerContainerIdentity(SESSION_KEY),
+ fakeDockerContainerIdentity(PROVIDER_CONTAINER_NAME),
"bash",
"-c",
]);
@@ -542,7 +502,7 @@ describe("docker session primitives", () => {
it("kill() tree-kills inside the container before killing the docker exec client", async () => {
const { calls, handle, killedStreams } = await createRunningSessionHandle({});
- const spawned = await handle.session.spawn({ command: "sleep 300" });
+ const spawned = await handle.sandbox.spawn({ command: "sleep 300" });
const spawnExec = findCall(calls, (args) => args[0] === "exec" && args.includes("bash"));
const wrapper = String(spawnExec?.args.at(-1));
const pidFilePath = /'(\/tmp\/\.eve-sbx-spawn-[0-9a-f-]+\.pid)'/.exec(wrapper)?.[1];
@@ -551,7 +511,10 @@ describe("docker session primitives", () => {
await spawned.kill();
const treeKill = findCall(calls, (args) => args.includes("eve-kill-tree"));
- expect(treeKill?.args.slice(0, 2)).toEqual(["exec", fakeDockerContainerIdentity(SESSION_KEY)]);
+ expect(treeKill?.args.slice(0, 2)).toEqual([
+ "exec",
+ fakeDockerContainerIdentity(PROVIDER_CONTAINER_NAME),
+ ]);
expect(treeKill?.args.at(-1)).toBe(pidFilePath);
expect(String(treeKill?.args.at(-3))).toContain("kill_tree");
// The local docker exec client is killed after the in-container
@@ -563,7 +526,7 @@ describe("docker session primitives", () => {
const { calls, handle } = await createRunningSessionHandle({});
const controller = new AbortController();
- await handle.session.spawn({ abortSignal: controller.signal, command: "sleep 300" });
+ await handle.sandbox.spawn({ abortSignal: controller.signal, command: "sleep 300" });
expect(findCall(calls, (args) => args.includes("eve-kill-tree"))).toBeUndefined();
controller.abort();
@@ -582,7 +545,7 @@ describe("docker session primitives", () => {
},
});
- await expect(handle.session.readTextFile({ path: "missing.txt" })).resolves.toBeNull();
+ await expect(handle.sandbox.readTextFile({ path: "missing.txt" })).resolves.toBeNull();
});
it("round-trips binary bytes through writeFile and readFile", async () => {
@@ -597,25 +560,25 @@ describe("docker session primitives", () => {
},
});
- await handle.session.writeBinaryFile({ content: bytes, path: "assets/fixture.bin" });
+ await handle.sandbox.writeBinaryFile({ content: bytes, path: "assets/fixture.bin" });
const write = findCall(calls, (args) => args[0] === "exec" && args[1] === "-i");
written = write?.stdin;
expect(write?.args.at(-1)).toContain("mkdir -p '/workspace/assets'");
expect(written?.equals(bytes)).toBe(true);
- const readBack = await handle.session.readBinaryFile({ path: "assets/fixture.bin" });
+ const readBack = await handle.sandbox.readBinaryFile({ path: "assets/fixture.bin" });
expect(readBack === null ? null : Buffer.from(readBack).equals(bytes)).toBe(true);
});
it("maps removePath options onto rm flags", async () => {
const { calls, handle } = await createRunningSessionHandle({});
- await handle.session.removePath({ force: true, path: "skills/tenant", recursive: true });
+ await handle.sandbox.removePath({ force: true, path: "skills/tenant", recursive: true });
const remove = findCall(calls, (args) => args[0] === "exec" && args.includes("rm"));
expect(remove?.args).toEqual([
"exec",
- fakeDockerContainerIdentity(SESSION_KEY),
+ fakeDockerContainerIdentity(PROVIDER_CONTAINER_NAME),
"rm",
"-rf",
"--",
@@ -633,7 +596,7 @@ describe("docker session primitives", () => {
},
});
- await handle.session.setNetworkPolicy("deny-all");
+ await handle.sandbox.setNetworkPolicy("deny-all");
expect(
findCall(calls, (args) => args[0] === "network" && args[1] === "disconnect")?.args,
@@ -642,7 +605,7 @@ describe("docker session primitives", () => {
"disconnect",
"--force",
"bridge",
- fakeDockerContainerIdentity(SESSION_KEY),
+ fakeDockerContainerIdentity(PROVIDER_CONTAINER_NAME),
]);
});
@@ -658,151 +621,28 @@ describe("docker session primitives", () => {
},
});
- await handle.session.setNetworkPolicy("allow-all");
+ await handle.sandbox.setNetworkPolicy("allow-all");
const networkCalls = calls
.filter((call) => call.args[0] === "network")
.map((call) => call.args);
expect(networkCalls).toEqual([
- ["network", "disconnect", "--force", "none", fakeDockerContainerIdentity(SESSION_KEY)],
- ["network", "connect", "bridge", fakeDockerContainerIdentity(SESSION_KEY)],
- ]);
- });
-
- it("rejects domain-level network policies with guidance toward the Vercel backend", async () => {
- const { handle } = await createRunningSessionHandle({});
-
- await expect(handle.session.setNetworkPolicy({ allow: { "*": [] } })).rejects.toThrow(
- /Vercel backend/,
- );
- });
-
- it("applies deny-all after base setup for template-less containers", async () => {
- const appRoot = await createScratchDirectory("eve-docker-sandbox-");
- const { calls, cli } = createFakeDockerCli((args) => {
- if (isContainerInspect(args) && args[3] === "{{.State.Running}}") {
- return { exitCode: 1, stderr: "No such container" };
- }
- if (isContainerInspect(args) && args[3] === "{{json .NetworkSettings.Networks}}") {
- return { exitCode: 0, stdout: '{"bridge":{}}' };
- }
- return undefined;
- });
-
- await createEngine({
- cli,
- options: { networkPolicy: "deny-all" },
- }).create({
- runtimeContext: { appRoot },
- sessionKey: SESSION_KEY,
- templateKey: null,
- });
-
- const run = findCall(calls, (args) => args[0] === "run");
- expect(run?.args).not.toContain("--network");
-
- const baseSetup = findCall(calls, (args) => args[0] === "exec" && args.includes("/bin/sh"));
- expect(baseSetup?.args.at(-1)).toContain("command -v bash");
- expect(baseSetup?.args.at(-1)).not.toContain("apt-get");
- expect(baseSetup?.args.at(-1)).not.toContain("deb.nodesource.com/node_24.x");
- expect(baseSetup?.args.at(-1)).not.toContain("python3");
- expect(baseSetup?.args.at(-1)).not.toContain("ripgrep");
-
- expect(
- findCall(calls, (args) => args[0] === "network" && args[1] === "disconnect")?.args,
- ).toEqual(["network", "disconnect", "--force", "bridge", SESSION_KEY]);
- });
-});
-
-describe("pruneDockerSandboxTemplates", () => {
- it("removes images for stale markers and keeps retained or recent ones", async () => {
- const appRoot = await createScratchDirectory("eve-docker-sandbox-");
- const now = Date.now();
-
- // Seed three markers through real prewarm reuse so paths match the
- // engine's layout exactly.
- const { cli } = createFakeDockerCli((args) => {
- if (args[0] === "image" && args[1] === "inspect") {
- return { exitCode: 0, stdout: "sha256:abc\n" };
- }
- return undefined;
- });
- const engine = createEngine({ cli });
- for (const templateKey of ["tpl-stale", "tpl-retained", "tpl-recent"]) {
- await engine.prewarm({ runtimeContext: { appRoot }, seedFiles: [], templateKey });
- }
-
- const markersDirectory = join(appRoot, ".eve", "sandbox-cache", "docker", "templates");
- const { utimes } = await import("node:fs/promises");
- await utimes(
- join(markersDirectory, defaultDockerTemplateImageTag("tpl-stale")),
- new Date(now - 60_000),
- new Date(now - 60_000),
- );
- await utimes(
- join(markersDirectory, defaultDockerTemplateImageTag("tpl-retained")),
- new Date(now - 30_000),
- new Date(now - 30_000),
- );
-
- const { calls: pruneCalls, cli: pruneCli } = createFakeDockerCli();
- await pruneDockerSandboxTemplates({
- appRoot,
- dockerCli: pruneCli,
- now,
- recentWindowMs: 5_000,
- retainCount: 2,
- });
-
- expect(pruneCalls.map((call) => call.args)).toEqual([
[
- "rmi",
- dockerTemplateImageReference({
- optionsHash: DEFAULT_DOCKER_OPTIONS_HASH,
- templateKey: "tpl-stale",
- }),
+ "network",
+ "disconnect",
+ "--force",
+ "none",
+ fakeDockerContainerIdentity(PROVIDER_CONTAINER_NAME),
],
+ ["network", "connect", "bridge", fakeDockerContainerIdentity(PROVIDER_CONTAINER_NAME)],
]);
- const { readdir } = await import("node:fs/promises");
- await expect(readdir(markersDirectory)).resolves.toEqual(
- expect.arrayContaining([
- defaultDockerTemplateImageTag("tpl-recent"),
- defaultDockerTemplateImageTag("tpl-retained"),
- ]),
- );
});
- it("keeps the marker when the image is still referenced by a container", async () => {
- const appRoot = await createScratchDirectory("eve-docker-sandbox-");
- const { cli } = createFakeDockerCli((args) => {
- if (args[0] === "image" && args[1] === "inspect") {
- return { exitCode: 0, stdout: "sha256:abc\n" };
- }
- return undefined;
- });
- await createEngine({ cli }).prewarm({
- runtimeContext: { appRoot },
- seedFiles: [],
- templateKey: "tpl-in-use",
- });
-
- const { cli: pruneCli } = createFakeDockerCli((args) => {
- if (args[0] === "rmi") {
- return { exitCode: 1, stderr: "image is being used by running container" };
- }
- return undefined;
- });
- await pruneDockerSandboxTemplates({
- appRoot,
- dockerCli: pruneCli,
- now: Date.now() + 60_000,
- recentWindowMs: 1_000,
- retainCount: 0,
- });
+ it("rejects domain-level network policies with guidance toward the Vercel provider", async () => {
+ const { handle } = await createRunningSessionHandle({});
- const { readdir } = await import("node:fs/promises");
- await expect(
- readdir(join(appRoot, ".eve", "sandbox-cache", "docker", "templates")),
- ).resolves.toEqual([defaultDockerTemplateImageTag("tpl-in-use")]);
+ await expect(handle.sandbox.setNetworkPolicy({ allow: { "*": [] } })).rejects.toThrow(
+ /Vercel provider/,
+ );
});
});
diff --git a/packages/eve/src/execution/sandbox/bindings/docker.scenario.test.ts b/packages/eve/src/execution/sandbox/bindings/docker.scenario.test.ts
index 09e9eebde..e852c0d34 100644
--- a/packages/eve/src/execution/sandbox/bindings/docker.scenario.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/docker.scenario.test.ts
@@ -1,15 +1,22 @@
import { randomUUID } from "node:crypto";
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
import { afterAll, describe, expect, it, vi } from "vitest";
import { createDockerCli, DockerUnavailableError } from "#execution/sandbox/bindings/docker-cli.js";
-import { createDockerSandboxBackend } from "#execution/sandbox/bindings/docker.js";
+import { createDockerSandboxProvider } from "#execution/sandbox/bindings/docker.js";
import {
createDockerSandboxOptionsHash,
DEFAULT_DOCKER_SANDBOX_IMAGE,
resolveDockerSandboxOptions,
} from "#execution/sandbox/bindings/docker-options.js";
import { dockerTemplateImageReference } from "#execution/sandbox/bindings/docker-templates.js";
+import {
+ dockerfileImageReference,
+ resolveSandboxDockerfile,
+} from "#execution/sandbox/dockerfile.js";
+import { createSandboxProviderHarness } from "#internal/testing/sandbox-provider-harness.js";
import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";
// Real-daemon scenarios are opt-in: they pull images and create
@@ -23,16 +30,20 @@ const TEST_IMAGE = process.env.EVE_DOCKER_SANDBOX_TEST_IMAGE ?? DEFAULT_DOCKER_S
const createScratchDirectory = useTemporaryDirectories();
+function createEngine(options?: Parameters<typeof createDockerSandboxProvider>[0]) {
+ return createSandboxProviderHarness(createDockerSandboxProvider(options), undefined);
+}
+
describe("docker CLI resolution", () => {
it("fails with an actionable error when the docker executable is missing", async () => {
vi.stubEnv("EVE_DOCKER_PATH", "/nonexistent/docker-binary");
try {
const appRoot = await createScratchDirectory("eve-docker-missing-");
- const engine = createDockerSandboxBackend();
+ const engine = createEngine();
- await expect(
- engine.prewarm({ runtimeContext: { appRoot }, seedFiles: [], templateKey: "tpl-x" }),
- ).rejects.toThrow(DockerUnavailableError);
+ await expect(engine.prepare({ appRoot, seedFiles: [] })).rejects.toThrow(
+ DockerUnavailableError,
+ );
} finally {
vi.unstubAllEnvs();
}
@@ -47,6 +58,7 @@ describe.runIf(runDockerScenarios)("docker sandbox engine against a real daemon"
templateKey,
});
const sessionKeys: string[] = [];
+ const extraImages: string[] = [];
const cleanupCli = createDockerCli();
function nextSessionKey(label: string): string {
@@ -56,43 +68,96 @@ describe.runIf(runDockerScenarios)("docker sandbox engine against a real daemon"
}
function createEngine() {
- return createDockerSandboxBackend({ createOptions: { image: TEST_IMAGE } });
+ return createSandboxProviderHarness(
+ createDockerSandboxProvider({ image: TEST_IMAGE }),
+ undefined,
+ );
}
afterAll(async () => {
for (const sessionKey of sessionKeys) {
await cleanupCli.run(["rm", "-f", sessionKey]);
}
- await cleanupCli.run(["rmi", "-f", templateImageReference]);
+ await cleanupCli.run(["rmi", "-f", templateImageReference, ...extraImages]);
}, 60_000);
+ it(
+ "builds a colocated Dockerfile before prewarming the template",
+ async () => {
+ const appRoot = await createScratchDirectory("eve-dockerfile-scenario-");
+ const agentRoot = join(appRoot, "agent");
+ const sandboxRoot = join(agentRoot, "sandbox");
+ await mkdir(sandboxRoot, { recursive: true });
+ await writeFile(
+ join(sandboxRoot, "Dockerfile"),
+ `FROM ${TEST_IMAGE}\nUSER root\nRUN printf dockerfile-ready > /dockerfile-marker\nUSER vercel-sandbox\n`,
+ );
+ const resourcesPath = join(appRoot, "compiled-resources");
+ await mkdir(join(resourcesPath, "workspace"), { recursive: true });
+ await writeFile(join(resourcesPath, "workspace", "seed.txt"), "immutable seed");
+ const dockerfile = await resolveSandboxDockerfile(agentRoot);
+ expect(dockerfile).toBeDefined();
+ const dockerfileTemplateKey = `${templateKey}-dockerfile`;
+ const dockerfileTemplateImage = dockerTemplateImageReference({
+ optionsHash: createDockerSandboxOptionsHash(
+ resolveDockerSandboxOptions({ image: TEST_IMAGE }),
+ ),
+ templateKey: dockerfileTemplateKey,
+ });
+ extraImages.push(
+ dockerfileTemplateImage,
+ dockerfileImageReference({ dockerfile: dockerfile!, templateKey: dockerfileTemplateKey }),
+ );
+
+ const engine = createEngine();
+ await engine.prepare({
+ resourcesPath,
+ appRoot,
+ seedFiles: [],
+ });
+ const handle = await engine.openSession({
+ appRoot,
+ sandboxName: nextSessionKey("dockerfile"),
+ });
+
+ const result = await handle.sandbox.run({
+ command: [
+ "cat /dockerfile-marker",
+ "cat /workspace/seed.txt",
+ "! sh -c 'printf bad > /eve/resources/workspace/seed.txt' 2>/dev/null",
+ "printf changed > /workspace/seed.txt",
+ ].join(" && "),
+ });
+ expect(result).toMatchObject({
+ exitCode: 0,
+ stdout: "dockerfile-readyimmutable seed",
+ });
+ },
+ 5 * 60_000,
+ );
+
it(
"prewarms a template with seed files and opens a session from it",
async () => {
const appRoot = await createScratchDirectory("eve-docker-scenario-");
const engine = createEngine();
- const first = await engine.prewarm({
- runtimeContext: { appRoot },
+ const first = await engine.prepare({
+ appRoot,
seedFiles: [{ content: "# Weather skill\n", path: "/workspace/skills/weather.md" }],
- templateKey,
});
- expect(first).toEqual({ reused: false });
-
- const second = await engine.prewarm({
- runtimeContext: { appRoot },
+ const second = await engine.prepare({
+ appRoot,
seedFiles: [{ content: "# Weather skill\n", path: "/workspace/skills/weather.md" }],
- templateKey,
});
- expect(second).toEqual({ reused: true });
+ expect(second).toEqual(first);
- const handle = await engine.create({
- runtimeContext: { appRoot },
- sessionKey: nextSessionKey("seeded"),
- templateKey,
+ const handle = await engine.openSession({
+ appRoot,
+ sandboxName: nextSessionKey("seeded"),
});
- const result = await handle.session.run({
+ const result = await handle.sandbox.run({
command: "cat /workspace/skills/weather.md",
});
expect(result.exitCode).toBe(0);
@@ -106,20 +171,19 @@ describe.runIf(runDockerScenarios)("docker sandbox engine against a real daemon"
async () => {
const appRoot = await createScratchDirectory("eve-docker-scenario-");
const engine = createEngine();
- const handle = await engine.create({
- runtimeContext: { appRoot },
- sessionKey: nextSessionKey("env"),
- templateKey,
+ const handle = await engine.openSession({
+ appRoot,
+ sandboxName: nextSessionKey("env"),
});
- const result = await handle.session.run({
+ const result = await handle.sandbox.run({
command: 'echo "$DEPLOY_ENV"',
env: { DEPLOY_ENV: "staging" },
});
expect(result.exitCode).toBe(0);
expect(result.stdout.trim()).toBe("staging");
- const spawned = await handle.session.spawn({ command: "printf out; printf err >&2" });
+ const spawned = await handle.sandbox.spawn({ command: "printf out; printf err >&2" });
const [stdout, stderr, waited] = await Promise.all([
collectStream(spawned.stdout),
collectStream(spawned.stderr),
@@ -137,10 +201,9 @@ describe.runIf(runDockerScenarios)("docker sandbox engine against a real daemon"
async () => {
const appRoot = await createScratchDirectory("eve-docker-scenario-");
const engine = createEngine();
- const handle = await engine.create({
- runtimeContext: { appRoot },
- sessionKey: nextSessionKey("kill-tree"),
- templateKey,
+ const handle = await engine.openSession({
+ appRoot,
+ sandboxName: nextSessionKey("kill-tree"),
});
// Counts container processes whose cmdline matches the sentinel
@@ -159,11 +222,11 @@ describe.runIf(runDockerScenarios)("docker sandbox engine against a real daemon"
// A foreground child plus a backgrounded one exercises the
// recursive tree kill beyond the immediate wrapper pid.
- const spawned = await handle.session.spawn({ command: "sleep 327 & sleep 313" });
+ const spawned = await handle.sandbox.spawn({ command: "sleep 327 & sleep 313" });
let running = 0;
for (let attempt = 0; attempt < 50; attempt += 1) {
- const counted = await handle.session.run({ command: countSurvivors });
+ const counted = await handle.sandbox.run({ command: countSurvivors });
running = Number(counted.stdout.trim());
if (running >= 2) {
break;
@@ -175,7 +238,7 @@ describe.runIf(runDockerScenarios)("docker sandbox engine against a real daemon"
await spawned.kill();
await Promise.resolve(spawned.wait()).catch(() => {});
- const survivors = await handle.session.run({ command: countSurvivors });
+ const survivors = await handle.sandbox.run({ command: countSurvivors });
expect(survivors.exitCode).toBe(0);
expect(survivors.stdout.trim()).toBe("0");
},
@@ -187,29 +250,28 @@ describe.runIf(runDockerScenarios)("docker sandbox engine against a real daemon"
async () => {
const appRoot = await createScratchDirectory("eve-docker-scenario-");
const engine = createEngine();
- const handle = await engine.create({
- runtimeContext: { appRoot },
- sessionKey: nextSessionKey("files"),
- templateKey,
+ const handle = await engine.openSession({
+ appRoot,
+ sandboxName: nextSessionKey("files"),
});
- await handle.session.writeTextFile({ content: "hello", path: "deep/nested/note.txt" });
+ await handle.sandbox.writeTextFile({ content: "hello", path: "deep/nested/note.txt" });
await expect(
- handle.session.readTextFile({ path: "/workspace/deep/nested/note.txt" }),
+ handle.sandbox.readTextFile({ path: "/workspace/deep/nested/note.txt" }),
).resolves.toBe("hello");
const bytes = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0xff, 0x00]);
- await handle.session.writeBinaryFile({ content: bytes, path: "assets/fixture.bin" });
- const sized = await handle.session.run({ command: "wc -c < assets/fixture.bin" });
+ await handle.sandbox.writeBinaryFile({ content: bytes, path: "assets/fixture.bin" });
+ const sized = await handle.sandbox.run({ command: "wc -c < assets/fixture.bin" });
expect(Number(sized.stdout.trim())).toBe(bytes.length);
- const readBack = await handle.session.readBinaryFile({ path: "assets/fixture.bin" });
+ const readBack = await handle.sandbox.readBinaryFile({ path: "assets/fixture.bin" });
expect(readBack === null ? null : Buffer.from(readBack).equals(bytes)).toBe(true);
- await expect(handle.session.readTextFile({ path: "missing.txt" })).resolves.toBeNull();
+ await expect(handle.sandbox.readTextFile({ path: "missing.txt" })).resolves.toBeNull();
- await handle.session.removePath({ force: true, path: "deep", recursive: true });
+ await handle.sandbox.removePath({ force: true, path: "deep", recursive: true });
await expect(
- handle.session.readTextFile({ path: "deep/nested/note.txt" }),
+ handle.sandbox.readTextFile({ path: "deep/nested/note.txt" }),
).resolves.toBeNull();
},
5 * 60_000,
@@ -219,28 +281,28 @@ describe.runIf(runDockerScenarios)("docker sandbox engine against a real daemon"
"flips a deny-all-created session to allow-all and back",
async () => {
const appRoot = await createScratchDirectory("eve-docker-scenario-");
- const engine = createDockerSandboxBackend({
- createOptions: { image: TEST_IMAGE, networkPolicy: "deny-all" },
- });
+ const engine = createSandboxProviderHarness(
+ createDockerSandboxProvider({ image: TEST_IMAGE }),
+ { networkPolicy: "deny-all" },
+ );
// Create from the suite's prewarmed template: bash is already
// baked in there, which a `--network none` container could not
// install on the fly.
- const handle = await engine.create({
- runtimeContext: { appRoot },
- sessionKey: nextSessionKey("network-flip"),
- templateKey,
+ const handle = await engine.openSession({
+ appRoot,
+ sandboxName: nextSessionKey("network-flip"),
});
// `--network none` containers have no interfaces beyond loopback.
- const denied = await handle.session.run({ command: "ip route 2>/dev/null | wc -l" });
+ const denied = await handle.sandbox.run({ command: "ip route 2>/dev/null | wc -l" });
expect(denied.stdout.trim()).toBe("0");
- await handle.session.setNetworkPolicy("allow-all");
- const allowed = await handle.session.run({ command: "ip route 2>/dev/null | wc -l" });
+ await handle.sandbox.setNetworkPolicy("allow-all");
+ const allowed = await handle.sandbox.run({ command: "ip route 2>/dev/null | wc -l" });
expect(Number(allowed.stdout.trim())).toBeGreaterThan(0);
- await handle.session.setNetworkPolicy("deny-all");
- const deniedAgain = await handle.session.run({ command: "ip route 2>/dev/null | wc -l" });
+ await handle.sandbox.setNetworkPolicy("deny-all");
+ const deniedAgain = await handle.sandbox.run({ command: "ip route 2>/dev/null | wc -l" });
expect(deniedAgain.stdout.trim()).toBe("0");
},
5 * 60_000,
@@ -253,28 +315,25 @@ describe.runIf(runDockerScenarios)("docker sandbox engine against a real daemon"
const engine = createEngine();
const sessionKey = nextSessionKey("reconnect");
- const firstHandle = await engine.create({
- runtimeContext: { appRoot },
- sessionKey,
- templateKey,
+ const { handle: firstHandle, state } = await engine.start({
+ appRoot,
+ sandboxName: sessionKey,
});
- await firstHandle.session.writeTextFile({
+ await firstHandle.sandbox.writeTextFile({
content: "survives reconnect",
path: "persisted.txt",
});
- const state = await firstHandle.captureState();
- expect(state.metadata).toEqual({ containerName: sessionKey });
+ expect(state).toMatchObject({ version: 2 });
// Server shutdown stops the container; reattach must restart it
// transparently.
- await firstHandle.shutdown();
+ await firstHandle.onRuntimeShutdown();
- const reconnected = await engine.create({
- existingMetadata: state.metadata,
- runtimeContext: { appRoot },
- sessionKey,
- templateKey,
+ const reconnected = await engine.openSession({
+ existing: state,
+ appRoot,
+ sandboxName: sessionKey,
});
- await expect(reconnected.session.readTextFile({ path: "persisted.txt" })).resolves.toBe(
+ await expect(reconnected.sandbox.readTextFile({ path: "persisted.txt" })).resolves.toBe(
"survives reconnect",
);
},
diff --git a/packages/eve/src/execution/sandbox/bindings/docker.test.ts b/packages/eve/src/execution/sandbox/bindings/docker.test.ts
index a03532993..c52e17327 100644
--- a/packages/eve/src/execution/sandbox/bindings/docker.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/docker.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from "vitest";
-import { createDockerSandboxBackend } from "#execution/sandbox/bindings/docker.js";
+import { createDockerSandboxProvider } from "#execution/sandbox/bindings/docker.js";
+import { createSandboxProviderHarness } from "#internal/testing/sandbox-provider-harness.js";
import type { DockerCli } from "#execution/sandbox/bindings/docker-cli.js";
describe("Docker sandbox deletion", () => {
@@ -22,15 +23,18 @@ describe("Docker sandbox deletion", () => {
throw new Error("stream is not used by this test");
},
};
- const backend = createDockerSandboxBackend({ dockerCli });
- const handle = await backend.create({
- runtimeContext: { appRoot: "/tmp/eve-app" },
- sessionKey: "session-key",
- templateKey: null,
+ const provider = createSandboxProviderHarness(
+ createDockerSandboxProvider(undefined, dockerCli),
+ {},
+ { preparedArtifact: () => ({ imageReference: "prepared-image" }) },
+ );
+ const handle = await provider.openSession({
+ appRoot: "/tmp/eve-app",
+ sandboxName: "session-key",
});
vi.mocked(run).mockClear();
- await handle.delete();
+ await handle.onSessionDelete();
expect(run).toHaveBeenNthCalledWith(1, ["stop", "-t", "0", "container-id-1"]);
expect(run).toHaveBeenNthCalledWith(2, ["rm", "-f", "container-id-1"]);
@@ -55,22 +59,24 @@ describe("Docker sandbox deletion", () => {
throw new Error("stream is not used by this test");
},
};
- const backend = createDockerSandboxBackend({ dockerCli });
- const oldHandle = await backend.create({
- runtimeContext: { appRoot: "/tmp/eve-app" },
- sessionKey: "session-key",
- templateKey: null,
+ const provider = createSandboxProviderHarness(
+ createDockerSandboxProvider(undefined, dockerCli),
+ {},
+ { preparedArtifact: () => ({ imageReference: "prepared-image" }) },
+ );
+ const oldHandle = await provider.openSession({
+ appRoot: "/tmp/eve-app",
+ sandboxName: "session-key",
});
- await oldHandle.delete();
+ await oldHandle.onSessionDelete();
containerId = "container-id-2";
- await backend.create({
- runtimeContext: { appRoot: "/tmp/eve-app" },
- sessionKey: "session-key",
- templateKey: null,
+ await provider.openSession({
+ appRoot: "/tmp/eve-app",
+ sandboxName: "session-key",
});
vi.mocked(run).mockClear();
- await oldHandle.session.writeTextFile({ content: "stale", path: "/workspace/stale.txt" });
+ await oldHandle.sandbox.writeTextFile({ content: "stale", path: "/workspace/stale.txt" });
expect(run).toHaveBeenCalledWith(
expect.arrayContaining(["container-id-1"]),
diff --git a/packages/eve/src/execution/sandbox/bindings/docker.ts b/packages/eve/src/execution/sandbox/bindings/docker.ts
index 35275b27a..7e59f8490 100644
--- a/packages/eve/src/execution/sandbox/bindings/docker.ts
+++ b/packages/eve/src/execution/sandbox/bindings/docker.ts
@@ -1,3 +1,4 @@
+import type { MutableNetworkSandboxSession } from "#shared/sandbox-session.js";
import { randomUUID } from "node:crypto";
import {
@@ -25,18 +26,30 @@ import {
touchDockerTemplateMarker,
} from "#execution/sandbox/bindings/docker-templates.js";
import { expectDockerSuccess } from "#execution/sandbox/bindings/docker-utils.js";
-import { writeSandboxSeedFiles } from "#execution/sandbox/bindings/local-backend-utils.js";
+import {
+ buildSandboxDockerfile,
+ dockerfileImageReference,
+ materializeSandboxDockerfile,
+} from "#execution/sandbox/dockerfile.js";
+import {
+ hydrateSandboxProviderResources,
+ prepareImmutableResources,
+} from "#execution/sandbox/bindings/immutable-resources.js";
import { createLoggingSandboxSession } from "#execution/sandbox/logging-session.js";
import { buildSandboxSession } from "#execution/sandbox/session.js";
+import { createSandboxProviderIdentity } from "#execution/sandbox/provider-identity.js";
+import {
+ isSandboxPreparedArtifactRecord,
+ sandboxProviderResourceIdentity,
+ type SandboxPreparedArtifact,
+ type SandboxProviderImplementation,
+ type SandboxProviderSessionContext,
+} from "#shared/sandbox-provider.js";
+import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";
import type {
- SandboxBackend,
- SandboxBackendCreateInput,
- SandboxBackendHandle,
- SandboxBackendPrewarmInput,
- SandboxBackendPrewarmResult,
-} from "#public/definitions/sandbox-backend.js";
-import { SandboxTemplateNotProvisionedError } from "#public/definitions/sandbox-backend.js";
-import type { DockerSandboxCreateOptions } from "#public/sandbox/docker-sandbox.js";
+ DockerSandboxEnvironmentOptions,
+ DockerSandboxRuntimeOptions,
+} from "#public/sandbox/docker-sandbox.js";
export {
DOCKER_TEMPLATE_IMAGE_REPOSITORY,
@@ -44,40 +57,44 @@ export {
} from "#execution/sandbox/bindings/docker-templates.js";
/**
- * Stable backend name. Participates in template/session key derivation
- * and persisted reconnect state.
+ * Stable provider name used for prepared-artifact storage and provider identity.
*/
-export const DOCKER_BACKEND_NAME = "docker";
+export const DOCKER_PROVIDER_NAME = "docker";
-/**
- * Construction input for {@link createDockerSandboxBackend}. Internal —
- * the public surface is the `docker()` factory under
- * `eve/sandbox`.
- */
-export interface CreateDockerSandboxBackendInput {
- readonly createOptions?: DockerSandboxCreateOptions;
- /** Injectable Docker driver so backend logic is testable without a daemon. */
- readonly dockerCli?: DockerCli;
-}
+type DockerSandboxPreparedArtifact = {
+ readonly imageReference: string;
+};
+type DockerSandboxSessionState = {
+ readonly containerName: string;
+ readonly generation: string;
+ readonly version: 2;
+};
/**
- * Creates the Docker sandbox backend.
+ * Creates the Docker sandbox provider.
*
* Two-phase lifecycle mapped onto Docker primitives:
*
* - `prewarm` runs the base image, applies base setup, runs the
- * authored `bootstrap`, writes seed files, then `docker commit`s the
+ * authored preparation, writes seed files, then `docker commit`s the
* container into a reusable template image.
* - `create` starts (or restarts) one long-lived container per session
* key from the template image. The container's filesystem carries
* session state across reconnects, so `shutdown` only stops the
* container and the next `create` restarts it with state intact.
*/
-export function createDockerSandboxBackend(
- input: CreateDockerSandboxBackendInput = {},
-): SandboxBackend {
- const cli = input.dockerCli ?? createDockerCli();
- const options = resolveDockerSandboxOptions(input.createOptions);
+export function createDockerSandboxProvider(
+ createOptions?: DockerSandboxEnvironmentOptions,
+ dockerCli?: DockerCli,
+): SandboxProviderImplementation<
+ DockerSandboxRuntimeOptions,
+ DockerSandboxPreparedArtifact,
+ DockerSandboxSessionState,
+ MutableNetworkSandboxSession
+> {
+ const cli = dockerCli ?? createDockerCli();
+ const authoredOptions = createOptions ?? {};
+ const options = resolveDockerSandboxOptions(authoredOptions);
const optionsHash = createDockerSandboxOptionsHash(options);
let daemonCheck: Promise<void> | undefined;
@@ -89,83 +106,176 @@ export function createDockerSandboxBackend(
return daemonCheck;
}
+ async function openDockerSession(
+ context: SandboxProviderSessionContext,
+ openOptions: Readonly<DockerSandboxRuntimeOptions> | undefined,
+ artifactValue: SandboxPreparedArtifact,
+ containerName: string,
+ createIfMissing: boolean,
+ ) {
+ await ensureDaemon();
+ const artifact = requirePreparedDockerArtifact(artifactValue);
+ if (!(await dockerImageExists(cli, artifact.imageReference))) {
+ throw new SandboxTemplateNotProvisionedError({
+ providerName: DOCKER_PROVIDER_NAME,
+ templateKey: artifact.imageReference,
+ });
+ }
+ const inspect = await cli.run([
+ "container",
+ "inspect",
+ "--format",
+ "{{.State.Running}}",
+ containerName,
+ ]);
+ if (inspect.exitCode === 0) {
+ if (inspect.stdout.trim() !== "true") {
+ expectDockerSuccess(
+ await cli.run(["start", containerName]),
+ `restart sandbox session container "${containerName}"`,
+ );
+ }
+ } else {
+ if (!createIfMissing) {
+ throw new Error(`Docker sandbox session container "${containerName}" no longer exists.`);
+ }
+ await startDockerContainer({
+ cli,
+ containerName,
+ image: artifact.imageReference,
+ initialNetworkPolicy: openOptions?.networkPolicy ?? "allow-all",
+ options,
+ role: "session",
+ tags: {
+ agent: context.session.id,
+ sessionId: context.session.id,
+ },
+ });
+ }
+ const containerIdentity = await resolveDockerHandleIdentity(cli, containerName);
+ const session = buildSandboxSession(
+ createDockerInternalSession({ cli, containerIdentity }),
+ (policy) => setDockerNetworkPolicy(cli, containerIdentity, policy),
+ );
+ return {
+ sandbox: session,
+ async onSessionDelete() {
+ await stopDockerContainerIfRunning(cli, containerIdentity);
+ expectDockerSuccess(
+ await cli.run(["rm", "-f", containerIdentity]),
+ `delete sandbox session container "${containerName}"`,
+ );
+ },
+ async onSessionStop() {
+ await stopDockerContainerIfRunning(cli, containerIdentity);
+ },
+ async onRuntimeShutdown() {
+ await stopDockerContainerIfRunning(cli, containerIdentity);
+ },
+ };
+ }
+
return {
- name: DOCKER_BACKEND_NAME,
- async prewarm(prewarmInput: SandboxBackendPrewarmInput): Promise<SandboxBackendPrewarmResult> {
- prewarmInput.log?.("checking Docker daemon");
+ async prepare(context) {
+ context.log?.("checking Docker daemon");
await ensureDaemon();
- const templateReferenceInput = {
+ const dockerfile = await materializeSandboxDockerfile({
+ files: context.files,
+ storagePath: context.storagePath,
+ });
+ const templateKey = createSandboxProviderIdentity({
+ dockerfile: dockerfile?.contentHash,
optionsHash,
- templateKey: prewarmInput.templateKey,
- };
+ resources: sandboxProviderResourceIdentity(context.resources),
+ sourceRevision: context.sourceRevision,
+ version: 2,
+ }).slice(0, 24);
+ const templateReferenceInput = { optionsHash, templateKey };
const imageReference = dockerTemplateImageReference(templateReferenceInput);
+ const resourceSource = context.resources.source;
+ const resourcesPath =
+ resourceSource.kind === "materialized"
+ ? await prepareImmutableResources({
+ storagePath: context.storagePath,
+ provider: DOCKER_PROVIDER_NAME,
+ resourcesKey: resourceSource.key,
+ sourcePath: resourceSource.path,
+ })
+ : undefined;
const markerPath = resolveDockerTemplateMarkerPath(
- prewarmInput.runtimeContext.appRoot,
+ context.storagePath,
templateReferenceInput,
);
- prewarmInput.log?.(`checking cached template image "${imageReference}"`);
+ context.log?.(`checking cached template image "${imageReference}"`);
if (await dockerImageExists(cli, imageReference)) {
- prewarmInput.log?.("reusing cached template image");
+ context.log?.("reusing cached template image");
await touchDockerTemplateMarker(markerPath, imageReference);
- return { reused: true };
+ return { imageReference };
}
- prewarmInput.log?.(`checking base image "${options.image}"`);
- await ensureDockerBaseImage(cli, options);
+ let baseImage = options.image;
+ if (dockerfile === undefined) {
+ context.log?.(`checking base image "${options.image}"`);
+ await ensureDockerBaseImage(cli, options);
+ } else {
+ baseImage = dockerfileImageReference({
+ dockerfile,
+ templateKey,
+ });
+ context.log?.(`building sandbox Dockerfile "${dockerfile.path}"`);
+ await buildSandboxDockerfile({
+ cli,
+ dockerfile,
+ imageReference: baseImage,
+ });
+ }
- const buildContainerName = `${prewarmInput.templateKey}-build-${randomUUID().slice(0, 8)}`;
- prewarmInput.log?.("starting template build container");
+ const buildContainerName = `${templateKey}-build-${randomUUID().slice(0, 8)}`;
+ context.log?.("starting template build container");
await startDockerContainer({
cli,
containerName: buildContainerName,
- image: options.image,
+ image: baseImage,
initialNetworkPolicy: "allow-all",
options,
+ resourcesPath,
role: "template-build",
});
try {
const buildContainerIdentity = await resolveDockerHandleIdentity(cli, buildContainerName);
- prewarmInput.log?.("preparing base runtime inside container");
+ context.log?.("preparing base runtime inside container");
await runDockerBaseSetup(cli, buildContainerIdentity);
- if (options.networkPolicy !== "allow-all") {
- prewarmInput.log?.("applying network policy");
- await setDockerNetworkPolicy(cli, buildContainerIdentity, options.networkPolicy);
- }
-
const templateSession = buildSandboxSession(
createDockerInternalSession({
cli,
containerIdentity: buildContainerIdentity,
- id: prewarmInput.templateKey,
}),
(policy) => setDockerNetworkPolicy(cli, buildContainerIdentity, policy),
);
- if (prewarmInput.seedFiles.length > 0) {
- prewarmInput.log?.(`writing ${prewarmInput.seedFiles.length} seed file(s)`);
- }
- await writeSandboxSeedFiles(templateSession, prewarmInput.seedFiles);
+ await hydrateSandboxProviderResources({
+ copySkills: true,
+ log: context.log,
+ resources: context.resources,
+ session: templateSession,
+ });
- if (prewarmInput.bootstrap !== undefined) {
- prewarmInput.log?.("running sandbox bootstrap");
- await prewarmInput.bootstrap({
- use: async () =>
- createLoggingSandboxSession({
- log: prewarmInput.log,
- session: templateSession,
- }),
- });
+ if (authoredOptions.prepare !== undefined) {
+ context.log?.("running sandbox preparation");
+ await authoredOptions.prepare(
+ createLoggingSandboxSession({ log: context.log, session: templateSession }),
+ );
}
// Quiesce before commit so the captured filesystem is stable.
- prewarmInput.log?.("stopping template build container");
+ context.log?.("stopping template build container");
expectDockerSuccess(
await cli.run(["stop", "-t", "0", buildContainerIdentity]),
`stop template build container "${buildContainerName}"`,
);
- prewarmInput.log?.(`committing template image "${imageReference}"`);
+ context.log?.(`committing template image "${imageReference}"`);
expectDockerSuccess(
await cli.run([
"commit",
@@ -174,7 +284,7 @@ export function createDockerSandboxBackend(
"--change",
`LABEL ${DOCKER_SANDBOX_LABEL}.role=template`,
"--change",
- `LABEL ${DOCKER_SANDBOX_LABEL}.template-key=${prewarmInput.templateKey}`,
+ `LABEL ${DOCKER_SANDBOX_LABEL}.template-key=${templateKey}`,
buildContainerIdentity,
imageReference,
]),
@@ -185,122 +295,72 @@ export function createDockerSandboxBackend(
await cli.run(["rm", "-f", buildContainerName]).catch(() => {});
}
- return { reused: false };
+ return { imageReference };
},
- async create(createInput: SandboxBackendCreateInput): Promise<SandboxBackendHandle> {
- await ensureDaemon();
- const containerName =
- getDockerContainerName(createInput.existingMetadata) ?? createInput.sessionKey;
-
- const inspect = await cli.run([
- "container",
- "inspect",
- "--format",
- "{{.State.Running}}",
- containerName,
- ]);
-
- if (inspect.exitCode === 0) {
- if (inspect.stdout.trim() !== "true") {
- expectDockerSuccess(
- await cli.run(["start", containerName]),
- `restart sandbox session container "${containerName}"`,
- );
- }
- } else {
- let image: string;
- if (createInput.templateKey === null) {
- await ensureDockerBaseImage(cli, options);
- image = options.image;
- } else {
- const templateReferenceInput = {
- optionsHash,
- templateKey: createInput.templateKey,
- };
- image = dockerTemplateImageReference(templateReferenceInput);
- if (!(await dockerImageExists(cli, image))) {
- throw new SandboxTemplateNotProvisionedError({
- backendName: DOCKER_BACKEND_NAME,
- templateKey: createInput.templateKey,
- });
- }
- await touchDockerTemplateMarker(
- resolveDockerTemplateMarkerPath(
- createInput.runtimeContext.appRoot,
- templateReferenceInput,
- ),
- image,
- );
- }
-
- try {
- await startDockerContainer({
- cli,
- containerName,
- image,
- initialNetworkPolicy:
- createInput.templateKey === null ? "allow-all" : options.networkPolicy,
- options,
- role: "session",
- tags: createInput.tags,
- });
- } catch (error) {
- if (createInput.templateKey !== null) {
- throw new SandboxTemplateNotProvisionedError({
- backendName: DOCKER_BACKEND_NAME,
- templateKey: createInput.templateKey,
- });
- }
- throw error;
- }
-
- if (createInput.templateKey === null) {
- await runDockerBaseSetup(cli, containerName);
- if (options.networkPolicy !== "allow-all") {
- await setDockerNetworkPolicy(cli, containerName, options.networkPolicy);
- }
- }
+ async resume(context, artifactValue, stateValue) {
+ const state = requireDockerSessionState(stateValue);
+ if (state.generation !== dockerGeneration(artifactValue, optionsHash)) {
+ throw new Error("Docker sandbox session state is incompatible with this environment.");
}
-
- const containerIdentity = await resolveDockerHandleIdentity(cli, containerName);
- const session = buildSandboxSession(
- createDockerInternalSession({ cli, containerIdentity, id: createInput.sessionKey }),
- (policy) => setDockerNetworkPolicy(cli, containerIdentity, policy),
+ return await openDockerSession(context, undefined, artifactValue, state.containerName, false);
+ },
+ async start(context, openOptions, artifactValue) {
+ const containerName = dockerSessionName(
+ context.session.id,
+ openOptions,
+ artifactValue,
+ optionsHash,
);
-
return {
- session,
- useSessionFn: async () => session,
- async captureState() {
- return {
- backendName: DOCKER_BACKEND_NAME,
- metadata: { containerName },
- sessionKey: createInput.sessionKey,
- };
- },
- async delete() {
- await stopDockerContainerIfRunning(cli, containerIdentity);
- expectDockerSuccess(
- await cli.run(["rm", "-f", containerIdentity]),
- `delete sandbox session container "${containerName}"`,
- );
- },
- async stop() {
- await stopDockerContainerIfRunning(cli, containerIdentity);
- },
- // Session state lives in the container filesystem, so a stopped
- // container restarts with state intact on the next `create`.
- async shutdown() {
- await stopDockerContainerIfRunning(cli, containerIdentity);
+ handle: await openDockerSession(context, openOptions, artifactValue, containerName, true),
+ state: {
+ containerName,
+ generation: dockerGeneration(artifactValue, optionsHash),
+ version: 2,
},
};
},
};
}
-function getDockerContainerName(metadata: Record<string, unknown> | undefined): string | undefined {
- const containerName = metadata?.containerName;
- return typeof containerName === "string" ? containerName : undefined;
+function dockerGeneration(artifact: SandboxPreparedArtifact, optionsHash: string): string {
+ return createSandboxProviderIdentity({ artifact, environment: optionsHash, version: 1 });
+}
+
+function dockerSessionName(
+ sessionId: string,
+ options: Readonly<DockerSandboxRuntimeOptions> | undefined,
+ artifact: SandboxPreparedArtifact,
+ optionsHash: string,
+): string {
+ return `eve-sbx-${createSandboxProviderIdentity({
+ artifact,
+ environment: optionsHash,
+ open: { networkPolicy: options?.networkPolicy },
+ sessionId,
+ version: 1,
+ }).slice(0, 32)}`;
+}
+
+function requirePreparedDockerArtifact(
+ artifact: SandboxPreparedArtifact,
+): DockerSandboxPreparedArtifact {
+ if (!isSandboxPreparedArtifactRecord(artifact) || typeof artifact.imageReference !== "string") {
+ throw new Error("Invalid prepared Docker artifact.");
+ }
+ return { imageReference: artifact.imageReference };
+}
+
+function requireDockerSessionState(state: SandboxPreparedArtifact): DockerSandboxSessionState {
+ if (
+ !isSandboxPreparedArtifactRecord(state) ||
+ state.version !== 2 ||
+ typeof state.containerName !== "string" ||
+ typeof state.generation !== "string"
+ ) {
+ throw new Error("Invalid Docker sandbox session state.");
+ }
+ return { containerName: state.containerName, generation: state.generation, version: 2 };
}
async function resolveDockerHandleIdentity(cli: DockerCli, containerName: string): Promise<string> {
diff --git a/packages/eve/src/execution/sandbox/bindings/immutable-resources.test.ts b/packages/eve/src/execution/sandbox/bindings/immutable-resources.test.ts
new file mode 100644
index 000000000..b6316d9a4
--- /dev/null
+++ b/packages/eve/src/execution/sandbox/bindings/immutable-resources.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { hydrateSandboxFromImmutableResources } from "#execution/sandbox/bindings/immutable-resources.js";
+
+describe("hydrateSandboxFromImmutableResources", () => {
+ it("copies workspace seed files and links skills to the read-only mount", async () => {
+ const run = vi.fn(async (_input: { readonly command: string }) => ({
+ exitCode: 0,
+ stderr: "",
+ stdout: "",
+ }));
+ await hydrateSandboxFromImmutableResources({ run } as never);
+ const command = run.mock.calls[0]?.[0].command ?? "";
+ expect(command).toContain("cp -a /eve/resources/workspace/. /workspace/");
+ expect(command).toContain('ln -s /eve/resources/skills "$HOME/.agents/skills"');
+ expect(command).not.toContain("cp -a /eve/resources/skills");
+ });
+
+ it("copies skills when the prepared image must retain them without the mount", async () => {
+ const run = vi.fn(async (_input: { readonly command: string }) => ({
+ exitCode: 0,
+ stderr: "",
+ stdout: "",
+ }));
+ await hydrateSandboxFromImmutableResources({ run } as never, true);
+ const command = run.mock.calls[0]?.[0].command ?? "";
+ expect(command).toContain('cp -a /eve/resources/skills/. "$HOME/.agents/skills/"');
+ expect(command).not.toContain("ln -s /eve/resources/skills");
+ });
+});
diff --git a/packages/eve/src/execution/sandbox/bindings/immutable-resources.ts b/packages/eve/src/execution/sandbox/bindings/immutable-resources.ts
new file mode 100644
index 000000000..89076ad4c
--- /dev/null
+++ b/packages/eve/src/execution/sandbox/bindings/immutable-resources.ts
@@ -0,0 +1,76 @@
+import { join } from "node:path";
+
+import {
+ copyDirectoryAtomically,
+ writeSandboxSeedFiles,
+} from "#execution/sandbox/bindings/local-provider-utils.js";
+import {
+ providerResourceTargetFiles,
+ type SandboxProviderResources,
+} from "#shared/sandbox-provider.js";
+import type { SandboxSession } from "#shared/sandbox-session.js";
+
+export const SANDBOX_RESOURCES_ROOT = "/eve/resources";
+
+export function resolveImmutableResourcesPath(input: {
+ readonly storagePath: string;
+ readonly provider: string;
+ readonly resourcesKey: string;
+}): string {
+ return join(input.storagePath, input.provider, "resources", input.resourcesKey);
+}
+
+export async function prepareImmutableResources(input: {
+ readonly storagePath: string;
+ readonly provider: string;
+ readonly resourcesKey: string;
+ readonly sourcePath: string;
+}): Promise<string> {
+ const path = resolveImmutableResourcesPath(input);
+ await copyDirectoryAtomically(input.sourcePath, path);
+ return path;
+}
+
+export async function hydrateSandboxProviderResources(input: {
+ readonly copySkills?: boolean;
+ readonly log?: (message: string) => void;
+ readonly resources: SandboxProviderResources;
+ readonly session: SandboxSession;
+}): Promise<void> {
+ switch (input.resources.source.kind) {
+ case "none":
+ case "inline":
+ await writeSandboxSeedFiles(input.session, providerResourceTargetFiles(input.resources));
+ return;
+ case "materialized":
+ input.log?.("hydrating workspace and skills from read-only resources");
+ await hydrateSandboxFromImmutableResources(input.session, input.copySkills);
+ return;
+ }
+}
+
+export async function hydrateSandboxFromImmutableResources(
+ session: SandboxSession,
+ copySkills = false,
+): Promise<void> {
+ const hydrateSkills = copySkills
+ ? [
+ ' mkdir -p "$HOME/.agents/skills"',
+ ` cp -a ${SANDBOX_RESOURCES_ROOT}/skills/. "$HOME/.agents/skills/"`,
+ ]
+ : [` ln -s ${SANDBOX_RESOURCES_ROOT}/skills "$HOME/.agents/skills"`];
+ 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`,
+ ' mkdir -p "$HOME/.agents"',
+ ' rm -rf "$HOME/.agents/skills"',
+ ...hydrateSkills,
+ "fi",
+ ].join("\n"),
+ });
+ if (result.exitCode !== 0) {
+ throw new Error(`Failed to hydrate sandbox resources: ${result.stderr || result.stdout}`);
+ }
+}
diff --git a/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.integration.test.ts b/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.integration.test.ts
index af8166e41..2450318ea 100644
--- a/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.integration.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.integration.test.ts
@@ -15,7 +15,7 @@ describe("just-bash sandbox deletion", () => {
await writeFile(join(rootPath, "state.txt"), "persisted");
const dispose = vi.fn(async () => {});
const sandbox = {
- captureState: vi.fn(async () => null),
+ captureState: vi.fn(async () => ({ rootPath })),
dispose,
readFileBytes: vi.fn(async () => null),
removePath: vi.fn(async () => {}),
@@ -26,9 +26,9 @@ describe("just-bash sandbox deletion", () => {
},
writeFiles: vi.fn(async () => {}),
} satisfies BashSandbox;
- const handle = createJustBashHandle(sandbox, "just-bash");
+ const handle = createJustBashHandle(sandbox);
- await handle.delete();
+ await handle.onSessionDelete();
expect(dispose).toHaveBeenCalledTimes(1);
await expect(access(rootPath)).rejects.toMatchObject({ code: "ENOENT" });
diff --git a/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.ts b/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.ts
index 459d85161..bfed0ee71 100644
--- a/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.ts
+++ b/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.ts
@@ -6,12 +6,12 @@ import type { IFileSystem } from "just-bash";
import {
createFileBackedInternalSandboxSession,
pathExists,
-} from "#execution/sandbox/bindings/local-backend-utils.js";
+} from "#execution/sandbox/bindings/local-provider-utils.js";
import { adaptMultiplexedCommandToSandboxProcess } from "#execution/sandbox/multiplexed-command.js";
import { shellQuote } from "#execution/sandbox/shell-quote.js";
import { buildSandboxSession } from "#execution/sandbox/session.js";
-import { loadOptionalEnginePackage } from "#internal/application/optional-package-install.js";
-import type { SandboxBackendHandle } from "#public/definitions/sandbox-backend.js";
+import type { SandboxProviderHandle, SandboxProviderHost } from "#shared/sandbox-provider.js";
+import type { FixedNetworkSandboxSession } from "#shared/sandbox-session.js";
import type { JustBashSandboxCreateOptions } from "#public/sandbox/just-bash-sandbox.js";
import { WORKSPACE_ROOT } from "#runtime/workspace/types.js";
import type {
@@ -32,8 +32,12 @@ interface LocalSandboxMetadata {
readonly version: typeof LOCAL_SANDBOX_METADATA_VERSION;
}
+export interface JustBashSessionMetadata {
+ readonly rootPath: string;
+}
+
export interface BashSandbox {
- captureState(): Promise<Record<string, unknown> | null>;
+ captureState(): Promise<JustBashSessionMetadata>;
dispose(): Promise<void>;
readFileBytes(path: string): Promise<Buffer | null>;
removePath(options: SandboxRemovePathOptions): Promise<void>;
@@ -47,42 +51,44 @@ let justBashModulePromise: Promise<JustBashModule> | undefined;
/**
* Loads `just-bash` from the application's own dependency tree. The
- * package is intentionally not bundled with eve — the backend is
+ * package is intentionally not bundled with eve — the provider is
* opt-in — so when it is missing eve installs it into the project
* during `eve dev` (unless `autoInstall: false`) and otherwise fails
* with an actionable install error.
*/
async function loadJustBashModule(input: {
- readonly appRoot: string;
readonly autoInstall: boolean;
+ readonly host: SandboxProviderHost;
}): Promise<JustBashModule> {
- justBashModulePromise ??= loadOptionalEnginePackage<JustBashModule>({
- appRoot: input.appRoot,
- autoInstall: input.autoInstall,
- importModule: async () => await import("just-bash"),
- missingMessage:
- "The just-bash sandbox backend requires the `just-bash` package, which is not bundled " +
- "with eve. Install it in your application (for example `pnpm add -D just-bash`), or use " +
- "docker() / defaultSandbox() instead.",
- packageName: JUST_BASH_PACKAGE_NAME,
- }).catch((error: unknown) => {
- justBashModulePromise = undefined;
- throw error;
- });
+ justBashModulePromise ??= input.host
+ .loadOptionalPackage<JustBashModule>({
+ autoInstall: input.autoInstall,
+ importModule: async () => await import("just-bash"),
+ missingMessage:
+ "The just-bash sandbox provider requires the `just-bash` package, which is not bundled " +
+ "with eve. Install it in your application (for example `pnpm add -D just-bash`), or use " +
+ "DockerSandbox or DefaultSandbox instead.",
+ packageName: JUST_BASH_PACKAGE_NAME,
+ })
+ .catch((error: unknown) => {
+ justBashModulePromise = undefined;
+ throw error;
+ });
return await justBashModulePromise;
}
export async function createBashSandbox(input: {
- readonly appRoot: string;
readonly autoInstall: boolean;
+ readonly host: SandboxProviderHost;
readonly customCommands?: JustBashSandboxCreateOptions["customCommands"];
readonly filesystem?: JustBashSandboxCreateOptions["filesystem"];
readonly rootPath: string;
readonly sessionKey: string;
+ readonly storagePath: string;
}): Promise<BashSandbox> {
const justBash = await loadJustBashModule({
- appRoot: input.appRoot,
autoInstall: input.autoInstall,
+ host: input.host,
});
const { ReadWriteFs, Sandbox } = justBash;
const filesystemRootPath = resolveLocalSandboxFilesystemRootPath(input.rootPath);
@@ -100,8 +106,9 @@ export async function createBashSandbox(input: {
if (input.filesystem !== undefined) {
try {
filesystem = await input.filesystem({
- appRoot: input.appRoot,
defaultFilesystem,
+ resolveProjectPath: input.host.resolveProjectPath,
+ storagePath: input.storagePath,
justBash,
});
} catch (error) {
@@ -114,7 +121,7 @@ export async function createBashSandbox(input: {
const sandbox = await Sandbox.create({
cwd: WORKSPACE_ROOT,
customCommands: input.customCommands === undefined ? undefined : [...input.customCommands],
- env: metadata?.env as Record<string, string> | undefined,
+ env: metadata === null ? undefined : { ...metadata.env },
fs: filesystem,
network: {
dangerouslyAllowFullInternetAccess: true,
@@ -195,44 +202,22 @@ export async function createBashSandbox(input: {
* Throw rather than silently no-op so brokering code surfaces the gap instead
* of leaking.
*/
-export async function justBashSetNetworkPolicyUnsupported(): Promise<never> {
- throw new Error(
- "setNetworkPolicy() is not supported on the just-bash sandbox backend. just-bash " +
- "applies its network policy only at sandbox creation (no run-time update) and does not run " +
- "git or other binaries. Use docker() for coarse egress control or vercel() / " +
- "microsandbox() for credential brokering.",
- );
-}
-
export function createJustBashHandle(
sandbox: BashSandbox,
- backendName: string,
-): SandboxBackendHandle {
- const session = buildSandboxSession(
- createFileBackedInternalSandboxSession({ id: sandbox.sessionKey, sandbox }),
- justBashSetNetworkPolicyUnsupported,
- );
+): SandboxProviderHandle<FixedNetworkSandboxSession> {
+ const session = buildSandboxSession(createFileBackedInternalSandboxSession({ sandbox }));
return {
- session,
- useSessionFn: async () => session,
- async captureState() {
- const metadata = (await sandbox.captureState()) ?? {};
- return {
- backendName,
- metadata,
- sessionKey: sandbox.sessionKey,
- };
- },
- async delete() {
+ sandbox: session,
+ async onSessionDelete() {
await sandbox.dispose();
await rm(sandbox.rootPath, { force: true, recursive: true });
},
- async stop() {
+ async onSessionStop() {
await sandbox.dispose();
},
// The interpreter lives in this process, so stopping it is all the
// shutdown a just-bash sandbox needs.
- async shutdown() {
+ async onRuntimeShutdown() {
await sandbox.dispose();
},
};
@@ -257,11 +242,13 @@ async function readLocalMetadata(metadataPath: string): Promise<LocalSandboxMeta
return null;
}
- const metadata = JSON.parse(
- await readFile(metadataPath, "utf8"),
- ) as Partial<LocalSandboxMetadata>;
+ const metadata: unknown = JSON.parse(await readFile(metadataPath, "utf8"));
- if (metadata.version !== LOCAL_SANDBOX_METADATA_VERSION || !isStringRecord(metadata.env)) {
+ if (
+ !isRecord(metadata) ||
+ metadata.version !== LOCAL_SANDBOX_METADATA_VERSION ||
+ !isStringRecord(metadata.env)
+ ) {
return null;
}
@@ -279,6 +266,10 @@ async function writeLocalMetadata(
await writeFile(metadataPath, `${JSON.stringify(metadata, null, 2)}\n`);
}
+function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
+ return value !== null && typeof value === "object" && !Array.isArray(value);
+}
+
function isStringRecord(value: unknown): value is Readonly<Record<string, string>> {
return (
value !== null &&
diff --git a/packages/eve/src/execution/sandbox/bindings/just-bash.integration.test.ts b/packages/eve/src/execution/sandbox/bindings/just-bash.integration.test.ts
index c3ae11fcc..0e0a7ec9d 100644
--- a/packages/eve/src/execution/sandbox/bindings/just-bash.integration.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/just-bash.integration.test.ts
@@ -1,28 +1,23 @@
import { describe, expect, it, vi } from "vitest";
-import { createJustBashSandboxBackend } from "#execution/sandbox/bindings/just-bash.js";
+import { createJustBashSandboxProvider } from "#execution/sandbox/bindings/just-bash.js";
+import { createSandboxProviderHarness } from "#internal/testing/sandbox-provider-harness.js";
import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";
-// Simulate an application that configured the just-bash backend without
-// the optional `just-bash` package being installed or installable.
vi.mock("just-bash", () => {
throw new Error("Cannot find module 'just-bash'");
});
const createScratchDirectory = useTemporaryDirectories();
-describe("just-bash backend without the optional dependency installed", () => {
+describe("just-bash provider without the optional dependency installed", () => {
it("fails with an actionable install hint outside eve dev", async () => {
const appRoot = await createScratchDirectory("eve-just-bash-missing-");
- const backend = createJustBashSandboxBackend();
-
- // Outside `eve dev` (no EVE_DEV flag) the loader must not attempt a
- // package-manager install — it fails actionably instead.
+ const provider = createSandboxProviderHarness(createJustBashSandboxProvider(), undefined);
await expect(
- backend.create({
- runtimeContext: { appRoot },
- sessionKey: "session-missing-dependency",
- templateKey: null,
+ provider.openSession({
+ appRoot,
+ sandboxName: "session-missing-dependency",
}),
).rejects.toThrow(/pnpm add -D just-bash/);
});
@@ -31,13 +26,14 @@ describe("just-bash backend without the optional dependency installed", () => {
vi.stubEnv("EVE_DEV", "1");
try {
const appRoot = await createScratchDirectory("eve-just-bash-no-autoinstall-");
- const backend = createJustBashSandboxBackend({ createOptions: { autoInstall: false } });
-
+ const provider = createSandboxProviderHarness(
+ createJustBashSandboxProvider({ autoInstall: false }),
+ undefined,
+ );
await expect(
- backend.create({
- runtimeContext: { appRoot },
- sessionKey: "session-no-autoinstall",
- templateKey: null,
+ provider.openSession({
+ appRoot,
+ sandboxName: "session-no-autoinstall",
}),
).rejects.toThrow(/pnpm add -D just-bash/);
} finally {
diff --git a/packages/eve/src/execution/sandbox/bindings/just-bash.scenario.test.ts b/packages/eve/src/execution/sandbox/bindings/just-bash.scenario.test.ts
index 1a6fd05e4..fba5b5a32 100644
--- a/packages/eve/src/execution/sandbox/bindings/just-bash.scenario.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/just-bash.scenario.test.ts
@@ -1,32 +1,29 @@
import { existsSync } from "node:fs";
-import { mkdir, readdir, readFile, stat, utimes, writeFile } from "node:fs/promises";
+import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { decodeBytesToUtf8, defineCommand, MountableFs, ReadWriteFs } from "just-bash";
import { describe, expect, it } from "vitest";
import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";
-import {
- createJustBashSandboxBackend,
- pruneJustBashSandboxTemplates,
-} from "#execution/sandbox/bindings/just-bash.js";
+import { createJustBashSandboxProvider } from "#execution/sandbox/bindings/just-bash.js";
+import { createSandboxProviderHarness } from "#internal/testing/sandbox-provider-harness.js";
+import type { JustBashSandboxCreateOptions } from "#public/sandbox/just-bash-sandbox.js";
import { executeGlobOnSandbox } from "#execution/sandbox/glob-tool.js";
import { executeGrepOnSandbox } from "#execution/sandbox/grep-tool.js";
-import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
-import { justbash } from "#public/sandbox/backends/just-bash.js";
const createScratchDirectory = useTemporaryDirectories();
-// The whole file exercises the opt-in just-bash backend; the workspace
+// The whole file exercises the opt-in just-bash provider; the workspace
// devDependency provides the `just-bash` install that applications opt
// into explicitly.
-function createJustBashBackend(): SandboxBackend {
- return createJustBashSandboxBackend();
+function createJustBashProvider(options: JustBashSandboxCreateOptions = {}) {
+ return createSandboxProviderHarness(createJustBashSandboxProvider(options), undefined);
}
async function createTemporaryCacheDirectory(label: string): Promise<string> {
- // The local backend derives its cache directory from
- // `runtimeContext.appRoot` via `resolveSandboxCacheDirectory`, so the
+ // The local provider derives its cache directory from
+ // `appRoot` via `resolveSandboxCacheDirectory`, so the
// helper returns a temporary appRoot rather than a cache directory
// directly.
return await createScratchDirectory(`eve-local-sandbox-${label}-`);
@@ -34,19 +31,16 @@ async function createTemporaryCacheDirectory(label: string): Promise<string> {
async function createPrewarmedLocalHandle(input: {
readonly appRoot: string;
- readonly sessionKey: string;
- readonly templateKey: string;
+ readonly sandboxName: string;
}) {
- const backend = createJustBashBackend();
- await backend.prewarm({
- runtimeContext: { appRoot: input.appRoot },
+ const provider = createJustBashProvider();
+ await provider.prepare({
+ appRoot: input.appRoot,
seedFiles: [],
- templateKey: input.templateKey,
});
- return await backend.create({
- runtimeContext: { appRoot: input.appRoot },
- sessionKey: input.sessionKey,
- templateKey: input.templateKey,
+ return await provider.openSession({
+ appRoot: input.appRoot,
+ sandboxName: input.sandboxName,
});
}
@@ -74,10 +68,10 @@ describe("just-bash sandbox file API", () => {
await mkdir(sourceRoot, { recursive: true });
await writeFile(join(sourceRoot, "instructions.md"), "before");
let factoryCalls = 0;
- const backend = justbash({
+ const provider = createJustBashProvider({
async filesystem(context) {
factoryCalls += 1;
- expect(context.appRoot).toBe(appRoot);
+ expect(context.resolveProjectPath(".")).toBe(appRoot);
await context.defaultFilesystem.mkdir("/source", { recursive: true });
return new MountableFs({
base: context.defaultFilesystem,
@@ -95,75 +89,71 @@ describe("just-bash sandbox file API", () => {
},
});
- const handle = await backend.create({
- runtimeContext: { appRoot },
- sessionKey: "session-custom-filesystem",
- templateKey: null,
+ const handle = await provider.openSession({
+ appRoot,
+ sandboxName: "session-custom-filesystem",
});
expect(factoryCalls).toBe(1);
- expect(await handle.session.readTextFile({ path: "/source/instructions.md" })).toBe("before");
+ expect(await handle.sandbox.readTextFile({ path: "/source/instructions.md" })).toBe("before");
await expect(
- executeGlobOnSandbox(handle.session, { path: "/source", pattern: "*" }),
+ executeGlobOnSandbox(handle.sandbox, { path: "/source", pattern: "*" }),
).resolves.toMatchObject({
content: "/source/instructions.md",
count: 1,
path: "/source",
});
await expect(
- executeGrepOnSandbox(handle.session, { path: "/source", pattern: "before" }),
+ executeGrepOnSandbox(handle.sandbox, { path: "/source", pattern: "before" }),
).resolves.toMatchObject({
content: "/source/instructions.md:1:before",
matchCount: 1,
path: "/source",
});
- await handle.session.writeTextFile({
+ await handle.sandbox.writeTextFile({
content: "after",
path: "/source/instructions.md",
});
- await handle.session.writeTextFile({ content: "scratch", path: "scratch.txt" });
+ await handle.sandbox.writeTextFile({ content: "scratch", path: "scratch.txt" });
expect(await readFile(join(sourceRoot, "instructions.md"), "utf8")).toBe("after");
expect(existsSync(join(sourceRoot, "scratch.txt"))).toBe(false);
- await handle.shutdown();
+ await handle.onRuntimeShutdown();
});
it("applies the filesystem factory only to live sessions", async () => {
const appRoot = await createTemporaryCacheDirectory("filesystem-factory-lifecycle");
let factoryCalls = 0;
- const backend = justbash({
+ const provider = createJustBashProvider({
async filesystem({ defaultFilesystem }) {
factoryCalls += 1;
return defaultFilesystem;
},
});
- await backend.prewarm({
- runtimeContext: { appRoot },
+ await provider.prepare({
+ appRoot,
seedFiles: [{ content: "from template", path: "/workspace/seed.txt" }],
- templateKey: "tpl-filesystem-factory",
});
expect(factoryCalls).toBe(0);
- const handle = await backend.create({
- runtimeContext: { appRoot },
- sessionKey: "session-filesystem-factory",
- templateKey: "tpl-filesystem-factory",
+ const handle = await provider.openSession({
+ appRoot,
+ sandboxName: "session-filesystem-factory",
});
expect(factoryCalls).toBe(1);
- await expect(handle.session.readTextFile({ path: "seed.txt" })).resolves.toBe("from template");
- await handle.shutdown();
+ await expect(handle.sandbox.readTextFile({ path: "seed.txt" })).resolves.toBe("from template");
+ await handle.onRuntimeShutdown();
});
it("writes a file via the public session and reads it back", async () => {
const cacheDirectory = await createTemporaryCacheDirectory("file-api");
const handle = await createPrewarmedLocalHandle({
appRoot: cacheDirectory,
- sessionKey: "session-write-read",
- templateKey: "tpl-write-read",
+ sandboxName: "session-write-read",
});
- await handle.session.writeTextFile({ content: "hello world", path: "note.txt" });
- const content = await handle.session.readTextFile({ path: "note.txt" });
+ await handle.sandbox.writeTextFile({ content: "hello world", path: "note.txt" });
+ const content = await handle.sandbox.readTextFile({ path: "note.txt" });
expect(content).toBe("hello world");
});
@@ -172,11 +162,10 @@ describe("just-bash sandbox file API", () => {
const cacheDirectory = await createTemporaryCacheDirectory("run-env");
const handle = await createPrewarmedLocalHandle({
appRoot: cacheDirectory,
- sessionKey: "session-run-env",
- templateKey: "tpl-run-env",
+ sandboxName: "session-run-env",
});
- const result = await handle.session.run({
+ const result = await handle.sandbox.run({
command: 'echo "$DEPLOY_ENV"',
env: { DEPLOY_ENV: "staging" },
});
@@ -189,11 +178,10 @@ describe("just-bash sandbox file API", () => {
const cacheDirectory = await createTemporaryCacheDirectory("spawn-env");
const handle = await createPrewarmedLocalHandle({
appRoot: cacheDirectory,
- sessionKey: "session-spawn-env",
- templateKey: "tpl-spawn-env",
+ sandboxName: "session-spawn-env",
});
- const process = await handle.session.spawn({
+ const process = await handle.sandbox.spawn({
command: 'echo "$DEPLOY_ENV"',
env: { DEPLOY_ENV: "production" },
});
@@ -204,28 +192,14 @@ describe("just-bash sandbox file API", () => {
expect(stdout.trim()).toBe("production");
});
- it("rejects setNetworkPolicy — the just-bash engine cannot broker", async () => {
- const cacheDirectory = await createTemporaryCacheDirectory("network-policy");
- const handle = await createPrewarmedLocalHandle({
- appRoot: cacheDirectory,
- sessionKey: "session-network-policy",
- templateKey: "tpl-network-policy",
- });
-
- await expect(handle.session.setNetworkPolicy("deny-all")).rejects.toThrow(
- "not supported on the just-bash sandbox backend",
- );
- });
-
it("readFile returns null for a missing file", async () => {
const cacheDirectory = await createTemporaryCacheDirectory("file-api");
const handle = await createPrewarmedLocalHandle({
appRoot: cacheDirectory,
- sessionKey: "session-missing",
- templateKey: "tpl-missing",
+ sandboxName: "session-missing",
});
- const content = await handle.session.readTextFile({ path: "does-not-exist.txt" });
+ const content = await handle.sandbox.readTextFile({ path: "does-not-exist.txt" });
expect(content).toBeNull();
});
@@ -234,15 +208,14 @@ describe("just-bash sandbox file API", () => {
const cacheDirectory = await createTemporaryCacheDirectory("file-api");
const handle = await createPrewarmedLocalHandle({
appRoot: cacheDirectory,
- sessionKey: "session-mkdir",
- templateKey: "tpl-mkdir",
+ sandboxName: "session-mkdir",
});
- await handle.session.writeTextFile({
+ await handle.sandbox.writeTextFile({
content: "nested content",
path: "deep/nested/dir/file.txt",
});
- const content = await handle.session.readTextFile({ path: "deep/nested/dir/file.txt" });
+ const content = await handle.sandbox.readTextFile({ path: "deep/nested/dir/file.txt" });
expect(content).toBe("nested content");
});
@@ -251,13 +224,12 @@ describe("just-bash sandbox file API", () => {
const cacheDirectory = await createTemporaryCacheDirectory("file-api");
const handle = await createPrewarmedLocalHandle({
appRoot: cacheDirectory,
- sessionKey: "session-overwrite",
- templateKey: "tpl-overwrite",
+ sandboxName: "session-overwrite",
});
- await handle.session.writeTextFile({ content: "original", path: "file.txt" });
- await handle.session.writeTextFile({ content: "replaced", path: "file.txt" });
- const content = await handle.session.readTextFile({ path: "file.txt" });
+ await handle.sandbox.writeTextFile({ content: "original", path: "file.txt" });
+ await handle.sandbox.writeTextFile({ content: "replaced", path: "file.txt" });
+ const content = await handle.sandbox.readTextFile({ path: "file.txt" });
expect(content).toBe("replaced");
});
@@ -266,85 +238,58 @@ describe("just-bash sandbox file API", () => {
const cacheDirectory = await createTemporaryCacheDirectory("file-api");
const handle = await createPrewarmedLocalHandle({
appRoot: cacheDirectory,
- sessionKey: "session-remove",
- templateKey: "tpl-remove",
+ sandboxName: "session-remove",
});
- await handle.session.writeTextFile({
+ await handle.sandbox.writeTextFile({
content: "dynamic skill",
path: "skills/tenant/SKILL.md",
});
- await handle.session.writeTextFile({
+ await handle.sandbox.writeTextFile({
content: "policy",
path: "skills/tenant/references/policy.md",
});
- await handle.session.removePath({ force: true, path: "skills/tenant", recursive: true });
+ await handle.sandbox.removePath({ force: true, path: "skills/tenant", recursive: true });
await expect(
- handle.session.readTextFile({ path: "skills/tenant/SKILL.md" }),
+ handle.sandbox.readTextFile({ path: "skills/tenant/SKILL.md" }),
).resolves.toBeNull();
await expect(
- handle.session.readTextFile({ path: "skills/tenant/references/policy.md" }),
+ handle.sandbox.readTextFile({ path: "skills/tenant/references/policy.md" }),
).resolves.toBeNull();
});
it("preserves files across capture and reconnect", async () => {
const appRoot = await createTemporaryCacheDirectory("file-api");
- const backend = createJustBashBackend();
+ const provider = createJustBashProvider();
- await backend.prewarm({
- runtimeContext: { appRoot },
+ await provider.prepare({
+ appRoot,
seedFiles: [],
- templateKey: "tpl-reconnect",
});
- const firstHandle = await backend.create({
- runtimeContext: { appRoot },
- sessionKey: "session-reconnect",
- templateKey: "tpl-reconnect",
+ const { handle: firstHandle, state } = await provider.start({
+ appRoot,
+ sandboxName: "session-reconnect",
});
- await firstHandle.session.writeTextFile({
+ await firstHandle.sandbox.writeTextFile({
content: "survives reconnect",
path: "persisted.txt",
});
- await firstHandle.stop();
- const state = await firstHandle.captureState();
+ await firstHandle.onSessionStop();
- expect(state.metadata).toEqual({
- rootPath: join(
- appRoot,
- ".eve",
- "sandbox-cache",
- "just-bash",
- "sessions",
- "session-reconnect",
- ),
- });
+ expect(state).toMatchObject({ version: 2 });
await expect(
- readFile(
- join(
- appRoot,
- ".eve",
- "sandbox-cache",
- "just-bash",
- "sessions",
- "session-reconnect",
- "fs",
- "workspace",
- "persisted.txt",
- ),
- "utf8",
- ),
+ readFile(join(state.rootPath, "fs", "workspace", "persisted.txt"), "utf8"),
).resolves.toBe("survives reconnect");
- const reconnectedHandle = await backend.create({
- existingMetadata: state.metadata,
- runtimeContext: { appRoot },
- sessionKey: "session-reconnect",
- templateKey: "tpl-reconnect",
+ const reconnectedHandle = await provider.openSession({
+ existing: state,
+ appRoot,
+ sandboxName: "session-reconnect",
});
- const content = await reconnectedHandle.session.readTextFile({ path: "persisted.txt" });
+ const content = await reconnectedHandle.sandbox.readTextFile({ path: "persisted.txt" });
expect(content).toBe("survives reconnect");
});
@@ -353,15 +298,14 @@ describe("just-bash sandbox file API", () => {
const cacheDirectory = await createTemporaryCacheDirectory("file-api");
const handle = await createPrewarmedLocalHandle({
appRoot: cacheDirectory,
- sessionKey: "session-line-range",
- templateKey: "tpl-line-range",
+ sandboxName: "session-line-range",
});
- await handle.session.writeTextFile({
+ await handle.sandbox.writeTextFile({
content: "alpha\nbeta\ngamma\ndelta\n",
path: "lines.txt",
});
- const range = await handle.session.readTextFile({
+ const range = await handle.sandbox.readTextFile({
path: "lines.txt",
startLine: 2,
endLine: 3,
@@ -374,12 +318,11 @@ describe("just-bash sandbox file API", () => {
const cacheDirectory = await createTemporaryCacheDirectory("file-api");
const handle = await createPrewarmedLocalHandle({
appRoot: cacheDirectory,
- sessionKey: "session-relative",
- templateKey: "tpl-relative",
+ sandboxName: "session-relative",
});
- await handle.session.writeTextFile({ content: "relative write", path: "rel.txt" });
- const content = await handle.session.readTextFile({ path: "/workspace/rel.txt" });
+ await handle.sandbox.writeTextFile({ content: "relative write", path: "rel.txt" });
+ const content = await handle.sandbox.readTextFile({ path: "/workspace/rel.txt" });
expect(content).toBe("relative write");
});
@@ -388,17 +331,16 @@ describe("just-bash sandbox file API", () => {
const cacheDirectory = await createTemporaryCacheDirectory("file-api");
const handle = await createPrewarmedLocalHandle({
appRoot: cacheDirectory,
- sessionKey: "session-buffer",
- templateKey: "tpl-buffer",
+ sandboxName: "session-buffer",
});
// A PNG header plus a handful of non-UTF-8 bytes. Reading this
// back as UTF-8 text would throw, so the roundtrip check uses the
// `wc -c` command to confirm the on-disk byte length matches.
const bytes = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0xff, 0x00]);
- await handle.session.writeBinaryFile({ content: bytes, path: "assets/fixture.bin" });
+ await handle.sandbox.writeBinaryFile({ content: bytes, path: "assets/fixture.bin" });
- const result = await handle.session.run({ command: "wc -c < assets/fixture.bin" });
+ const result = await handle.sandbox.run({ command: "wc -c < assets/fixture.bin" });
expect(result.exitCode).toBe(0);
expect(Number(result.stdout.trim())).toBe(bytes.length);
});
@@ -407,7 +349,7 @@ describe("just-bash sandbox file API", () => {
describe("just-bash custom commands", () => {
it("forwards custom commands to live sessions", async () => {
const appRoot = await createTemporaryCacheDirectory("custom-command");
- const backend = justbash({
+ const provider = createJustBashProvider({
customCommands: [
defineCommand("cap", async (args, context) => {
if (args[0] === "fail") {
@@ -421,258 +363,102 @@ describe("just-bash custom commands", () => {
}),
],
});
- const handle = await backend.create({
- runtimeContext: { appRoot },
- sessionKey: "session-custom-command",
- templateKey: null,
+ const handle = await provider.openSession({
+ appRoot,
+ sandboxName: "session-custom-command",
});
await expect(
- handle.session.run({ command: "printf 'hello' | cap > result.txt" }),
+ handle.sandbox.run({ command: "printf 'hello' | cap > result.txt" }),
).resolves.toMatchObject({
exitCode: 0,
stdout: "",
});
- await expect(handle.session.readTextFile({ path: "result.txt" })).resolves.toBe("HELLO");
- await expect(handle.session.run({ command: "cap fail" })).resolves.toMatchObject({
+ await expect(handle.sandbox.readTextFile({ path: "result.txt" })).resolves.toBe("HELLO");
+ await expect(handle.sandbox.run({ command: "cap fail" })).resolves.toMatchObject({
exitCode: 23,
stderr: "cap failed\n",
});
- await handle.shutdown();
+ await handle.onRuntimeShutdown();
});
});
-describe("createLocalSandboxBackend with the just-bash engine", () => {
- it("exposes a distinct stable backend name", () => {
- const backend = createJustBashBackend();
- expect(backend.name).toBe("just-bash");
+describe("just-bash provider", () => {
+ it("exposes a distinct stable provider name", () => {
+ const provider = createJustBashProvider();
+ expect(provider).toBeDefined();
});
it("creates a fresh session when no template key is requested", async () => {
const appRoot = await createTemporaryCacheDirectory("fresh-session");
- const backend = createJustBashBackend();
+ const provider = createJustBashProvider();
- const handle = await backend.create({
- runtimeContext: { appRoot },
- sessionKey: "session-without-template",
- templateKey: null,
+ const handle = await provider.openSession({
+ appRoot,
+ sandboxName: "session-without-template",
});
- const result = await handle.session.run({
+ const result = await handle.sandbox.run({
command: "find /workspace -maxdepth 2 -type f | sort",
});
expect(result.stdout.trim()).toBe("");
});
- it("reports a fresh build on first prewarm and a reuse on the second", async () => {
- const appRoot = await createTemporaryCacheDirectory("reuse-report");
- const backend = createJustBashBackend();
-
- const first = await backend.prewarm({
- runtimeContext: { appRoot },
- seedFiles: [{ content: "# Weather skill\n", path: "/workspace/skills/weather.md" }],
- templateKey: "tpl-reuse-report",
- });
- const second = await backend.prewarm({
- runtimeContext: { appRoot },
- seedFiles: [{ content: "# Weather skill\n", path: "/workspace/skills/weather.md" }],
- templateKey: "tpl-reuse-report",
- });
-
- expect(first).toEqual({ reused: false });
- expect(second).toEqual({ reused: true });
- await expect(
- readFile(
- join(
- appRoot,
- ".eve",
- "sandbox-cache",
- "just-bash",
- "templates",
- "tpl-reuse-report",
- "fs",
- "workspace",
- "skills",
- "weather.md",
- ),
- "utf8",
- ),
- ).resolves.toBe("# Weather skill\n");
- });
-
- it("prunes stale cached templates while preserving retained and recent templates", async () => {
- const appRoot = await createTemporaryCacheDirectory("template-prune");
- const templatesRoot = join(appRoot, ".eve", "sandbox-cache", "just-bash", "templates");
- const recentTemplateRoot = join(templatesRoot, "recent");
- const retainedTemplateRoot = join(templatesRoot, "retained");
- const staleTemplateRoot = join(templatesRoot, "stale");
- const staleTemporaryRoot = join(templatesRoot, "stale-publish.tmp");
- const recentTemporaryRoot = join(templatesRoot, "recent-publish.tmp");
- const now = 1_000_000;
-
- for (const templateRoot of [
- recentTemplateRoot,
- retainedTemplateRoot,
- staleTemplateRoot,
- staleTemporaryRoot,
- recentTemporaryRoot,
- ]) {
- await mkdir(templateRoot, { recursive: true });
- await writeFile(join(templateRoot, "marker.txt"), templateRoot);
- }
- await utimes(recentTemplateRoot, new Date(now - 1_000), new Date(now - 1_000));
- await utimes(retainedTemplateRoot, new Date(now - 20_000), new Date(now - 20_000));
- await utimes(staleTemplateRoot, new Date(now - 30_000), new Date(now - 30_000));
- await utimes(staleTemporaryRoot, new Date(now - 30_000), new Date(now - 30_000));
- await utimes(recentTemporaryRoot, new Date(now - 1_000), new Date(now - 1_000));
-
- await pruneJustBashSandboxTemplates({
- appRoot,
- now,
- recentWindowMs: 5_000,
- retainCount: 2,
- });
-
- await expect(readdir(templatesRoot)).resolves.toEqual(
- expect.arrayContaining(["recent", "retained", "recent-publish.tmp"]),
- );
- expect(existsSync(staleTemplateRoot)).toBe(false);
- expect(existsSync(staleTemporaryRoot)).toBe(false);
- });
-
- it("touches a reused template so cleanup keeps the active template", async () => {
- const appRoot = await createTemporaryCacheDirectory("template-touch");
- const backend = createJustBashBackend();
- const templateRoot = join(appRoot, ".eve", "sandbox-cache", "just-bash", "templates", "active");
- const oldTime = new Date(1_000);
- const now = Date.now();
-
- await backend.prewarm({
- runtimeContext: { appRoot },
- seedFiles: [],
- templateKey: "active",
- });
- await utimes(templateRoot, oldTime, oldTime);
-
- await expect(
- backend.prewarm({
- runtimeContext: { appRoot },
- seedFiles: [],
- templateKey: "active",
- }),
- ).resolves.toEqual({ reused: true });
-
- expect((await stat(templateRoot)).mtimeMs).toBeGreaterThan(oldTime.getTime());
-
- await pruneJustBashSandboxTemplates({
- appRoot,
- now,
- recentWindowMs: now - oldTime.getTime() - 1,
- retainCount: 0,
- });
-
- expect(existsSync(templateRoot)).toBe(true);
- });
-
it("creates a session from a prewarmed template with seed files", async () => {
const appRoot = await createTemporaryCacheDirectory("seed-template");
- const backend = createJustBashBackend();
+ const provider = createJustBashProvider();
- await backend.prewarm({
- runtimeContext: { appRoot },
+ await provider.prepare({
+ appRoot,
seedFiles: [
{
content: "# Weather skill\n",
path: "/workspace/skills/weather.md",
},
],
- templateKey: "template-seeded-later",
});
- const seededHandle = await backend.create({
- runtimeContext: { appRoot },
- sessionKey: "session-from-repaired-template",
- templateKey: "template-seeded-later",
+ const seededHandle = await provider.openSession({
+ appRoot,
+ sandboxName: "session-from-repaired-template",
});
- const result = await seededHandle.session.run({
+ const result = await seededHandle.sandbox.run({
command: "find /workspace -maxdepth 3 -type f | sort",
});
expect(result.stdout.trim().split("\n")).toEqual(["/workspace/skills/weather.md"]);
});
- it("writes seed files before bootstrap and captures bootstrap outputs", async () => {
- const appRoot = await createTemporaryCacheDirectory("seed-before-bootstrap");
- const backend = createJustBashBackend();
-
- await backend.prewarm({
- bootstrap: async ({ use }) => {
- const sandbox = await use();
- await expect(sandbox.readTextFile({ path: "/workspace/seed.txt" })).resolves.toBe(
- "authored seed",
- );
- await sandbox.writeTextFile({
- content: "bootstrap output",
- path: "/workspace/bootstrap.txt",
- });
- },
- runtimeContext: { appRoot },
- seedFiles: [{ content: "authored seed", path: "/workspace/seed.txt" }],
- templateKey: "template-seed-before-bootstrap",
- });
-
- const handle = await backend.create({
- runtimeContext: { appRoot },
- sessionKey: "session-seed-before-bootstrap",
- templateKey: "template-seed-before-bootstrap",
- });
- await expect(handle.session.readTextFile({ path: "/workspace/seed.txt" })).resolves.toBe(
- "authored seed",
- );
- await expect(handle.session.readTextFile({ path: "/workspace/bootstrap.txt" })).resolves.toBe(
- "bootstrap output",
- );
- });
-
- it("does not repair an existing session directory with later seed files", async () => {
+ it("rejects existing session state from a different prepared artifact", async () => {
const appRoot = await createTemporaryCacheDirectory("seed-session");
- const backend = createJustBashBackend();
+ const provider = createJustBashProvider();
- await backend.prewarm({
- runtimeContext: { appRoot },
+ await provider.prepare({
+ appRoot,
seedFiles: [],
- templateKey: "template-seeded-later-session",
});
- const initialHandle = await backend.create({
- runtimeContext: { appRoot },
- sessionKey: "session-seeded-later",
- templateKey: "template-seeded-later-session",
+ const { handle: initialHandle, state: initialState } = await provider.start({
+ appRoot,
+ sandboxName: "session-seeded-later",
});
- const initialState = await initialHandle.captureState();
-
- await initialHandle.shutdown();
+ await initialHandle.onRuntimeShutdown();
- await backend.prewarm({
- runtimeContext: { appRoot },
+ await provider.prepare({
+ appRoot,
seedFiles: [
{
content: "# Weather skill\n",
path: "/workspace/skills/weather.md",
},
],
- templateKey: "template-seeded-later-session-next",
});
- const seededHandle = await backend.create({
- existingMetadata: initialState.metadata,
- runtimeContext: { appRoot },
- sessionKey: "session-seeded-later",
- templateKey: "template-seeded-later-session-next",
- });
- const result = await seededHandle.session.run({
- command: "find /workspace -maxdepth 3 -type f | sort",
- });
-
- expect(result.stdout.trim()).toBe("");
+ await expect(
+ provider.openSession({
+ existing: initialState,
+ appRoot,
+ sandboxName: "session-seeded-later",
+ }),
+ ).rejects.toThrow("session state is incompatible");
});
});
diff --git a/packages/eve/src/execution/sandbox/bindings/just-bash.ts b/packages/eve/src/execution/sandbox/bindings/just-bash.ts
index a3aa9df3b..a647a49cb 100644
--- a/packages/eve/src/execution/sandbox/bindings/just-bash.ts
+++ b/packages/eve/src/execution/sandbox/bindings/just-bash.ts
@@ -7,16 +7,15 @@ import {
copyDirectoryAtomically,
createFileBackedInternalSandboxSession,
pathExists,
- resolveLocalBackendSessionRootPath,
- resolveLocalBackendTemplateRootPath,
- resolveLocalBackendTemplatesDirectory,
+ resolveLocalProviderSessionRootPath,
+ resolveLocalProviderTemplateRootPath,
+ resolveLocalProviderTemplatesDirectory,
touchDirectory,
writeSandboxSeedFiles,
-} from "#execution/sandbox/bindings/local-backend-utils.js";
+} from "#execution/sandbox/bindings/local-provider-utils.js";
import {
createBashSandbox,
createJustBashHandle,
- justBashSetNetworkPolicyUnsupported,
} from "#execution/sandbox/bindings/just-bash-runtime.js";
import {
LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,
@@ -25,179 +24,193 @@ import {
} from "#execution/sandbox/bindings/local-template-prune.js";
import { createLoggingSandboxSession } from "#execution/sandbox/logging-session.js";
import { buildSandboxSession } from "#execution/sandbox/session.js";
-import { resolveSandboxCacheDirectory } from "#internal/application/paths.js";
-import type {
- SandboxBackend,
- SandboxBackendCreateInput,
- SandboxBackendHandle,
- SandboxBackendPrewarmInput,
- SandboxBackendPrewarmResult,
-} from "#public/definitions/sandbox-backend.js";
-import { SandboxTemplateNotProvisionedError } from "#public/definitions/sandbox-backend.js";
+import { createSandboxProviderIdentity } from "#execution/sandbox/provider-identity.js";
import type { JustBashSandboxCreateOptions } from "#public/sandbox/just-bash-sandbox.js";
+import { resolveSandboxCacheDirectory } from "#internal/application/paths.js";
+import type { FixedNetworkSandboxSession } from "#shared/sandbox-session.js";
+import {
+ isSandboxPreparedArtifactRecord,
+ providerResourceTargetFiles,
+ sandboxProviderResourceIdentity,
+ type SandboxPreparedArtifact,
+ type SandboxProviderImplementation,
+ type SandboxProviderSessionContext,
+} from "#shared/sandbox-provider.js";
+import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";
const JUST_BASH_CACHE_DIRECTORY_NAME = "just-bash";
+export const JUST_BASH_PROVIDER_NAME = "just-bash";
-/**
- * Stable backend name. Participates in template/session key derivation
- * and persisted reconnect state.
- */
-export const JUST_BASH_BACKEND_NAME = "just-bash";
+type JustBashPreparedArtifact = { readonly templateRootPath: string };
+type JustBashSessionState = {
+ readonly generation: string;
+ readonly rootPath: string;
+ readonly version: 2;
+};
-/**
- * Construction input for {@link createJustBashSandboxBackend}. Internal —
- * the public surface is the `justbash()` factory under
- * `eve/sandbox`.
- */
-export interface CreateJustBashSandboxBackendInput {
- readonly createOptions?: JustBashSandboxCreateOptions;
-}
+export function createJustBashSandboxProvider(
+ authoredOptions: JustBashSandboxCreateOptions | undefined = undefined,
+): SandboxProviderImplementation<
+ undefined,
+ JustBashPreparedArtifact,
+ JustBashSessionState,
+ FixedNetworkSandboxSession
+> {
+ const options = authoredOptions ?? {};
+ const autoInstall = options.autoInstall ?? true;
+ const environmentIdentity = {
+ autoInstall,
+ customCommands: options.customCommands,
+ filesystem: options.filesystem,
+ version: 2,
+ };
-/**
- * Creates the just-bash sandbox backend.
- *
- * The cache directory is derived from the runtime context's `appRoot`
- * on every `create` call so the backend stays stateless and matches
- * the framework's per-call dispatch contract.
- */
-export function createJustBashSandboxBackend(
- input: CreateJustBashSandboxBackendInput = {},
-): SandboxBackend {
- const autoInstall = input.createOptions?.autoInstall ?? true;
- const customCommands = input.createOptions?.customCommands;
- const filesystem = input.createOptions?.filesystem;
return {
- name: JUST_BASH_BACKEND_NAME,
- async prewarm(prewarmInput: SandboxBackendPrewarmInput): Promise<SandboxBackendPrewarmResult> {
- const cacheDirectory = resolveSandboxCacheDirectory(prewarmInput.runtimeContext.appRoot);
- const templateRootPath = resolveTemplateRootPath(cacheDirectory, prewarmInput.templateKey);
-
+ async prepare(context) {
+ const templateIdentity = createSandboxProviderIdentity({
+ ...environmentIdentity,
+ resources: sandboxProviderResourceIdentity(context.resources),
+ sourceRevision: context.sourceRevision,
+ }).slice(0, 24);
+ const templateRootPath = resolveTemplateRootPath(context.storagePath, templateIdentity);
if (await pathExists(templateRootPath)) {
await touchDirectory(templateRootPath);
- return { reused: true };
+ context.log?.("reusing cached template filesystem");
+ return { templateRootPath };
}
const temporaryTemplateRootPath = `${templateRootPath}.${randomUUID()}.tmp`;
let published = false;
const templateSandbox = await createBashSandbox({
- appRoot: prewarmInput.runtimeContext.appRoot,
autoInstall,
+ host: context.host,
rootPath: temporaryTemplateRootPath,
- sessionKey: prewarmInput.templateKey,
+ sessionKey: `prepare-${templateIdentity}`,
+ storagePath: context.storagePath,
});
const templateSession = buildSandboxSession(
- createFileBackedInternalSandboxSession({
- id: templateSandbox.sessionKey,
- sandbox: templateSandbox,
- }),
- justBashSetNetworkPolicyUnsupported,
+ createFileBackedInternalSandboxSession({ sandbox: templateSandbox }),
);
try {
- await writeSandboxSeedFiles(templateSession, prewarmInput.seedFiles);
-
- if (prewarmInput.bootstrap !== undefined) {
- prewarmInput.log?.("running sandbox bootstrap");
- await prewarmInput.bootstrap({
- use: async () =>
- createLoggingSandboxSession({
- log: prewarmInput.log,
- session: templateSession,
- }),
- });
- }
-
- const captured = await templateSandbox.captureState();
- if (captured === null) {
- throw new Error(
- `Failed to capture local sandbox template state for "${prewarmInput.templateKey}".`,
+ await writeSandboxSeedFiles(
+ templateSession,
+ providerResourceTargetFiles(context.resources),
+ );
+ if (options.prepare !== undefined) {
+ context.log?.("running sandbox preparation");
+ await options.prepare(
+ createLoggingSandboxSession({ log: context.log, session: templateSession }),
);
}
-
+ await templateSandbox.captureState();
await mkdir(dirname(templateRootPath), { recursive: true });
try {
await rename(temporaryTemplateRootPath, templateRootPath);
published = true;
} catch (error) {
- if (await pathExists(templateRootPath)) {
- return { reused: true };
- }
+ if (await pathExists(templateRootPath)) return { templateRootPath };
throw error;
}
} finally {
await templateSandbox.dispose();
- if (!published) {
- await rm(temporaryTemplateRootPath, { force: true, recursive: true }).catch(() => {});
- }
+ if (!published) await rm(temporaryTemplateRootPath, { force: true, recursive: true });
}
-
- return { reused: false };
+ return { templateRootPath };
},
- async create(createInput: SandboxBackendCreateInput): Promise<SandboxBackendHandle> {
- const cacheDirectory = resolveSandboxCacheDirectory(createInput.runtimeContext.appRoot);
- const sessionRootPath =
- getLocalRootPath(createInput.existingMetadata) ??
- resolveSessionRootPath(cacheDirectory, createInput.sessionKey);
-
- if (!(await pathExists(sessionRootPath))) {
- if (createInput.templateKey === null) {
- await mkdir(sessionRootPath, { recursive: true });
- } else {
- const templateRootPath = resolveTemplateRootPath(cacheDirectory, createInput.templateKey);
-
- if (!(await pathExists(templateRootPath))) {
- throw new SandboxTemplateNotProvisionedError({
- backendName: JUST_BASH_BACKEND_NAME,
- templateKey: createInput.templateKey,
- });
- }
-
- await copyDirectoryAtomically(templateRootPath, sessionRootPath);
- }
+ async resume(context, artifactValue, stateValue) {
+ const artifact = requirePreparedJustBashArtifact(artifactValue);
+ const state = requireJustBashSessionState(stateValue);
+ const generation = createSandboxProviderIdentity({ artifact, version: 1 });
+ const expectedRootPath = sessionRootPath(context, artifact);
+ if (state.generation !== generation || state.rootPath !== expectedRootPath) {
+ throw new Error("just-bash session state is incompatible with this environment.");
}
-
- const sandbox = await createBashSandbox({
- appRoot: createInput.runtimeContext.appRoot,
- autoInstall,
- customCommands,
- filesystem,
- rootPath: sessionRootPath,
- sessionKey: createInput.sessionKey,
- });
-
- return createJustBashHandle(sandbox, JUST_BASH_BACKEND_NAME);
+ if (!(await pathExists(state.rootPath))) {
+ throw new Error(`just-bash session root "${state.rootPath}" no longer exists.`);
+ }
+ return await openHandle(context, state.rootPath, options);
+ },
+ async start(context, _openOptions, artifactValue) {
+ const artifact = requirePreparedJustBashArtifact(artifactValue);
+ const rootPath = sessionRootPath(context, artifact);
+ await ensureSessionRoot(artifact, rootPath);
+ return {
+ handle: await openHandle(context, rootPath, options),
+ state: {
+ generation: createSandboxProviderIdentity({ artifact, version: 1 }),
+ rootPath,
+ version: 2,
+ },
+ };
},
};
}
-/**
- * Removes stale just-bash sandbox template directories for one
- * application's cache.
- */
+function sessionRootPath(
+ context: SandboxProviderSessionContext,
+ artifact: JustBashPreparedArtifact,
+): string {
+ return resolveSessionRootPath(
+ context.storagePath,
+ createSandboxProviderIdentity({ artifact, sessionId: context.session.id, version: 1 }).slice(
+ 0,
+ 24,
+ ),
+ );
+}
+
+async function ensureSessionRoot(
+ artifact: JustBashPreparedArtifact,
+ sessionRootPath: string,
+): Promise<void> {
+ if (await pathExists(sessionRootPath)) return;
+ if (!(await pathExists(artifact.templateRootPath))) {
+ throw new SandboxTemplateNotProvisionedError({
+ providerName: JUST_BASH_PROVIDER_NAME,
+ templateKey: artifact.templateRootPath,
+ });
+ }
+ await copyDirectoryAtomically(artifact.templateRootPath, sessionRootPath);
+}
+
+async function openHandle(
+ context: SandboxProviderSessionContext,
+ rootPath: string,
+ options: JustBashSandboxCreateOptions,
+) {
+ const sandbox = await createBashSandbox({
+ autoInstall: options.autoInstall ?? true,
+ customCommands: options.customCommands,
+ filesystem: options.filesystem,
+ host: context.host,
+ rootPath,
+ sessionKey: context.session.id,
+ storagePath: context.storagePath,
+ });
+ return createJustBashHandle(sandbox);
+}
+
export async function pruneJustBashSandboxTemplates(input: {
readonly appRoot: string;
readonly now?: number;
readonly recentWindowMs?: number;
readonly retainCount?: number;
}): Promise<void> {
- const templatesDirectory = resolveLocalBackendTemplatesDirectory(
+ const templatesDirectory = resolveLocalProviderTemplatesDirectory(
resolveSandboxCacheDirectory(input.appRoot),
JUST_BASH_CACHE_DIRECTORY_NAME,
);
const now = input.now ?? Date.now();
const recentWindowMs = input.recentWindowMs ?? LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS;
const retainCount = input.retainCount ?? LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT;
-
let entries: Dirent<string>[];
try {
entries = await readdir(templatesDirectory, { withFileTypes: true });
} catch (error) {
- if (error instanceof Error && "code" in error && error.code === "ENOENT") {
- return;
- }
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return;
throw error;
}
-
const directories = await Promise.all(
entries
.filter((entry) => entry.isDirectory())
@@ -210,18 +223,14 @@ export async function pruneJustBashSandboxTemplates(input: {
};
}),
);
-
const staleTemplates = selectStaleTemplateEntries(
directories.filter((directory) => !directory.isTemporary),
{ now, recentWindowMs, retainCount },
);
- // Temporary build directories are garbage as soon as they fall out of
- // the recency window — they only exist while a publish is in flight.
const staleTemporaries = selectStaleTemplateEntries(
directories.filter((directory) => directory.isTemporary),
{ now, recentWindowMs, retainCount: 0 },
);
-
await Promise.all(
[...staleTemplates, ...staleTemporaries].map(
async (entry) => await rm(entry.path, { force: true, recursive: true }),
@@ -229,23 +238,31 @@ export async function pruneJustBashSandboxTemplates(input: {
);
}
-function resolveTemplateRootPath(cacheDirectory: string, templateKey: string): string {
- return resolveLocalBackendTemplateRootPath(
- cacheDirectory,
- JUST_BASH_CACHE_DIRECTORY_NAME,
- templateKey,
- );
+function requirePreparedJustBashArtifact(
+ artifact: SandboxPreparedArtifact,
+): JustBashPreparedArtifact {
+ if (!isSandboxPreparedArtifactRecord(artifact) || typeof artifact.templateRootPath !== "string") {
+ throw new Error("Invalid prepared just-bash artifact.");
+ }
+ return { templateRootPath: artifact.templateRootPath };
}
-function resolveSessionRootPath(cacheDirectory: string, sessionKey: string): string {
- return resolveLocalBackendSessionRootPath(
- cacheDirectory,
- JUST_BASH_CACHE_DIRECTORY_NAME,
- sessionKey,
- );
+function requireJustBashSessionState(state: SandboxPreparedArtifact): JustBashSessionState {
+ if (
+ !isSandboxPreparedArtifactRecord(state) ||
+ state.version !== 2 ||
+ typeof state.generation !== "string" ||
+ typeof state.rootPath !== "string"
+ ) {
+ throw new Error("Invalid just-bash session state.");
+ }
+ return { generation: state.generation, rootPath: state.rootPath, version: 2 };
+}
+
+function resolveTemplateRootPath(storagePath: string, key: string): string {
+ return resolveLocalProviderTemplateRootPath(storagePath, JUST_BASH_CACHE_DIRECTORY_NAME, key);
}
-function getLocalRootPath(metadata: Record<string, unknown> | undefined): string | undefined {
- const rootPath = metadata?.rootPath;
- return typeof rootPath === "string" ? rootPath : undefined;
+function resolveSessionRootPath(storagePath: string, key: string): string {
+ return resolveLocalProviderSessionRootPath(storagePath, JUST_BASH_CACHE_DIRECTORY_NAME, key);
}
diff --git a/packages/eve/src/execution/sandbox/bindings/local-backend-utils.ts b/packages/eve/src/execution/sandbox/bindings/local-provider-utils.ts
similarity index 84%
rename from packages/eve/src/execution/sandbox/bindings/local-backend-utils.ts
rename to packages/eve/src/execution/sandbox/bindings/local-provider-utils.ts
index 340ba0591..3fb3b99d4 100644
--- a/packages/eve/src/execution/sandbox/bindings/local-backend-utils.ts
+++ b/packages/eve/src/execution/sandbox/bindings/local-provider-utils.ts
@@ -5,7 +5,10 @@ import { dirname, join } from "node:path";
import { bufferToStream, streamToBuffer } from "#execution/sandbox/stream-utils.js";
import { WORKSPACE_ROOT } from "#runtime/workspace/types.js";
import { resolveSandboxModelPath } from "#shared/skill-paths.js";
-import type { SandboxSeedFile } from "#shared/sandbox-backend.js";
+export interface SandboxSeedFile {
+ readonly content: string | Uint8Array;
+ readonly path: string;
+}
import type {
InternalSandboxSession,
SandboxProcess,
@@ -24,11 +27,9 @@ export interface FileBackedSandbox {
}
export function createFileBackedInternalSandboxSession(input: {
- readonly id: string;
readonly sandbox: FileBackedSandbox;
}): InternalSandboxSession {
return {
- id: input.id,
resolvePath: resolveWorkspacePath,
async spawn(options: SandboxSpawnOptions) {
return await input.sandbox.spawn(options);
@@ -88,27 +89,30 @@ export async function touchDirectory(path: string): Promise<void> {
await utimes(path, now, now);
}
-export function resolveLocalBackendTemplateRootPath(
+export function resolveLocalProviderTemplateRootPath(
cacheDirectory: string,
- backendCacheName: string,
+ providerCacheName: string,
templateKey: string,
): string {
- return join(resolveLocalBackendTemplatesDirectory(cacheDirectory, backendCacheName), templateKey);
+ return join(
+ resolveLocalProviderTemplatesDirectory(cacheDirectory, providerCacheName),
+ templateKey,
+ );
}
-export function resolveLocalBackendTemplatesDirectory(
+export function resolveLocalProviderTemplatesDirectory(
cacheDirectory: string,
- backendCacheName: string,
+ providerCacheName: string,
): string {
- return join(cacheDirectory, backendCacheName, "templates");
+ return join(cacheDirectory, providerCacheName, "templates");
}
-export function resolveLocalBackendSessionRootPath(
+export function resolveLocalProviderSessionRootPath(
cacheDirectory: string,
- backendCacheName: string,
+ providerCacheName: string,
sessionKey: string,
): string {
- return join(cacheDirectory, backendCacheName, "sessions", sessionKey);
+ return join(cacheDirectory, providerCacheName, "sessions", sessionKey);
}
export async function writeSandboxSeedFiles(
diff --git a/packages/eve/src/execution/sandbox/bindings/local.test.ts b/packages/eve/src/execution/sandbox/bindings/local.test.ts
index 6127d0ac2..7ae232025 100644
--- a/packages/eve/src/execution/sandbox/bindings/local.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/local.test.ts
@@ -1,39 +1,25 @@
import { describe, expect, it } from "vitest";
import {
- createDockerSandboxBackend,
- createJustBashSandboxBackend,
- createMicrosandboxSandboxBackend,
- DOCKER_BACKEND_NAME,
- JUST_BASH_BACKEND_NAME,
- MICROSANDBOX_BACKEND_NAME,
+ createDockerSandboxProvider,
+ createJustBashSandboxProvider,
+ createMicrosandboxSandboxProvider,
+ DOCKER_PROVIDER_NAME,
+ JUST_BASH_PROVIDER_NAME,
+ MICROSANDBOX_PROVIDER_NAME,
} from "#execution/sandbox/bindings/local.js";
-describe("local sandbox backend factories", () => {
- it("expose distinct stable backend names", () => {
- // Backend names participate in template/session key derivation and
- // persisted reconnect state, so the engines must never collide.
- expect(createDockerSandboxBackend().name).toBe(DOCKER_BACKEND_NAME);
- expect(createJustBashSandboxBackend().name).toBe(JUST_BASH_BACKEND_NAME);
- expect(createMicrosandboxSandboxBackend().name).toBe(MICROSANDBOX_BACKEND_NAME);
+describe("local sandbox providers", () => {
+ it("use distinct stable provider names", () => {
expect(
- new Set([DOCKER_BACKEND_NAME, JUST_BASH_BACKEND_NAME, MICROSANDBOX_BACKEND_NAME, "vercel"])
+ new Set([DOCKER_PROVIDER_NAME, JUST_BASH_PROVIDER_NAME, MICROSANDBOX_PROVIDER_NAME, "vercel"])
.size,
).toBe(4);
});
- it("constructing a backend performs no environment probing or installs", () => {
- // Construction must stay side-effect free: probing and installs are
- // deferred to first use so `defineSandbox` evaluation (including at
- // compile time) stays cheap on any host.
- expect(createDockerSandboxBackend({ createOptions: { image: "alpine:3" } }).name).toBe(
- "docker",
- );
- expect(createMicrosandboxSandboxBackend({ createOptions: { cpus: 2 } }).name).toBe(
- "microsandbox",
- );
- expect(createJustBashSandboxBackend({ createOptions: { autoInstall: false } }).name).toBe(
- "just-bash",
- );
+ it("construct provider implementations without probing or installing", () => {
+ expect(createDockerSandboxProvider({ image: "alpine:3" })).toBeDefined();
+ expect(createMicrosandboxSandboxProvider({ cpus: 2 })).toBeDefined();
+ expect(createJustBashSandboxProvider({ autoInstall: false })).toBeDefined();
});
});
diff --git a/packages/eve/src/execution/sandbox/bindings/local.ts b/packages/eve/src/execution/sandbox/bindings/local.ts
index 5aa561e45..6a0b89916 100644
--- a/packages/eve/src/execution/sandbox/bindings/local.ts
+++ b/packages/eve/src/execution/sandbox/bindings/local.ts
@@ -1,11 +1,11 @@
/**
- * Facade over every local sandbox backend (Docker, just-bash,
+ * Facade over every local sandbox provider (Docker, just-bash,
* microsandbox) plus their availability probes and cache pruning.
*
* This module is the single import path for local-engine functionality
* from the public surface, so the hosted (Vercel) server bundle can
* prune all of it by stubbing one module — see
- * `createCompiledSandboxBackendPrunePlugin`. Anything exported here
+ * `createCompiledSandboxProviderPrunePlugin`. Anything exported here
* must also exist on that stub.
*/
import {
@@ -17,19 +17,19 @@ import { pruneJustBashSandboxTemplates } from "#execution/sandbox/bindings/just-
import { pruneMicrosandboxTemplates } from "#execution/sandbox/bindings/microsandbox.js";
export {
- createDockerSandboxBackend,
- DOCKER_BACKEND_NAME,
+ createDockerSandboxProvider,
+ DOCKER_PROVIDER_NAME,
pruneDockerSandboxTemplates,
} from "#execution/sandbox/bindings/docker.js";
export { isLinuxDockerDaemonAvailableSync } from "#execution/sandbox/bindings/docker-cli.js";
export {
- createJustBashSandboxBackend,
- JUST_BASH_BACKEND_NAME,
+ createJustBashSandboxProvider,
+ JUST_BASH_PROVIDER_NAME,
pruneJustBashSandboxTemplates,
} from "#execution/sandbox/bindings/just-bash.js";
export {
- createMicrosandboxSandboxBackend,
- MICROSANDBOX_BACKEND_NAME,
+ createMicrosandboxSandboxProvider,
+ MICROSANDBOX_PROVIDER_NAME,
pruneMicrosandboxTemplates,
} from "#execution/sandbox/bindings/microsandbox.js";
export { isMicrosandboxPlatformSupported } from "#execution/sandbox/bindings/microsandbox-platform.js";
@@ -69,7 +69,7 @@ export async function pruneLocalSandboxTemplates(input: {
*/
export function pruneLocalSandboxTemplatesInBackground(appRoot: string): void {
void pruneLocalSandboxTemplates({ appRoot }).catch((error) => {
- console.warn(`[eve:dev] failed to prune stale local sandbox templates: ${errorMessage(error)}`);
+ console.warn(`[eve:sandbox] failed to prune stale local templates: ${errorMessage(error)}`);
});
}
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-create.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-create.ts
index 9336ae1e0..ba2217cf1 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-create.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-create.ts
@@ -19,7 +19,9 @@ export async function createMicrosandboxWithProgress(input: {
readonly log?: (message: string) => void;
readonly source: string;
}): Promise<MicrosandboxSandbox> {
- const progress = { phase: "resolving the image" as MicrosandboxCreatePhase };
+ const progress: { phase: MicrosandboxCreatePhase } = {
+ phase: "resolving the image",
+ };
try {
const creation = await input.builder.createWithPullProgress();
@@ -163,13 +165,17 @@ function readMicrosandboxErrorCode(
error instanceof Error &&
"code" in error &&
typeof error.code === "string" &&
- Object.hasOwn(MICROSANDBOX_ERROR_HINTS, error.code)
+ isMicrosandboxErrorCodeWithHint(error.code)
) {
- return error.code as MicrosandboxErrorCode;
+ return error.code;
}
return undefined;
}
+function isMicrosandboxErrorCodeWithHint(value: string): value is MicrosandboxErrorCode {
+ return value === "database" || value === "imageNotFound" || value === "libkrunfwNotFound";
+}
+
function microsandboxErrorHint(code: MicrosandboxErrorCode | undefined): string | undefined {
return code === undefined ? undefined : MICROSANDBOX_ERROR_HINTS[code];
}
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.test.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.test.ts
deleted file mode 100644
index c7bd18e12..000000000
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.test.ts
+++ /dev/null
@@ -1,379 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-import {
- clearActiveMicrosandboxSessionHandlesForTest,
- createMicrosandboxHandle,
- prewarmMicrosandboxTemplate,
-} from "#execution/sandbox/bindings/microsandbox-lifecycle.js";
-import { SandboxTemplateNotProvisionedError } from "#public/definitions/sandbox-backend.js";
-import {
- MICROSANDBOX_DEFAULT_IMAGE,
- resolveMicrosandboxOptions,
-} from "#execution/sandbox/bindings/microsandbox-options.js";
-
-const runtimeMocks = vi.hoisted(() => ({
- connectMicrosandbox: vi.fn(),
- createPreparedMicrosandbox: vi.fn(),
- createProviderName: vi.fn((prefix: string, key: string) => `${prefix}-${key}`),
- doesPathExist: vi.fn(async () => false),
- loadMicrosandboxModule: vi.fn(async () => ({}) as never),
- removeSnapshotIfExists: vi.fn(async () => {}),
- sandboxExists: vi.fn(async () => false),
- snapshotExists: vi.fn(async () => true),
-}));
-
-const fsMocks = vi.hoisted(() => ({
- mkdir: vi.fn(async (_path: string, _options?: unknown) => {}),
- rename: vi.fn(async (_oldPath: string, _newPath: string) => {}),
- rm: vi.fn(async (_path: string, _options?: unknown) => {}),
-}));
-
-const metadataMocks = vi.hoisted(() => ({
- readSessionMetadata: vi.fn(async () => null),
- readSessionMetadataRecord: vi.fn((value: unknown) => value ?? null),
- readTemplateMetadata: vi.fn(async () => ({
- optionsHash: "options-hash",
- snapshotName: "template-snapshot",
- version: 2,
- })),
- resolveMicrosandboxMetadataPath: vi.fn((rootPath: string) => `${rootPath}/metadata.json`),
- writeTemplateMetadata: vi.fn(async () => {}),
-}));
-
-vi.mock("node:fs/promises", () => fsMocks);
-
-vi.mock("#execution/sandbox/bindings/microsandbox-runtime.js", async (importOriginal) => ({
- ...(await importOriginal<typeof import("#execution/sandbox/bindings/microsandbox-runtime.js")>()),
- ...runtimeMocks,
-}));
-
-vi.mock("#execution/sandbox/bindings/microsandbox-metadata.js", async (importOriginal) => ({
- ...(await importOriginal<
- typeof import("#execution/sandbox/bindings/microsandbox-metadata.js")
- >()),
- ...metadataMocks,
-}));
-
-describe("createMicrosandboxHandle", () => {
- beforeEach(() => {
- clearActiveMicrosandboxSessionHandlesForTest();
- vi.clearAllMocks();
- runtimeMocks.loadMicrosandboxModule.mockResolvedValue({} as never);
- runtimeMocks.connectMicrosandbox.mockReset();
- runtimeMocks.sandboxExists.mockResolvedValue(false);
- runtimeMocks.snapshotExists.mockResolvedValue(true);
- metadataMocks.readSessionMetadata.mockResolvedValue(null);
- metadataMocks.readSessionMetadataRecord.mockImplementation((value: unknown) => value ?? null);
- metadataMocks.readTemplateMetadata.mockResolvedValue({
- optionsHash: "options-hash",
- snapshotName: "template-snapshot",
- version: 2,
- });
- });
-
- it("reuses the active same-process session instead of reopening from the template", async () => {
- const vm = createFakeMicrosandboxVm("session-key");
- runtimeMocks.createPreparedMicrosandbox.mockResolvedValue(vm);
- const options = resolveMicrosandboxOptions({ image: MICROSANDBOX_DEFAULT_IMAGE });
- const createInput = {
- runtimeContext: { appRoot: "/tmp/eve-app" },
- sessionKey: "session-key",
- templateKey: "template-key",
- };
-
- const firstHandle = await createMicrosandboxHandle({
- backendName: "microsandbox",
- createInput,
- options,
- optionsHash: "options-hash",
- });
- await firstHandle.session.writeTextFile({
- content: "survives active cache",
- path: "date.txt",
- });
- const state = await firstHandle.captureState();
-
- const secondHandle = await createMicrosandboxHandle({
- backendName: "microsandbox",
- createInput: {
- ...createInput,
- existingMetadata: state.metadata,
- },
- options,
- optionsHash: "options-hash",
- });
-
- await expect(secondHandle.session.readTextFile({ path: "date.txt" })).resolves.toBe(
- "survives active cache",
- );
- expect(secondHandle).toBe(firstHandle);
- expect(runtimeMocks.createPreparedMicrosandbox).toHaveBeenCalledTimes(1);
- });
-
- it("creates fresh from the template when persisted session state disappeared", async () => {
- const vm = createFakeMicrosandboxVm("session-key");
- runtimeMocks.connectMicrosandbox.mockResolvedValueOnce(null);
- runtimeMocks.createPreparedMicrosandbox.mockResolvedValue(vm);
- runtimeMocks.snapshotExists.mockResolvedValue(true);
- const options = resolveMicrosandboxOptions({ image: MICROSANDBOX_DEFAULT_IMAGE });
-
- const handle = await createMicrosandboxHandle({
- backendName: "microsandbox",
- createInput: {
- existingMetadata: {
- optionsHash: "options-hash",
- sandboxName: "deleted-sandbox",
- stateSnapshotName: "deleted-session-snapshot",
- version: 2,
- },
- runtimeContext: { appRoot: "/tmp/eve-app" },
- sessionKey: "session-key",
- templateKey: "template-key",
- },
- options,
- optionsHash: "options-hash",
- });
-
- expect(runtimeMocks.connectMicrosandbox).toHaveBeenCalledTimes(1);
- expect(runtimeMocks.createPreparedMicrosandbox).toHaveBeenCalledWith(
- expect.objectContaining({
- fromSnapshot: "template-snapshot",
- sessionKey: "session-key",
- setupBaseRuntime: false,
- }),
- );
- await expect(handle.captureState()).resolves.toMatchObject({
- backendName: "microsandbox",
- sessionKey: "session-key",
- });
- });
-
- it("stops the VM and evicts the active-session cache on shutdown", async () => {
- const vm = createFakeMicrosandboxVm("session-key");
- runtimeMocks.createPreparedMicrosandbox.mockResolvedValue(vm);
- const options = resolveMicrosandboxOptions({ image: MICROSANDBOX_DEFAULT_IMAGE });
- const createInput = {
- runtimeContext: { appRoot: "/tmp/eve-app" },
- sessionKey: "session-key",
- templateKey: "template-key",
- };
-
- const handle = await createMicrosandboxHandle({
- backendName: "microsandbox",
- createInput,
- options,
- optionsHash: "options-hash",
- });
- await handle.shutdown();
-
- expect(vm.shutdown).toHaveBeenCalledTimes(1);
-
- const nextHandle = await createMicrosandboxHandle({
- backendName: "microsandbox",
- createInput,
- options,
- optionsHash: "options-hash",
- });
- expect(nextHandle).not.toBe(handle);
- expect(runtimeMocks.createPreparedMicrosandbox).toHaveBeenCalledTimes(2);
- });
-
- it("stops the VM and evicts the active-session cache on an authored stop", async () => {
- const vm = createFakeMicrosandboxVm("session-key");
- runtimeMocks.createPreparedMicrosandbox.mockResolvedValue(vm);
- const options = resolveMicrosandboxOptions({ image: MICROSANDBOX_DEFAULT_IMAGE });
- const createInput = {
- runtimeContext: { appRoot: "/tmp/eve-app" },
- sessionKey: "session-key",
- templateKey: "template-key",
- };
-
- const handle = await createMicrosandboxHandle({
- backendName: "microsandbox",
- createInput,
- options,
- optionsHash: "options-hash",
- });
- await handle.stop();
-
- expect(vm.stop).toHaveBeenCalledTimes(1);
-
- const nextHandle = await createMicrosandboxHandle({
- backendName: "microsandbox",
- createInput,
- options,
- optionsHash: "options-hash",
- });
- expect(nextHandle).not.toBe(handle);
- expect(runtimeMocks.createPreparedMicrosandbox).toHaveBeenCalledTimes(2);
- });
-
- it("deletes persisted state and evicts the active-session cache", async () => {
- const vm = createFakeMicrosandboxVm("session-key");
- runtimeMocks.createPreparedMicrosandbox.mockResolvedValue(vm);
- const options = resolveMicrosandboxOptions({ image: MICROSANDBOX_DEFAULT_IMAGE });
- const createInput = {
- runtimeContext: { appRoot: "/tmp/eve-app" },
- sessionKey: "session-key",
- templateKey: "template-key",
- };
-
- const handle = await createMicrosandboxHandle({
- backendName: "microsandbox",
- createInput,
- options,
- optionsHash: "options-hash",
- });
- await handle.delete();
-
- expect(vm.shutdown).toHaveBeenCalledTimes(1);
- expect(vm.removePersisted).toHaveBeenCalledTimes(1);
-
- const nextHandle = await createMicrosandboxHandle({
- backendName: "microsandbox",
- createInput,
- options,
- optionsHash: "options-hash",
- });
- expect(nextHandle).not.toBe(handle);
- expect(runtimeMocks.createPreparedMicrosandbox).toHaveBeenCalledTimes(2);
- });
-
- it("reports a missing template snapshot race as not provisioned", async () => {
- runtimeMocks.createPreparedMicrosandbox.mockRejectedValueOnce(
- new Error("snapshot template-snapshot not found"),
- );
- runtimeMocks.snapshotExists.mockResolvedValue(true);
- const options = resolveMicrosandboxOptions({ image: MICROSANDBOX_DEFAULT_IMAGE });
-
- await expect(
- createMicrosandboxHandle({
- backendName: "microsandbox",
- createInput: {
- runtimeContext: { appRoot: "/tmp/eve-app" },
- sessionKey: "session-key",
- templateKey: "template-key",
- },
- options,
- optionsHash: "options-hash",
- }),
- ).rejects.toBeInstanceOf(SandboxTemplateNotProvisionedError);
- });
-});
-
-describe("prewarmMicrosandboxTemplate", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- runtimeMocks.loadMicrosandboxModule.mockResolvedValue({} as never);
- runtimeMocks.snapshotExists.mockResolvedValue(false);
- metadataMocks.readTemplateMetadata.mockResolvedValue({
- optionsHash: "options-hash",
- snapshotName: "missing-template-snapshot",
- version: 2,
- });
- });
-
- it("replaces stale template metadata after rebuilding a missing snapshot", async () => {
- runtimeMocks.createPreparedMicrosandbox.mockResolvedValue(createFakeMicrosandboxVm("template"));
- const appRoot = "/tmp/eve-app";
- const templateRootPath = "/tmp/eve-app/.eve/sandbox-cache/microsandbox/templates/template-key";
-
- const result = await prewarmMicrosandboxTemplate({
- backendName: "microsandbox",
- options: resolveMicrosandboxOptions({ image: MICROSANDBOX_DEFAULT_IMAGE }),
- optionsHash: "options-hash",
- prewarmInput: {
- runtimeContext: { appRoot },
- seedFiles: [],
- templateKey: "template-key",
- },
- });
-
- const replaceCallIndex = fsMocks.rm.mock.calls.findIndex(([path]) => path === templateRootPath);
- const renameOrder = fsMocks.rename.mock.invocationCallOrder[0];
- const replaceOrder = fsMocks.rm.mock.invocationCallOrder[replaceCallIndex];
- expect(replaceCallIndex).toBeGreaterThanOrEqual(0);
- if (renameOrder === undefined || replaceOrder === undefined) {
- throw new Error("Expected template replacement before rename.");
- }
- expect(replaceOrder).toBeLessThan(renameOrder);
- expect(fsMocks.rename).toHaveBeenCalledWith(
- expect.stringMatching(
- /^\/tmp\/eve-app\/\.eve\/sandbox-cache\/microsandbox\/templates\/template-key\..+\.tmp$/u,
- ),
- templateRootPath,
- );
- expect(result).toEqual({ reused: false });
- });
-
- it("writes seed files before bootstrap and snapshots bootstrap outputs", async () => {
- const vm = createFakeMicrosandboxVm("template");
- runtimeMocks.createPreparedMicrosandbox.mockResolvedValue(vm);
-
- await prewarmMicrosandboxTemplate({
- backendName: "microsandbox",
- options: resolveMicrosandboxOptions({ image: MICROSANDBOX_DEFAULT_IMAGE }),
- optionsHash: "options-hash",
- prewarmInput: {
- bootstrap: async ({ use }) => {
- const sandbox = await use();
- await expect(sandbox.readTextFile({ path: "/workspace/seed.txt" })).resolves.toBe(
- "authored seed",
- );
- await sandbox.writeTextFile({
- content: "bootstrap output",
- path: "/workspace/bootstrap.txt",
- });
- },
- runtimeContext: { appRoot: "/tmp/eve-app" },
- seedFiles: [{ content: "authored seed", path: "/workspace/seed.txt" }],
- templateKey: "template-key",
- },
- });
-
- await expect(vm.readFileBytes("/workspace/bootstrap.txt")).resolves.toEqual(
- Buffer.from("bootstrap output"),
- );
- expect(vm.writeFiles.mock.invocationCallOrder[1]).toBeLessThan(
- vm.stopAndSnapshot.mock.invocationCallOrder[0]!,
- );
- });
-});
-
-function createFakeMicrosandboxVm(sessionKey: string) {
- const files = new Map<string, Buffer>();
-
- return {
- id: sessionKey,
- async captureState(optionsHash: string) {
- return {
- optionsHash,
- sandboxName: "active-sandbox",
- version: 2,
- };
- },
- async detach() {},
- stop: vi.fn(async () => {}),
- shutdown: vi.fn(async () => {}),
- async readFileBytes(path: string) {
- return files.get(path) ?? null;
- },
- async removePath({ path }: { readonly path: string }) {
- files.delete(path);
- },
- removePersisted: vi.fn(async () => {}),
- async setNetworkPolicy() {},
- async spawn() {
- throw new Error("spawn is not used by this test.");
- },
- stopAndSnapshot: vi.fn(async () => {}),
- writeFiles: vi.fn(
- async (nextFiles: ReadonlyArray<{ readonly content: Uint8Array; readonly path: string }>) => {
- for (const file of nextFiles) {
- files.set(file.path, Buffer.from(file.content));
- }
- },
- ),
- async writeMetadata() {},
- };
-}
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.ts
index 1a4c05b03..9eb071a0e 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.ts
@@ -1,27 +1,43 @@
import { randomUUID } from "node:crypto";
+
+import {
+ hydrateSandboxProviderResources,
+ prepareImmutableResources,
+} from "#execution/sandbox/bindings/immutable-resources.js";
+
+import {
+ assertDockerDaemonAvailable,
+ createDockerCli,
+} from "#execution/sandbox/bindings/docker-cli.js";
+import {
+ buildSandboxDockerfile,
+ dockerfileImageReference,
+ publishDockerImageForMicrosandbox,
+} from "#execution/sandbox/dockerfile.js";
import { mkdir, rename, rm } from "node:fs/promises";
import { dirname } from "node:path";
import {
createFileBackedInternalSandboxSession,
touchDirectory,
- writeSandboxSeedFiles,
-} from "#execution/sandbox/bindings/local-backend-utils.js";
+} from "#execution/sandbox/bindings/local-provider-utils.js";
import {
MICROSANDBOX_METADATA_VERSION,
+ type MicrosandboxSessionMetadata,
+ type MicrosandboxTemplateMetadata,
readSessionMetadata,
- readSessionMetadataRecord,
readTemplateMetadata,
resolveMicrosandboxMetadataPath,
writeTemplateMetadata,
} from "#execution/sandbox/bindings/microsandbox-metadata.js";
import type { ResolvedMicrosandboxOptions } from "#execution/sandbox/bindings/microsandbox-options.js";
+import type { MicrosandboxSandboxRuntimeOptions } from "#public/sandbox/microsandbox-sandbox.js";
import {
connectMicrosandbox,
createPreparedMicrosandbox,
createProviderName,
+ createStableHash,
doesPathExist,
- isMicrosandboxNotFoundError,
loadMicrosandboxModule,
type MicrosandboxVm,
removeSnapshotIfExists,
@@ -35,78 +51,114 @@ import {
import { createLoggingSandboxSession } from "#execution/sandbox/logging-session.js";
import { withDevelopmentSandboxMetadataPathTag } from "#execution/sandbox/development-run.js";
import { buildSandboxSession } from "#execution/sandbox/session.js";
-import { resolveSandboxCacheDirectory } from "#internal/application/paths.js";
-import type {
- SandboxBackendCreateInput,
- SandboxBackendHandle,
- SandboxBackendPrewarmInput,
- SandboxBackendPrewarmResult,
-} from "#public/definitions/sandbox-backend.js";
-import { SandboxTemplateNotProvisionedError } from "#public/definitions/sandbox-backend.js";
+import {
+ isSandboxPreparedArtifactRecord,
+ type SandboxPreparedArtifact,
+ type SandboxProviderSessionContext,
+ type SandboxProviderHandle,
+ type SandboxProviderPrepareContext,
+} from "#shared/sandbox-provider.js";
+import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";
import type {
- MicrosandboxBootstrapUseOptions,
- MicrosandboxSessionUseOptions,
-} from "#public/sandbox/microsandbox-sandbox.js";
-import type { InternalSandboxSession } from "#shared/sandbox-session.js";
+ InternalSandboxSession,
+ MutableNetworkSandboxSession,
+} from "#shared/sandbox-session.js";
+
+type LiveMicrosandboxOptions = ResolvedMicrosandboxOptions & MicrosandboxSandboxRuntimeOptions;
+
+export type MicrosandboxPreparedArtifact = {
+ readonly image: string | null;
+ readonly optionsHash: string;
+ readonly snapshotName: string;
+ readonly version: typeof MICROSANDBOX_METADATA_VERSION;
+};
const activeMicrosandboxSessionHandles = new Map<
string,
- SandboxBackendHandle<MicrosandboxSessionUseOptions>
+ SandboxProviderHandle<MutableNetworkSandboxSession>
>();
export async function prewarmMicrosandboxTemplate(input: {
- readonly backendName: string;
+ readonly providerName: string;
readonly options: ResolvedMicrosandboxOptions;
readonly optionsHash: string;
- readonly prewarmInput: SandboxBackendPrewarmInput<MicrosandboxBootstrapUseOptions>;
-}): Promise<SandboxBackendPrewarmResult> {
- input.prewarmInput.log?.("loading microsandbox runtime");
+ readonly context: SandboxProviderPrepareContext;
+ readonly dockerfile?: import("#execution/sandbox/dockerfile.js").SandboxDockerfile;
+ readonly prepare?: (
+ sandbox: import("#shared/sandbox-session.js").SandboxSession,
+ ) => Promise<void> | void;
+ readonly templateKey: string;
+}): Promise<MicrosandboxPreparedArtifact> {
+ input.context.log?.("loading microsandbox runtime");
const module = await loadMicrosandboxModule({
- appRoot: input.prewarmInput.runtimeContext.appRoot,
- log: input.prewarmInput.log,
+ host: input.context.host,
+ log: input.context.log,
options: input.options,
});
- const cacheDirectory = resolveSandboxCacheDirectory(input.prewarmInput.runtimeContext.appRoot);
- const templateRootPath = resolveMicrosandboxTemplateRootPath(
- cacheDirectory,
- input.prewarmInput.templateKey,
- );
+ const cacheDirectory = input.context.storagePath;
+ const templateRootPath = resolveMicrosandboxTemplateRootPath(cacheDirectory, input.templateKey);
const metadataPath = resolveMicrosandboxMetadataPath(templateRootPath);
- input.prewarmInput.log?.("checking cached snapshot");
+ input.context.log?.("checking cached snapshot");
const existing = await readTemplateMetadata(metadataPath);
if (
existing?.optionsHash === input.optionsHash &&
(await snapshotExists(module, existing.snapshotName))
) {
- input.prewarmInput.log?.("reusing cached snapshot");
+ input.context.log?.("reusing cached snapshot");
await touchDirectory(templateRootPath);
- return { reused: true };
+ return microsandboxTemplateArtifact(existing);
}
- const snapshotName = createProviderName(
- "eve-sbx-tpl",
- input.prewarmInput.templateKey,
- input.optionsHash,
- );
+ const snapshotName = createProviderName("eve-sbx-tpl", input.templateKey, input.optionsHash);
const temporaryTemplateRootPath = `${templateRootPath}.${randomUUID()}.tmp`;
const temporarySandboxName = createProviderName(
"eve-sbx-tpl-tmp",
- `${input.prewarmInput.templateKey}:${randomUUID()}`,
+ `${input.templateKey}:${randomUUID()}`,
);
await removeSnapshotIfExists(module, snapshotName);
await rm(temporaryTemplateRootPath, { force: true, recursive: true });
await mkdir(temporaryTemplateRootPath, { recursive: true });
- input.prewarmInput.log?.(`creating template VM from image "${input.options.image}"`);
+ let templateOptions = input.options;
+ if (input.dockerfile !== undefined) {
+ const cli = createDockerCli();
+ await assertDockerDaemonAvailable(cli);
+ const imageReference = dockerfileImageReference({
+ dockerfile: input.dockerfile,
+ templateKey: input.templateKey,
+ });
+ input.context.log?.(`building sandbox Dockerfile "${input.dockerfile.path}"`);
+ await buildSandboxDockerfile({
+ cli,
+ dockerfile: input.dockerfile,
+ imageReference,
+ });
+ input.context.log?.("publishing Dockerfile image for microsandbox");
+ const publishedImage = await publishDockerImageForMicrosandbox({ cli, imageReference });
+ templateOptions = { ...input.options, image: publishedImage, pullPolicy: "always" };
+ }
+
+ const resourceSource = input.context.resources.source;
+ const resourcesPath =
+ resourceSource.kind === "materialized"
+ ? await prepareImmutableResources({
+ storagePath: input.context.storagePath,
+ provider: input.providerName,
+ resourcesKey: resourceSource.key,
+ sourcePath: resourceSource.path,
+ })
+ : undefined;
+ input.context.log?.(`creating template VM from image "${templateOptions.image}"`);
const templateSandbox = await createPreparedMicrosandbox({
- log: input.prewarmInput.log,
+ log: input.context.log,
module,
name: temporarySandboxName,
- networkPolicy: input.options.networkPolicy,
- options: input.options,
- sessionKey: input.prewarmInput.templateKey,
+ networkPolicy: "allow-all",
+ options: templateOptions,
+ resourcesPath,
+ sessionKey: input.templateKey,
setupBaseRuntime: true,
tags: undefined,
});
@@ -118,29 +170,24 @@ export async function prewarmMicrosandboxTemplate(input: {
);
try {
- if (input.prewarmInput.seedFiles.length > 0) {
- input.prewarmInput.log?.(`writing ${input.prewarmInput.seedFiles.length} seed file(s)`);
- }
- await writeSandboxSeedFiles(templateSession, input.prewarmInput.seedFiles);
+ await hydrateSandboxProviderResources({
+ copySkills: true,
+ log: input.context.log,
+ resources: input.context.resources,
+ session: templateSession,
+ });
- if (input.prewarmInput.bootstrap !== undefined) {
- input.prewarmInput.log?.("running sandbox bootstrap");
- await input.prewarmInput.bootstrap({
- use: async (useOptions?: MicrosandboxBootstrapUseOptions) => {
- if (useOptions?.networkPolicy !== undefined) {
- await templateSandbox.setNetworkPolicy(useOptions.networkPolicy);
- }
- return createLoggingSandboxSession({
- log: input.prewarmInput.log,
- session: templateSession,
- });
- },
- });
+ if (input.prepare !== undefined) {
+ input.context.log?.("running sandbox preparation");
+ await input.prepare(
+ createLoggingSandboxSession({ log: input.context.log, session: templateSession }),
+ );
}
- input.prewarmInput.log?.("snapshotting template VM");
+ input.context.log?.("snapshotting template VM");
await templateSandbox.stopAndSnapshot(snapshotName);
await writeTemplateMetadata(resolveMicrosandboxMetadataPath(temporaryTemplateRootPath), {
+ image: input.dockerfile === undefined ? undefined : templateOptions.image,
optionsHash: input.optionsHash,
snapshotName,
version: MICROSANDBOX_METADATA_VERSION,
@@ -152,7 +199,10 @@ export async function prewarmMicrosandboxTemplate(input: {
await rename(temporaryTemplateRootPath, templateRootPath);
} catch (error) {
if (await doesPathExist(templateRootPath)) {
- return { reused: true };
+ const published = await readTemplateMetadata(metadataPath);
+ if (published !== null) {
+ return microsandboxTemplateArtifact(published);
+ }
}
throw error;
}
@@ -161,129 +211,175 @@ export async function prewarmMicrosandboxTemplate(input: {
await rm(temporaryTemplateRootPath, { force: true, recursive: true }).catch(() => {});
}
- return { reused: false };
+ return microsandboxTemplateArtifact({
+ image: input.dockerfile === undefined ? undefined : templateOptions.image,
+ optionsHash: input.optionsHash,
+ snapshotName,
+ version: MICROSANDBOX_METADATA_VERSION,
+ });
}
export async function createMicrosandboxHandle(input: {
- readonly backendName: string;
- readonly createInput: SandboxBackendCreateInput;
+ readonly artifact: MicrosandboxPreparedArtifact;
+ readonly context: SandboxProviderSessionContext;
+ readonly createIfMissing?: boolean;
readonly options: ResolvedMicrosandboxOptions;
readonly optionsHash: string;
-}): Promise<SandboxBackendHandle<MicrosandboxSessionUseOptions>> {
- const module = await loadMicrosandboxModule({
- appRoot: input.createInput.runtimeContext.appRoot,
- options: input.options,
- });
- const cacheDirectory = resolveSandboxCacheDirectory(input.createInput.runtimeContext.appRoot);
+ readonly providerName: string;
+ readonly runtimeOptions?: MicrosandboxSandboxRuntimeOptions;
+ readonly sessionIdentity?: string;
+}): Promise<{
+ readonly handle: SandboxProviderHandle<MutableNetworkSandboxSession>;
+ readonly state: {
+ readonly optionsHash: string;
+ readonly sessionIdentity: string;
+ readonly version: 3;
+ };
+}> {
+ const preparedTemplate = requirePreparedMicrosandboxTemplate(input.artifact, input.providerName);
+ const sessionIdentity =
+ input.sessionIdentity ??
+ createStableHash(
+ `${input.context.session.id}:${preparedTemplate.snapshotName}:${input.optionsHash}`,
+ ).slice(0, 32);
const sessionRootPath = resolveMicrosandboxSessionRootPath(
- cacheDirectory,
- input.createInput.sessionKey,
+ input.context.storagePath,
+ sessionIdentity,
);
+ const metadataPath = resolveMicrosandboxMetadataPath(sessionRootPath);
+ const existingState = await readSessionMetadata(metadataPath);
+ const image = resolveMicrosandboxImage(existingState, preparedTemplate, input.options);
+ const options: LiveMicrosandboxOptions = {
+ ...input.options,
+ ...image,
+ networkPolicy: input.runtimeOptions?.networkPolicy,
+ };
+ const module = await loadMicrosandboxModule({ host: input.context.host, options });
const activeSessionKey = createActiveMicrosandboxSessionKey(sessionRootPath, input.optionsHash);
const activeHandle = activeMicrosandboxSessionHandles.get(activeSessionKey);
- if (activeHandle !== undefined) {
- return activeHandle;
- }
-
- const metadataPath = resolveMicrosandboxMetadataPath(sessionRootPath);
- const existingMetadata =
- readSessionMetadataRecord(input.createInput.existingMetadata) ??
- (await readSessionMetadata(metadataPath));
- const sessionTags = withDevelopmentSandboxMetadataPathTag(input.createInput.tags, metadataPath);
+ const state = { optionsHash: input.optionsHash, sessionIdentity, version: 3 as const };
+ if (activeHandle !== undefined) return { handle: activeHandle, state };
+ const sessionTags = withDevelopmentSandboxMetadataPathTag(
+ { sessionId: input.context.session.id },
+ metadataPath,
+ );
if (
- existingMetadata?.optionsHash === input.optionsHash &&
- ((await sandboxExists(module, existingMetadata.sandboxName)) ||
- (existingMetadata.stateSnapshotName !== undefined &&
- (await snapshotExists(module, existingMetadata.stateSnapshotName))))
+ existingState?.optionsHash === input.optionsHash &&
+ ((await sandboxExists(module, existingState.sandboxName)) ||
+ (existingState.stateSnapshotName !== undefined &&
+ (await snapshotExists(module, existingState.stateSnapshotName))))
) {
- const sandbox = await connectMicrosandbox({
- metadata: existingMetadata,
+ const connected = await connectMicrosandbox({
+ metadata: existingState,
metadataPath,
module,
- options: input.options,
- sessionKey: input.createInput.sessionKey,
+ options,
+ sessionKey: input.context.session.id,
tags: sessionTags,
});
- if (sandbox !== null) {
- return cacheHandle(
- activeSessionKey,
- createHandle(sandbox, input.backendName, input.optionsHash, () => {
- activeMicrosandboxSessionHandles.delete(activeSessionKey);
- }),
- );
+ if (connected !== null) {
+ return {
+ handle: cacheHandle(
+ activeSessionKey,
+ createHandle(connected, input.optionsHash, () => {
+ activeMicrosandboxSessionHandles.delete(activeSessionKey);
+ }),
+ ),
+ state,
+ };
}
}
- let snapshotName: string | null = null;
- if (input.createInput.templateKey !== null) {
- const templateRootPath = resolveMicrosandboxTemplateRootPath(
- cacheDirectory,
- input.createInput.templateKey,
- );
- const templateMetadata = await readTemplateMetadata(
- resolveMicrosandboxMetadataPath(templateRootPath),
+ if (input.sessionIdentity !== undefined && input.createIfMissing === false) {
+ throw new Error(
+ `microsandbox session "${input.sessionIdentity}" is no longer available to resume.`,
);
-
- if (
- templateMetadata === null ||
- templateMetadata.optionsHash !== input.optionsHash ||
- !(await snapshotExists(module, templateMetadata.snapshotName))
- ) {
- throw new SandboxTemplateNotProvisionedError({
- backendName: input.backendName,
- templateKey: input.createInput.templateKey,
- });
- }
-
- snapshotName = templateMetadata.snapshotName;
}
- const sandboxName = createProviderName(
- "eve-sbx-ses",
- `${input.createInput.sessionKey}:${randomUUID()}`,
- );
- let sandbox: MicrosandboxVm;
- try {
- sandbox = await createPreparedMicrosandbox({
- fromSnapshot: snapshotName ?? undefined,
- module,
- name: sandboxName,
- networkPolicy: input.options.networkPolicy,
- options: input.options,
- sessionKey: input.createInput.sessionKey,
- setupBaseRuntime: snapshotName === null,
- tags: sessionTags,
+ if (
+ preparedTemplate.optionsHash !== input.optionsHash ||
+ !(await snapshotExists(module, preparedTemplate.snapshotName))
+ ) {
+ throw new SandboxTemplateNotProvisionedError({
+ providerName: input.providerName,
+ templateKey: preparedTemplate.snapshotName,
});
- } catch (error) {
- if (
- snapshotName !== null &&
- input.createInput.templateKey !== null &&
- isMicrosandboxNotFoundError(error)
- ) {
- throw new SandboxTemplateNotProvisionedError({
- backendName: input.backendName,
- templateKey: input.createInput.templateKey,
- });
- }
- throw error;
}
-
+ const sandboxName = createProviderName("eve-sbx-ses", sessionIdentity);
+ const sandbox = await createPreparedMicrosandbox({
+ fromSnapshot: preparedTemplate.snapshotName,
+ module,
+ name: sandboxName,
+ networkPolicy: options.networkPolicy,
+ options,
+ sessionKey: input.context.session.id,
+ setupBaseRuntime: false,
+ tags: sessionTags,
+ });
await sandbox.writeMetadata(metadataPath, input.optionsHash);
- return cacheHandle(
+ const handle = cacheHandle(
activeSessionKey,
- createHandle(sandbox, input.backendName, input.optionsHash, () => {
+ createHandle(sandbox, input.optionsHash, () => {
activeMicrosandboxSessionHandles.delete(activeSessionKey);
}),
);
+ return { handle, state };
+}
+
+function resolveMicrosandboxImage(
+ session: Readonly<MicrosandboxSessionMetadata> | null,
+ template: MicrosandboxTemplateMetadata | undefined,
+ defaults: ResolvedMicrosandboxOptions,
+): Pick<ResolvedMicrosandboxOptions, "image" | "pullPolicy"> {
+ if (session?.image !== undefined) {
+ return { image: session.image, pullPolicy: "always" };
+ }
+ if (template?.image !== undefined) {
+ return { image: template.image, pullPolicy: "always" };
+ }
+ return { image: defaults.image, pullPolicy: defaults.pullPolicy };
+}
+
+function microsandboxTemplateArtifact(
+ metadata: MicrosandboxTemplateMetadata,
+): MicrosandboxPreparedArtifact {
+ return {
+ image: metadata.image ?? null,
+ optionsHash: metadata.optionsHash,
+ snapshotName: metadata.snapshotName,
+ version: metadata.version,
+ };
+}
+
+function requirePreparedMicrosandboxTemplate(
+ artifact: SandboxPreparedArtifact,
+ providerName: string,
+): MicrosandboxTemplateMetadata {
+ if (
+ !isSandboxPreparedArtifactRecord(artifact) ||
+ artifact.version !== MICROSANDBOX_METADATA_VERSION ||
+ typeof artifact.optionsHash !== "string" ||
+ typeof artifact.snapshotName !== "string"
+ ) {
+ throw new SandboxTemplateNotProvisionedError({
+ providerName,
+ templateKey: "invalid-artifact",
+ });
+ }
+ return {
+ image: typeof artifact.image === "string" ? artifact.image : undefined,
+ optionsHash: artifact.optionsHash,
+ snapshotName: artifact.snapshotName,
+ version: MICROSANDBOX_METADATA_VERSION,
+ };
}
function createHandle(
sandbox: MicrosandboxVm,
- backendName: string,
- optionsHash: string,
+ _optionsHash: string,
onShutdown?: () => void,
-): SandboxBackendHandle<MicrosandboxSessionUseOptions> {
+): SandboxProviderHandle<MutableNetworkSandboxSession> {
const session = buildSandboxSession(
createMicrosandboxInternalSession(sandbox),
async (policy) => {
@@ -291,33 +387,17 @@ function createHandle(
},
);
return {
- session,
- useSessionFn: async (options?: MicrosandboxSessionUseOptions) => {
- if (options?.networkPolicy !== undefined) {
- await sandbox.setNetworkPolicy(options.networkPolicy);
- }
- return buildSandboxSession(createMicrosandboxInternalSession(sandbox), async (policy) => {
- await sandbox.setNetworkPolicy(policy);
- });
- },
- async captureState() {
- const metadata = await sandbox.captureState(optionsHash);
- return {
- backendName,
- metadata: { ...metadata },
- sessionKey: sandbox.id,
- };
- },
- async delete() {
+ sandbox: session,
+ async onSessionDelete() {
await sandbox.shutdown();
await sandbox.removePersisted();
onShutdown?.();
},
- async stop() {
+ async onSessionStop() {
await sandbox.stop();
onShutdown?.();
},
- async shutdown() {
+ async onRuntimeShutdown() {
onShutdown?.();
await sandbox.shutdown();
},
@@ -325,7 +405,7 @@ function createHandle(
}
function createMicrosandboxInternalSession(sandbox: MicrosandboxVm): InternalSandboxSession {
- return createFileBackedInternalSandboxSession({ id: sandbox.id, sandbox });
+ return createFileBackedInternalSandboxSession({ sandbox });
}
function createActiveMicrosandboxSessionKey(sessionRootPath: string, optionsHash: string): string {
@@ -334,8 +414,8 @@ function createActiveMicrosandboxSessionKey(sessionRootPath: string, optionsHash
function cacheHandle(
key: string,
- handle: SandboxBackendHandle<MicrosandboxSessionUseOptions>,
-): SandboxBackendHandle<MicrosandboxSessionUseOptions> {
+ handle: SandboxProviderHandle<MutableNetworkSandboxSession>,
+): SandboxProviderHandle<MutableNetworkSandboxSession> {
activeMicrosandboxSessionHandles.set(key, handle);
return handle;
}
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-metadata.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-metadata.ts
index b646c462b..7c6a1e2d1 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-metadata.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-metadata.ts
@@ -2,18 +2,23 @@ import { randomUUID } from "node:crypto";
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
-import type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";
+import {
+ isSandboxNetworkPolicy,
+ type SandboxNetworkPolicy,
+} from "#shared/sandbox-network-policy.js";
export const MICROSANDBOX_METADATA_VERSION = 2;
export const MICROSANDBOX_METADATA_FILE_NAME = "metadata.json";
export interface MicrosandboxTemplateMetadata {
+ readonly image?: string;
readonly optionsHash: string;
readonly snapshotName: string;
readonly version: typeof MICROSANDBOX_METADATA_VERSION;
}
export interface MicrosandboxSessionMetadata {
+ readonly image?: string;
readonly networkPolicy?: SandboxNetworkPolicy;
readonly optionsHash: string;
readonly sandboxName: string;
@@ -21,6 +26,28 @@ export interface MicrosandboxSessionMetadata {
readonly version: typeof MICROSANDBOX_METADATA_VERSION;
}
+export function createMicrosandboxSessionMetadata(input: {
+ readonly networkPolicy: SandboxNetworkPolicy | undefined;
+ readonly optionsHash: string;
+ readonly sandboxName: string;
+ readonly stateSnapshotName: string | undefined;
+}): MicrosandboxSessionMetadata {
+ const metadata: {
+ networkPolicy?: SandboxNetworkPolicy;
+ optionsHash: string;
+ sandboxName: string;
+ stateSnapshotName?: string;
+ version: typeof MICROSANDBOX_METADATA_VERSION;
+ } = {
+ optionsHash: input.optionsHash,
+ sandboxName: input.sandboxName,
+ version: MICROSANDBOX_METADATA_VERSION,
+ };
+ if (input.networkPolicy !== undefined) metadata.networkPolicy = input.networkPolicy;
+ if (input.stateSnapshotName !== undefined) metadata.stateSnapshotName = input.stateSnapshotName;
+ return metadata;
+}
+
export function resolveMicrosandboxMetadataPath(rootPath: string): string {
return join(rootPath, MICROSANDBOX_METADATA_FILE_NAME);
}
@@ -37,6 +64,7 @@ export async function readTemplateMetadata(
return null;
}
return {
+ image: typeof metadata.image === "string" ? metadata.image : undefined,
optionsHash: metadata.optionsHash,
snapshotName: metadata.snapshotName,
version: MICROSANDBOX_METADATA_VERSION,
@@ -63,12 +91,14 @@ export function readSessionMetadataRecord(value: unknown): MicrosandboxSessionMe
if (
value.version !== MICROSANDBOX_METADATA_VERSION ||
typeof value.optionsHash !== "string" ||
- typeof value.sandboxName !== "string"
+ typeof value.sandboxName !== "string" ||
+ (value.networkPolicy !== undefined && !isSandboxNetworkPolicy(value.networkPolicy))
) {
return null;
}
return {
- networkPolicy: value.networkPolicy as SandboxNetworkPolicy | undefined,
+ image: typeof value.image === "string" ? value.image : undefined,
+ networkPolicy: value.networkPolicy,
optionsHash: value.optionsHash,
sandboxName: value.sandboxName,
stateSnapshotName:
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-network.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-network.ts
index 1e17c2f10..a740c3099 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-network.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-network.ts
@@ -295,10 +295,7 @@ function normalizeAllowEntries(
if (Array.isArray(allow)) {
return allow.map((domain) => ({ domain, rules: [] }));
}
- return Object.entries(allow).map(([domain, rules]) => ({
- domain,
- rules: Array.isArray(rules) ? rules : [],
- }));
+ return Object.entries(allow).map(([domain, rules]) => ({ domain, rules }));
}
function normalizeTransforms(
@@ -324,18 +321,25 @@ function serializeMicrosandboxNetworkDestination(
case "any":
return "any";
case "cidr":
- return { cidr: destination.cidr ?? "" };
+ return { cidr: requireDestinationValue(destination.cidr, "CIDR") };
case "domain":
- return { domain: destination.domain ?? "" };
+ return { domain: requireDestinationValue(destination.domain, "domain") };
case "domainSuffix":
- return { domain_suffix: destination.suffix ?? "" };
+ return { domain_suffix: requireDestinationValue(destination.suffix, "domain suffix") };
case "group":
- return { group: destination.group ?? "" };
+ return { group: requireDestinationValue(destination.group, "group") };
default:
throw new Error("Unsupported microsandbox network destination kind.");
}
}
+function requireDestinationValue(value: string | undefined, kind: string): string {
+ if (value === undefined || value.length === 0) {
+ throw new Error(`Microsandbox network destination is missing its ${kind}.`);
+ }
+ return value;
+}
+
function createPlaceholderHeaders(
domain: string,
headers: Readonly<Record<string, string>>,
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-options.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-options.ts
index 1be9aed44..0d1c3923d 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-options.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-options.ts
@@ -1,6 +1,5 @@
import { DEFAULT_EVE_SANDBOX_IMAGE } from "#execution/sandbox/bindings/eve-image.js";
import type { MicrosandboxSandboxCreateOptions } from "#public/sandbox/microsandbox-sandbox.js";
-import type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";
export const MICROSANDBOX_DEFAULT_IMAGE = DEFAULT_EVE_SANDBOX_IMAGE;
export const MICROSANDBOX_DEFAULT_CPUS = 1;
@@ -10,7 +9,7 @@ export const MICROSANDBOX_DEFAULT_PULL_POLICY = "if-missing";
export const MICROSANDBOX_USER = "vercel-sandbox";
/**
- * Fully-defaulted microsandbox backend options consumed by the backend
+ * Fully-defaulted microsandbox options consumed by the provider
* implementation.
*/
export interface ResolvedMicrosandboxOptions {
@@ -18,7 +17,6 @@ export interface ResolvedMicrosandboxOptions {
readonly env: Readonly<Record<string, string>>;
readonly image: string;
readonly memoryMiB: number;
- readonly networkPolicy?: SandboxNetworkPolicy;
readonly pullPolicy: "always" | "if-missing" | "never";
readonly setup: {
readonly autoInstall: boolean;
@@ -37,7 +35,6 @@ export function resolveMicrosandboxOptions(
env: options?.env ?? {},
image: options?.image ?? MICROSANDBOX_DEFAULT_IMAGE,
memoryMiB: options?.memoryMiB ?? MICROSANDBOX_DEFAULT_MEMORY_MIB,
- networkPolicy: options?.networkPolicy,
pullPolicy: options?.pullPolicy ?? MICROSANDBOX_DEFAULT_PULL_POLICY,
setup: {
autoInstall: options?.setup?.autoInstall ?? true,
@@ -51,9 +48,17 @@ export function resolveMicrosandboxOptions(
* compatibility hashing. Setup behavior intentionally stays out: how
* the runtime got installed must not invalidate captured templates.
*/
+interface MicrosandboxTemplateOptions {
+ readonly cpus: number;
+ readonly env: Readonly<Record<string, string>>;
+ readonly image: string;
+ readonly memoryMiB: number;
+ readonly pullPolicy: ResolvedMicrosandboxOptions["pullPolicy"];
+}
+
export function microsandboxOptionsForHash(
options: ResolvedMicrosandboxOptions,
-): Record<string, unknown> {
+): MicrosandboxTemplateOptions {
return {
cpus: options.cpus,
env: options.env,
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-platform.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-platform.ts
index 1fb003d96..a983435aa 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-platform.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-platform.ts
@@ -48,24 +48,24 @@ export async function assertMicrosandboxPlatformCandidate(): Promise<void> {
if (process.platform === "linux" && (process.arch === "x64" || process.arch === "arm64")) {
if (!isGlibcLinux()) {
throw new Error(
- "The microsandbox sandbox backend requires a glibc-based Linux distribution; musl " +
- "hosts are not supported. Use docker() or vercel() instead.",
+ "The microsandbox sandbox provider requires a glibc-based Linux distribution; musl " +
+ "hosts are not supported. Use DockerSandbox or VercelSandbox instead.",
);
}
if (process.env.MSB_PATH !== undefined || (await doesPathExist("/dev/kvm"))) {
return;
}
throw new Error(
- "The microsandbox sandbox backend requires Linux with KVM enabled. `/dev/kvm` is not " +
+ "The microsandbox sandbox provider requires Linux with KVM enabled. `/dev/kvm` is not " +
"available on this host. Enable KVM, set MSB_PATH for a custom runtime, or use " +
- "docker() / vercel().",
+ "DockerSandbox or VercelSandbox.",
);
}
throw new Error(
- "The microsandbox sandbox backend supports Linux with KVM or macOS on Apple Silicon. " +
- `Current host is ${process.platform}/${process.arch}. Use docker() or ` +
- "vercel() on this host.",
+ "The microsandbox sandbox provider supports Linux with KVM or macOS on Apple Silicon. " +
+ `Current host is ${process.platform}/${process.arch}. Use DockerSandbox or ` +
+ "VercelSandbox on this host.",
);
}
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.test.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.test.ts
index cb72e887d..0331b3ae0 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.test.ts
@@ -49,7 +49,7 @@ describe.skipIf(process.platform === "win32")("connectMicrosandbox", () => {
}),
);
- await vm.setNetworkPolicy("deny-all");
+ await vm.setNetworkPolicy?.("deny-all");
expect(metadataState.writeSessionMetadata).toHaveBeenCalledWith(
"/tmp/eve-microsandbox-session/metadata.json",
@@ -366,6 +366,27 @@ describe.skipIf(process.platform === "win32")("createPreparedMicrosandbox", () =
}
});
+ it("mounts compiled resources read-only", async () => {
+ const module = createCreationModule({
+ create: async () => createMockMicrosandbox(),
+ progress: [],
+ });
+
+ await createPreparedMicrosandbox({
+ module: module as never,
+ name: "template-vm",
+ networkPolicy: "deny-all",
+ options: resolveMicrosandboxOptions(undefined),
+ resourcesPath: "/tmp/resources",
+ sessionKey: "template-key",
+ setupBaseRuntime: false,
+ });
+
+ expect(module.mounts).toEqual([
+ { guest: "/eve/resources", host: "/tmp/resources", readonly: true },
+ ]);
+ });
+
it("adds image and provider context when VM creation rejects", async () => {
class TestMicrosandboxError extends Error {
readonly code = "imageNotFound";
@@ -450,6 +471,7 @@ function createCreationModule(input: {
readonly create: () => Promise<ReturnType<typeof createMockMicrosandbox>>;
readonly progress: readonly Record<string, unknown>[];
}) {
+ const mounts: Array<{ guest: string; host?: string; readonly: boolean }> = [];
const builder = {
cpus: returnBuilder,
async create() {
@@ -472,6 +494,26 @@ function createCreationModule(input: {
pullPolicy: returnBuilder,
replace: returnBuilder,
user: returnBuilder,
+ volume(guest: string, configure: (mount: unknown) => unknown) {
+ const record = { guest, readonly: false } as {
+ guest: string;
+ host?: string;
+ readonly: boolean;
+ };
+ const mount = {
+ bind(host: string) {
+ record.host = host;
+ return mount;
+ },
+ readonly() {
+ record.readonly = true;
+ return mount;
+ },
+ };
+ configure(mount);
+ mounts.push(record);
+ return builder;
+ },
workdir: returnBuilder,
};
@@ -480,6 +522,7 @@ function createCreationModule(input: {
}
return {
+ mounts,
Sandbox: {
builder() {
return builder;
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.ts
index f697452fa..9c668643d 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.ts
@@ -14,6 +14,7 @@ import {
type ResolvedMicrosandboxOptions,
} from "#execution/sandbox/bindings/microsandbox-options.js";
import {
+ createMicrosandboxSessionMetadata,
MICROSANDBOX_METADATA_VERSION,
type MicrosandboxSessionMetadata,
writeSessionMetadata,
@@ -26,12 +27,11 @@ import { adaptMicrosandboxExecToSandboxProcess } from "#execution/sandbox/bindin
import {
importInstalledEnginePackage,
isEveDevEnvironment,
- loadOptionalEnginePackage,
} from "#internal/application/optional-package-install.js";
import { withDevelopmentSandboxTags } from "#execution/sandbox/development-run.js";
-import type { SandboxBackendTags } from "#public/definitions/sandbox-backend.js";
import { WORKSPACE_ROOT } from "#runtime/workspace/types.js";
import type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";
+import type { SandboxProviderHost } from "#shared/sandbox-provider.js";
import type {
SandboxProcess,
SandboxRemovePathOptions,
@@ -59,12 +59,14 @@ const MICROSANDBOX_PACKAGE_NAME = "microsandbox";
const MICROSANDBOX_CONNECT_TIMEOUT_MS = 10_000;
const MICROSANDBOX_STOP_TIMEOUT_MS = 10_000;
+const MICROSANDBOX_HOME = `/home/${MICROSANDBOX_USER}`;
+
export class MicrosandboxVm {
readonly #input: {
readonly module: MicrosandboxModule;
readonly options: ResolvedMicrosandboxOptions;
readonly sessionKey: string;
- readonly tags?: SandboxBackendTags;
+ readonly tags?: Readonly<Record<string, string>>;
};
#metadataPath?: string;
#networkPolicy?: SandboxNetworkPolicy;
@@ -78,7 +80,7 @@ export class MicrosandboxVm {
readonly module: MicrosandboxModule;
readonly options: ResolvedMicrosandboxOptions;
readonly sessionKey: string;
- readonly tags?: SandboxBackendTags;
+ readonly tags?: Readonly<Record<string, string>>;
},
sandbox: MicrosandboxSandbox,
sandboxName: string,
@@ -100,19 +102,22 @@ export class MicrosandboxVm {
return this.#input.sessionKey;
}
+ get name(): string {
+ return this.#sandboxName;
+ }
+
async captureState(optionsHash: string): Promise<MicrosandboxSessionMetadata> {
this.#optionsHash = optionsHash;
if (isEveDevEnvironment()) {
if (this.#metadataPath !== undefined) {
await this.writeMetadata(this.#metadataPath, optionsHash);
}
- return {
+ return createMicrosandboxSessionMetadata({
networkPolicy: this.#networkPolicy,
optionsHash,
sandboxName: this.#sandboxName,
stateSnapshotName: this.#stateSnapshotName,
- version: MICROSANDBOX_METADATA_VERSION,
- };
+ });
}
const previousStateSnapshotName = this.#stateSnapshotName;
@@ -129,13 +134,12 @@ export class MicrosandboxVm {
if (previousStateSnapshotName !== undefined) {
await removeSnapshotIfExists(this.#input.module, previousStateSnapshotName);
}
- return {
+ return createMicrosandboxSessionMetadata({
networkPolicy: this.#networkPolicy,
optionsHash,
sandboxName: this.#sandboxName,
stateSnapshotName,
- version: MICROSANDBOX_METADATA_VERSION,
- };
+ });
}
async detach(): Promise<void> {
@@ -233,6 +237,7 @@ export class MicrosandboxVm {
const env = {
...this.#input.options.env,
+ HOME: MICROSANDBOX_HOME,
...createTransformBrokerEnvironment(createMicrosandboxNetworkPlan(this.#networkPolicy)),
...options.env,
};
@@ -285,6 +290,7 @@ export class MicrosandboxVm {
this.#metadataPath = path;
this.#optionsHash = optionsHash;
await writeSessionMetadata(path, {
+ image: this.#input.options.image,
networkPolicy: this.#networkPolicy,
optionsHash,
sandboxName: this.#sandboxName,
@@ -319,9 +325,10 @@ export async function createPreparedMicrosandbox(input: {
readonly name: string;
readonly networkPolicy?: SandboxNetworkPolicy;
readonly options: ResolvedMicrosandboxOptions;
+ readonly resourcesPath?: string;
readonly sessionKey: string;
readonly setupBaseRuntime: boolean;
- readonly tags?: SandboxBackendTags;
+ readonly tags?: Readonly<Record<string, string>>;
}): Promise<MicrosandboxVm> {
const initialNetworkPolicy = input.setupBaseRuntime ? "allow-all" : input.networkPolicy;
const sandbox = await createMicrosandbox({
@@ -331,6 +338,7 @@ export async function createPreparedMicrosandbox(input: {
name: input.name,
networkPolicy: initialNetworkPolicy,
options: input.options,
+ resourcesPath: input.resourcesPath,
tags: input.tags,
user: input.setupBaseRuntime ? undefined : MICROSANDBOX_USER,
workdir: input.setupBaseRuntime ? "/" : WORKSPACE_ROOT,
@@ -367,7 +375,7 @@ export async function connectMicrosandbox(input: {
readonly module: MicrosandboxModule;
readonly options: ResolvedMicrosandboxOptions;
readonly sessionKey: string;
- readonly tags?: SandboxBackendTags;
+ readonly tags?: Readonly<Record<string, string>>;
}): Promise<MicrosandboxVm | null> {
let handle;
try {
@@ -417,7 +425,7 @@ async function restoreMicrosandboxSessionSnapshot(input: {
readonly module: MicrosandboxModule;
readonly options: ResolvedMicrosandboxOptions;
readonly sessionKey: string;
- readonly tags?: SandboxBackendTags;
+ readonly tags?: Readonly<Record<string, string>>;
}): Promise<MicrosandboxVm | null> {
if (
input.metadata.stateSnapshotName === undefined ||
@@ -458,9 +466,9 @@ async function restoreMicrosandboxSessionSnapshot(input: {
}
const MICROSANDBOX_MISSING_PACKAGE_MESSAGE =
- "The microsandbox sandbox backend requires the `microsandbox` package, which is not bundled " +
+ "The microsandbox sandbox provider requires the `microsandbox` package, which is not bundled " +
"with eve. Install it in your application (for example `pnpm add -D microsandbox`), or use " +
- "docker() / vercel() instead.";
+ "DockerSandbox or VercelSandbox instead.";
/**
* Loads the microsandbox npm package and ensures its VM runtime is
@@ -471,7 +479,7 @@ const MICROSANDBOX_MISSING_PACKAGE_MESSAGE =
* errors instead.
*/
export async function loadMicrosandboxModule(input: {
- readonly appRoot: string;
+ readonly host: SandboxProviderHost;
readonly log?: (message: string) => void;
readonly options: ResolvedMicrosandboxOptions;
}): Promise<MicrosandboxModule> {
@@ -479,8 +487,7 @@ export async function loadMicrosandboxModule(input: {
await assertMicrosandboxPlatformCandidate();
const module = await withProgressHeartbeat("loading microsandbox npm package", input.log, () =>
- loadOptionalEnginePackage<MicrosandboxModule>({
- appRoot: input.appRoot,
+ input.host.loadOptionalPackage<MicrosandboxModule>({
autoInstall: input.options.setup.autoInstall,
importModule: async () => await import("microsandbox"),
missingMessage: MICROSANDBOX_MISSING_PACKAGE_MESSAGE,
@@ -595,14 +602,15 @@ async function createMicrosandbox(input: {
readonly name: string;
readonly networkPolicy?: SandboxNetworkPolicy;
readonly options: ResolvedMicrosandboxOptions;
- readonly tags?: SandboxBackendTags;
+ readonly resourcesPath?: string;
+ readonly tags?: Readonly<Record<string, string>>;
readonly user?: string;
readonly workdir: string;
}): Promise<MicrosandboxSandbox> {
let builder = input.module.Sandbox.builder(input.name)
.cpus(input.options.cpus)
.detached(true)
- .envs(input.options.env)
+ .envs({ ...input.options.env, HOME: MICROSANDBOX_HOME })
.labels(resolveMicrosandboxLabels(input.tags))
.memory(input.options.memoryMiB)
.pullPolicy(input.options.pullPolicy)
@@ -615,6 +623,15 @@ async function createMicrosandbox(input: {
builder = builder.image(input.options.image);
}
+ if (input.options.image.startsWith("127.0.0.1:")) {
+ builder = builder.registry((registry) => registry.insecure());
+ }
+ if (input.resourcesPath !== undefined) {
+ builder = builder.volume("/eve/resources", (mount) =>
+ mount.bind(input.resourcesPath).readonly(),
+ );
+ }
+
if (input.user !== undefined) {
builder = builder.user(input.user);
}
@@ -660,9 +677,11 @@ async function removeSandboxIfExists(
}
}
-function resolveMicrosandboxLabels(tags: SandboxBackendTags | undefined): Record<string, string> {
+function resolveMicrosandboxLabels(
+ tags: Readonly<Record<string, string>> | undefined,
+): Record<string, string> {
return {
- "eve.backend": "microsandbox",
+ "eve.provider": "microsandbox",
...withDevelopmentSandboxTags(tags),
};
}
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-templates.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-templates.ts
index 66d207c25..252f31570 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-templates.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-templates.ts
@@ -3,10 +3,10 @@ import { readdir, rm, stat } from "node:fs/promises";
import { join } from "node:path";
import {
- resolveLocalBackendSessionRootPath,
- resolveLocalBackendTemplateRootPath,
- resolveLocalBackendTemplatesDirectory,
-} from "#execution/sandbox/bindings/local-backend-utils.js";
+ resolveLocalProviderSessionRootPath,
+ resolveLocalProviderTemplateRootPath,
+ resolveLocalProviderTemplatesDirectory,
+} from "#execution/sandbox/bindings/local-provider-utils.js";
import {
LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,
LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT,
@@ -65,7 +65,7 @@ export function resolveMicrosandboxTemplateRootPath(
cacheDirectory: string,
templateKey: string,
): string {
- return resolveLocalBackendTemplateRootPath(
+ return resolveLocalProviderTemplateRootPath(
cacheDirectory,
MICROSANDBOX_CACHE_DIRECTORY_NAME,
templateKey,
@@ -73,14 +73,14 @@ export function resolveMicrosandboxTemplateRootPath(
}
export function resolveMicrosandboxTemplatesDirectory(cacheDirectory: string): string {
- return resolveLocalBackendTemplatesDirectory(cacheDirectory, MICROSANDBOX_CACHE_DIRECTORY_NAME);
+ return resolveLocalProviderTemplatesDirectory(cacheDirectory, MICROSANDBOX_CACHE_DIRECTORY_NAME);
}
export function resolveMicrosandboxSessionRootPath(
cacheDirectory: string,
sessionKey: string,
): string {
- return resolveLocalBackendSessionRootPath(
+ return resolveLocalProviderSessionRootPath(
cacheDirectory,
MICROSANDBOX_CACHE_DIRECTORY_NAME,
sessionKey,
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox.scenario.test.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox.scenario.test.ts
index 0964b83fc..d4820af56 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox.scenario.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox.scenario.test.ts
@@ -6,10 +6,11 @@ import { describe, expect, it } from "vitest";
import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";
import {
- createMicrosandboxSandboxBackend,
+ createMicrosandboxSandboxProvider,
pruneMicrosandboxTemplates,
} from "#execution/sandbox/bindings/microsandbox.js";
import { isMicrosandboxPlatformSupported } from "#execution/sandbox/bindings/microsandbox-platform.js";
+import { createSandboxProviderHarness } from "#internal/testing/sandbox-provider-harness.js";
// Microsandbox is unsupported on Windows (native bindings ship for
// macOS Apple Silicon and glibc Linux only), so every suite in this
@@ -24,9 +25,13 @@ const runMicrosandboxVmScenarios =
const createScratchDirectory = useTemporaryDirectories();
+function createProvider() {
+ return createSandboxProviderHarness(createMicrosandboxSandboxProvider(), undefined);
+}
+
async function createTemporaryCacheDirectory(label: string): Promise<string> {
- // The backend derives its cache directory from
- // `runtimeContext.appRoot` via `resolveSandboxCacheDirectory`, so the
+ // The provider derives its cache directory from
+ // `appRoot` via `resolveSandboxCacheDirectory`, so the
// helper returns a temporary appRoot rather than a cache directory
// directly.
return await createScratchDirectory(`eve-microsandbox-${label}-`);
@@ -34,19 +39,16 @@ async function createTemporaryCacheDirectory(label: string): Promise<string> {
async function createPrewarmedHandle(input: {
readonly appRoot: string;
- readonly sessionKey: string;
- readonly templateKey: string;
+ readonly sandboxName: string;
}) {
- const backend = createMicrosandboxSandboxBackend();
- await backend.prewarm({
- runtimeContext: { appRoot: input.appRoot },
+ const provider = createProvider();
+ await provider.prepare({
+ appRoot: input.appRoot,
seedFiles: [],
- templateKey: input.templateKey,
});
- return await backend.create({
- runtimeContext: { appRoot: input.appRoot },
- sessionKey: input.sessionKey,
- templateKey: input.templateKey,
+ return await provider.openSession({
+ appRoot: input.appRoot,
+ sandboxName: input.sandboxName,
});
}
@@ -68,16 +70,54 @@ async function collectStream(stream: ReadableStream<Uint8Array>): Promise<string
}
describe.runIf(runMicrosandboxVmScenarios)("microsandbox sandbox file API", () => {
+ it("prewarms from a colocated Dockerfile", async () => {
+ const appRoot = await createTemporaryCacheDirectory("dockerfile");
+ const agentRoot = join(appRoot, "agent");
+ const sandboxRoot = join(agentRoot, "sandbox");
+ await mkdir(sandboxRoot, { recursive: true });
+ await writeFile(
+ join(sandboxRoot, "Dockerfile"),
+ [
+ "FROM ubuntu:24.04",
+ "RUN apt-get update && apt-get install -y bash sudo",
+ "RUN printf dockerfile-ready > /dockerfile-marker",
+ "",
+ ].join("\n"),
+ );
+ const resourcesPath = join(appRoot, "compiled-resources");
+ await mkdir(join(resourcesPath, "workspace"), { recursive: true });
+ await writeFile(join(resourcesPath, "workspace", "seed.txt"), "immutable seed");
+ const provider = createProvider();
+ await provider.prepare({
+ resourcesPath,
+ appRoot,
+ seedFiles: [],
+ });
+ const handle = await provider.openSession({
+ appRoot,
+ sandboxName: "session-dockerfile",
+ });
+
+ const result = await handle.sandbox.run({
+ command: [
+ "cat /dockerfile-marker",
+ "cat /workspace/seed.txt",
+ "! sh -c 'printf bad > /eve/resources/workspace/seed.txt' 2>/dev/null",
+ "printf changed > /workspace/seed.txt",
+ ].join(" && "),
+ });
+ expect(result).toMatchObject({ exitCode: 0, stdout: "dockerfile-readyimmutable seed" });
+ });
+
it("writes a file via the public session and reads it back", async () => {
const appRoot = await createTemporaryCacheDirectory("file-api");
const handle = await createPrewarmedHandle({
appRoot,
- sessionKey: "session-write-read",
- templateKey: "tpl-write-read",
+ sandboxName: "session-write-read",
});
- await handle.session.writeTextFile({ content: "hello world", path: "note.txt" });
- const content = await handle.session.readTextFile({ path: "note.txt" });
+ await handle.sandbox.writeTextFile({ content: "hello world", path: "note.txt" });
+ const content = await handle.sandbox.readTextFile({ path: "note.txt" });
expect(content).toBe("hello world");
});
@@ -86,11 +126,10 @@ describe.runIf(runMicrosandboxVmScenarios)("microsandbox sandbox file API", () =
const appRoot = await createTemporaryCacheDirectory("run-env");
const handle = await createPrewarmedHandle({
appRoot,
- sessionKey: "session-run-env",
- templateKey: "tpl-run-env",
+ sandboxName: "session-run-env",
});
- const result = await handle.session.run({
+ const result = await handle.sandbox.run({
command: 'echo "$DEPLOY_ENV"',
env: { DEPLOY_ENV: "staging" },
});
@@ -103,11 +142,10 @@ describe.runIf(runMicrosandboxVmScenarios)("microsandbox sandbox file API", () =
const appRoot = await createTemporaryCacheDirectory("spawn-env");
const handle = await createPrewarmedHandle({
appRoot,
- sessionKey: "session-spawn-env",
- templateKey: "tpl-spawn-env",
+ sandboxName: "session-spawn-env",
});
- const spawned = await handle.session.spawn({
+ const spawned = await handle.sandbox.spawn({
command: 'echo "$DEPLOY_ENV"',
env: { DEPLOY_ENV: "production" },
});
@@ -122,22 +160,20 @@ describe.runIf(runMicrosandboxVmScenarios)("microsandbox sandbox file API", () =
const appRoot = await createTemporaryCacheDirectory("network-policy");
const handle = await createPrewarmedHandle({
appRoot,
- sessionKey: "session-network-policy",
- templateKey: "tpl-network-policy",
+ sandboxName: "session-network-policy",
});
- await expect(handle.session.setNetworkPolicy("deny-all")).resolves.toBeUndefined();
+ await expect(handle.sandbox.setNetworkPolicy("deny-all")).resolves.toBeUndefined();
});
it("readFile returns null for a missing file", async () => {
const appRoot = await createTemporaryCacheDirectory("file-api");
const handle = await createPrewarmedHandle({
appRoot,
- sessionKey: "session-missing",
- templateKey: "tpl-missing",
+ sandboxName: "session-missing",
});
- const content = await handle.session.readTextFile({ path: "does-not-exist.txt" });
+ const content = await handle.sandbox.readTextFile({ path: "does-not-exist.txt" });
expect(content).toBeNull();
});
@@ -146,64 +182,57 @@ describe.runIf(runMicrosandboxVmScenarios)("microsandbox sandbox file API", () =
const appRoot = await createTemporaryCacheDirectory("file-api");
const handle = await createPrewarmedHandle({
appRoot,
- sessionKey: "session-remove",
- templateKey: "tpl-remove",
+ sandboxName: "session-remove",
});
- await handle.session.writeTextFile({
+ await handle.sandbox.writeTextFile({
content: "dynamic skill",
path: "skills/tenant/SKILL.md",
});
- await handle.session.writeTextFile({
+ await handle.sandbox.writeTextFile({
content: "policy",
path: "skills/tenant/references/policy.md",
});
- await handle.session.removePath({ force: true, path: "skills/tenant", recursive: true });
+ await handle.sandbox.removePath({ force: true, path: "skills/tenant", recursive: true });
await expect(
- handle.session.readTextFile({ path: "skills/tenant/SKILL.md" }),
+ handle.sandbox.readTextFile({ path: "skills/tenant/SKILL.md" }),
).resolves.toBeNull();
await expect(
- handle.session.readTextFile({ path: "skills/tenant/references/policy.md" }),
+ handle.sandbox.readTextFile({ path: "skills/tenant/references/policy.md" }),
).resolves.toBeNull();
});
it("preserves files across capture and reconnect", async () => {
const appRoot = await createTemporaryCacheDirectory("file-api");
- const backend = createMicrosandboxSandboxBackend();
+ const provider = createProvider();
- await backend.prewarm({
- runtimeContext: { appRoot },
+ await provider.prepare({
+ appRoot,
seedFiles: [],
- templateKey: "tpl-reconnect",
});
- const firstHandle = await backend.create({
- runtimeContext: { appRoot },
- sessionKey: "session-reconnect",
- templateKey: "tpl-reconnect",
+ const { handle: firstHandle, state } = await provider.start({
+ appRoot,
+ sandboxName: "session-reconnect",
});
- await firstHandle.session.writeTextFile({
+ await firstHandle.sandbox.writeTextFile({
content: "survives reconnect",
path: "persisted.txt",
});
- const state = await firstHandle.captureState();
-
- expect(state.backendName).toBe("microsandbox");
- expect(state.metadata).toMatchObject({
+ expect(state).toMatchObject({
optionsHash: expect.any(String),
sandboxName: expect.any(String),
version: 2,
});
- const reconnectedHandle = await backend.create({
- existingMetadata: state.metadata,
- runtimeContext: { appRoot },
- sessionKey: "session-reconnect",
- templateKey: "tpl-reconnect",
+ const reconnectedHandle = await provider.openSession({
+ existing: state,
+ appRoot,
+ sandboxName: "session-reconnect",
});
- const content = await reconnectedHandle.session.readTextFile({ path: "persisted.txt" });
+ const content = await reconnectedHandle.sandbox.readTextFile({ path: "persisted.txt" });
expect(content).toBe("survives reconnect");
});
@@ -212,45 +241,40 @@ describe.runIf(runMicrosandboxVmScenarios)("microsandbox sandbox file API", () =
const appRoot = await createTemporaryCacheDirectory("file-api");
const handle = await createPrewarmedHandle({
appRoot,
- sessionKey: "session-buffer",
- templateKey: "tpl-buffer",
+ sandboxName: "session-buffer",
});
// A PNG header plus a handful of non-UTF-8 bytes. Reading this
// back as UTF-8 text would throw, so the roundtrip check uses the
// `wc -c` command to confirm the on-disk byte length matches.
const bytes = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0xff, 0x00]);
- await handle.session.writeBinaryFile({ content: bytes, path: "assets/fixture.bin" });
+ await handle.sandbox.writeBinaryFile({ content: bytes, path: "assets/fixture.bin" });
- const result = await handle.session.run({ command: "wc -c < assets/fixture.bin" });
+ const result = await handle.sandbox.run({ command: "wc -c < assets/fixture.bin" });
expect(result.exitCode).toBe(0);
expect(Number(result.stdout.trim())).toBe(bytes.length);
});
it("reports a fresh build on first prewarm and a reuse on the second", async () => {
const appRoot = await createTemporaryCacheDirectory("reuse-report");
- const backend = createMicrosandboxSandboxBackend();
+ const provider = createProvider();
- const first = await backend.prewarm({
- runtimeContext: { appRoot },
+ const first = await provider.prepare({
+ appRoot,
seedFiles: [{ content: "# Weather skill\n", path: "/workspace/skills/weather.md" }],
- templateKey: "tpl-reuse-report",
});
- const second = await backend.prewarm({
- runtimeContext: { appRoot },
+ const second = await provider.prepare({
+ appRoot,
seedFiles: [{ content: "# Weather skill\n", path: "/workspace/skills/weather.md" }],
- templateKey: "tpl-reuse-report",
});
- expect(first).toEqual({ reused: false });
- expect(second).toEqual({ reused: true });
- const handle = await backend.create({
- runtimeContext: { appRoot },
- sessionKey: "session-reuse-report",
- templateKey: "tpl-reuse-report",
+ expect(second).toEqual(first);
+ const handle = await provider.openSession({
+ appRoot,
+ sandboxName: "session-reuse-report",
});
await expect(
- handle.session.readTextFile({ path: "/workspace/skills/weather.md" }),
+ handle.sandbox.readTextFile({ path: "/workspace/skills/weather.md" }),
).resolves.toBe("# Weather skill\n");
});
});
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox.test.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox.test.ts
index 211a9c2e7..36e81e752 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox.test.ts
@@ -1,6 +1,5 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { createMicrosandboxSandboxBackend } from "#execution/sandbox/bindings/microsandbox.js";
import {
createMicrosandboxNetworkPlan,
createTransformBrokerEnvironment,
@@ -23,15 +22,11 @@ vi.mock("#execution/sandbox/bindings/microsandbox-lifecycle.js", () => lifecycle
// glibc Linux only; keep every microsandbox suite off Windows.
const onWindows = process.platform === "win32";
-describe.skipIf(onWindows)("createMicrosandboxSandboxBackend", () => {
+describe.skipIf(onWindows)("microsandbox provider", () => {
beforeEach(() => {
vi.clearAllMocks();
});
- it("exposes the stable backend name without loading microsandbox", () => {
- expect(createMicrosandboxSandboxBackend().name).toBe("microsandbox");
- });
-
it("defaults to eve's published sandbox runtime image", () => {
expect(MICROSANDBOX_DEFAULT_IMAGE).toBe(DEFAULT_EVE_SANDBOX_IMAGE);
expect(resolveMicrosandboxOptions(undefined).image).toBe(MICROSANDBOX_DEFAULT_IMAGE);
@@ -45,32 +40,6 @@ describe.skipIf(onWindows)("createMicrosandboxSandboxBackend", () => {
expect(base.setup.autoInstall).toBe(true);
expect(noInstall.setup.autoInstall).toBe(false);
});
-
- it("adds version-skew guidance to database failures during prewarm", async () => {
- const cause = Object.assign(
- new Error("Migration file of version 'm20260606_000001_named_volume_kinds' is missing"),
- { code: "database" },
- );
- lifecycleMocks.prewarmMicrosandboxTemplate.mockRejectedValueOnce(cause);
-
- const prewarm = createMicrosandboxSandboxBackend().prewarm?.({
- runtimeContext: { appRoot: "/tmp/eve-app" },
- seedFiles: [],
- templateKey: "template-key",
- });
-
- await expect(prewarm).rejects.toMatchObject({
- cause,
- message: expect.stringContaining(
- 'Failed to prewarm microsandbox template "template-key" [database]: ' +
- "Migration file of version 'm20260606_000001_named_volume_kinds' is missing.",
- ),
- // The per-code remediation travels as a structured hint, not prose.
- hint:
- "Check that the microsandbox npm package and installed VM runtime use the same version. " +
- "If versions changed, use a clean MSB_HOME or migrate the existing database.",
- });
- });
});
describe.skipIf(onWindows)("createMicrosandboxNetworkPlan", () => {
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox.ts
index 6b6cf54d1..65eeffa35 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox.ts
@@ -1,85 +1,158 @@
+import type { MutableNetworkSandboxSession } from "#shared/sandbox-session.js";
+import { enrichMicrosandboxError } from "#execution/sandbox/bindings/microsandbox-create.js";
import {
createMicrosandboxHandle,
+ type MicrosandboxPreparedArtifact,
prewarmMicrosandboxTemplate,
} from "#execution/sandbox/bindings/microsandbox-lifecycle.js";
-import { enrichMicrosandboxError } from "#execution/sandbox/bindings/microsandbox-create.js";
import {
microsandboxOptionsForHash,
resolveMicrosandboxOptions,
} from "#execution/sandbox/bindings/microsandbox-options.js";
import { createStableHash } from "#execution/sandbox/bindings/microsandbox-runtime.js";
+import { materializeSandboxDockerfile } from "#execution/sandbox/dockerfile.js";
+import { createSandboxProviderIdentity } from "#execution/sandbox/provider-identity.js";
import type {
- SandboxBackend,
- SandboxBackendCreateInput,
- SandboxBackendHandle,
- SandboxBackendPrewarmInput,
- SandboxBackendPrewarmResult,
-} from "#public/definitions/sandbox-backend.js";
-import type {
- MicrosandboxBootstrapUseOptions,
MicrosandboxSandboxCreateOptions,
- MicrosandboxSessionUseOptions,
+ MicrosandboxSandboxRuntimeOptions,
} from "#public/sandbox/microsandbox-sandbox.js";
+import {
+ isSandboxPreparedArtifactRecord,
+ sandboxProviderResourceIdentity,
+ type SandboxPreparedArtifact,
+ type SandboxProviderImplementation,
+} from "#shared/sandbox-provider.js";
export { pruneMicrosandboxTemplates } from "#execution/sandbox/bindings/microsandbox-templates.js";
-/**
- * Stable backend name. Participates in template/session key derivation
- * and persisted reconnect state.
- */
-export const MICROSANDBOX_BACKEND_NAME = "microsandbox";
+export const MICROSANDBOX_PROVIDER_NAME = "microsandbox";
-/**
- * Construction input for {@link createMicrosandboxSandboxBackend}.
- * Internal — the public surface is the `microsandbox()` factory
- * under `eve/sandbox`.
- */
-export interface CreateMicrosandboxSandboxBackendInput {
- readonly createOptions?: MicrosandboxSandboxCreateOptions;
-}
+export type MicrosandboxProviderSessionState = {
+ readonly optionsHash: string;
+ readonly sessionIdentity: string;
+ readonly version: 3;
+};
-/**
- * Creates the microsandbox sandbox backend: lightweight local VMs with
- * snapshot-backed templates, running each command as the
- * `vercel-sandbox` user for parity with hosted Vercel Sandbox.
- */
-export function createMicrosandboxSandboxBackend(
- input: CreateMicrosandboxSandboxBackendInput = {},
-): SandboxBackend<MicrosandboxBootstrapUseOptions, MicrosandboxSessionUseOptions> {
- const options = resolveMicrosandboxOptions(input.createOptions);
+export function createMicrosandboxSandboxProvider(
+ authoredOptions: MicrosandboxSandboxCreateOptions | undefined = undefined,
+): SandboxProviderImplementation<
+ MicrosandboxSandboxRuntimeOptions,
+ MicrosandboxPreparedArtifact,
+ MicrosandboxProviderSessionState,
+ MutableNetworkSandboxSession
+> {
+ const createOptions = authoredOptions ?? {};
+ const options = resolveMicrosandboxOptions(createOptions);
const optionsHash = createStableHash(JSON.stringify(microsandboxOptionsForHash(options))).slice(
0,
20,
);
return {
- name: MICROSANDBOX_BACKEND_NAME,
- async prewarm(
- prewarmInput: SandboxBackendPrewarmInput<MicrosandboxBootstrapUseOptions>,
- ): Promise<SandboxBackendPrewarmResult> {
+ async prepare(context) {
+ const dockerfile = await materializeSandboxDockerfile({
+ files: context.files,
+ storagePath: context.storagePath,
+ });
+ const templateKey = createSandboxProviderIdentity({
+ dockerfile: dockerfile?.contentHash,
+ optionsHash,
+ resources: sandboxProviderResourceIdentity(context.resources),
+ sourceRevision: context.sourceRevision,
+ version: 2,
+ }).slice(0, 24);
try {
return await prewarmMicrosandboxTemplate({
- backendName: MICROSANDBOX_BACKEND_NAME,
+ context,
+ dockerfile,
options,
optionsHash,
- prewarmInput,
+ prepare: createOptions.prepare,
+ providerName: MICROSANDBOX_PROVIDER_NAME,
+ templateKey,
});
} catch (error) {
- throw enrichMicrosandboxError({
- context: `Failed to prewarm microsandbox template "${prewarmInput.templateKey}"`,
- error,
- });
+ throw enrichMicrosandboxError({ context: "Failed to prepare microsandbox", error });
+ }
+ },
+ async resume(context, artifactValue, stateValue) {
+ const artifact = requireArtifact(artifactValue);
+ const state = requireState(stateValue);
+ if (
+ state.optionsHash !== optionsHash ||
+ artifact.optionsHash !== optionsHash ||
+ state.sessionIdentity !==
+ microsandboxSessionIdentity(context.session.id, artifact, optionsHash)
+ ) {
+ throw new Error("microsandbox session state is incompatible with this environment.");
}
+ const result = await createMicrosandboxHandle({
+ artifact,
+ context,
+ createIfMissing: false,
+ sessionIdentity: state.sessionIdentity,
+ options,
+ optionsHash,
+ providerName: MICROSANDBOX_PROVIDER_NAME,
+ });
+ return result.handle;
},
- async create(
- createInput: SandboxBackendCreateInput,
- ): Promise<SandboxBackendHandle<MicrosandboxSessionUseOptions>> {
- return await createMicrosandboxHandle({
- backendName: MICROSANDBOX_BACKEND_NAME,
- createInput,
+ async start(context, runtimeOptions, artifactValue) {
+ const artifact = requireArtifact(artifactValue);
+ const result = await createMicrosandboxHandle({
+ artifact,
+ context,
options,
optionsHash,
+ providerName: MICROSANDBOX_PROVIDER_NAME,
+ runtimeOptions,
});
+ return result;
},
};
}
+
+function microsandboxSessionIdentity(
+ sessionId: string,
+ artifact: MicrosandboxPreparedArtifact,
+ optionsHash: string,
+): string {
+ const identity = createStableHash(`${sessionId}:${artifact.snapshotName}:${optionsHash}`).slice(
+ 0,
+ 32,
+ );
+ return identity;
+}
+
+function requireArtifact(artifact: SandboxPreparedArtifact): MicrosandboxPreparedArtifact {
+ if (
+ !isSandboxPreparedArtifactRecord(artifact) ||
+ artifact.version !== 2 ||
+ typeof artifact.optionsHash !== "string" ||
+ typeof artifact.snapshotName !== "string"
+ ) {
+ throw new Error("Invalid prepared microsandbox artifact.");
+ }
+ return {
+ image: typeof artifact.image === "string" ? artifact.image : null,
+ optionsHash: artifact.optionsHash,
+ snapshotName: artifact.snapshotName,
+ version: 2,
+ };
+}
+
+function requireState(state: unknown): MicrosandboxProviderSessionState {
+ if (
+ !isSandboxPreparedArtifactRecord(state) ||
+ state.version !== 3 ||
+ typeof state.optionsHash !== "string" ||
+ typeof state.sessionIdentity !== "string"
+ ) {
+ throw new Error("Invalid microsandbox session state.");
+ }
+ return {
+ optionsHash: state.optionsHash,
+ sessionIdentity: state.sessionIdentity,
+ version: 3,
+ };
+}
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 d2c912a27..dff63f8d7 100644
--- a/packages/eve/src/execution/sandbox/bindings/vercel-base-runtime.ts
+++ b/packages/eve/src/execution/sandbox/bindings/vercel-base-runtime.ts
@@ -10,7 +10,7 @@ import type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";
* Prepares a fresh Vercel sandbox for use by the framework.
*/
export async function ensureVercelSandboxBaseRuntime(sandbox: VercelSandbox): Promise<void> {
- await runSandboxBootstrapStep(sandbox, {
+ await runSandboxInitializationStep(sandbox, {
failureMessage: "Failed to initialize Vercel sandbox base runtime.",
script: buildDockerBaseSetupScript(),
});
@@ -39,16 +39,16 @@ export function createVercelNetworkPolicySetter(
};
}
-async function runSandboxBootstrapStep(
+async function runSandboxInitializationStep(
sandbox: VercelSandbox,
input: { readonly failureMessage: string; readonly script: string },
): Promise<void> {
- const result = await runBootstrapCommand(sandbox, input.script);
+ const result = await runInitializationCommand(sandbox, input.script);
if (result === null) {
return;
}
- const sudoResult = await runBootstrapCommandWithSudo(sandbox, input.script);
+ const sudoResult = await runInitializationCommandWithSudo(sandbox, input.script);
if (sudoResult === null) {
return;
}
@@ -57,8 +57,11 @@ async function runSandboxBootstrapStep(
throw new Error(`${input.failureMessage}${output ? `\n${output}` : ""}`);
}
-async function runBootstrapCommand(sandbox: VercelSandbox, script: string): Promise<string | null> {
- return await readBootstrapFailure(
+async function runInitializationCommand(
+ sandbox: VercelSandbox,
+ script: string,
+): Promise<string | null> {
+ return await readInitializationFailure(
await sandbox.runCommand({
args: ["-lc", script],
cmd: "bash",
@@ -66,11 +69,11 @@ async function runBootstrapCommand(sandbox: VercelSandbox, script: string): Prom
);
}
-async function runBootstrapCommandWithSudo(
+async function runInitializationCommandWithSudo(
sandbox: VercelSandbox,
script: string,
): Promise<string | null> {
- return await readBootstrapFailure(
+ return await readInitializationFailure(
await sandbox.runCommand({
args: ["-n", "bash", "-lc", script],
cmd: "sudo",
@@ -78,7 +81,7 @@ async function runBootstrapCommandWithSudo(
);
}
-async function readBootstrapFailure(
+async function readInitializationFailure(
result: Awaited<ReturnType<VercelSandbox["runCommand"]>>,
): Promise<string | null> {
if (result.exitCode === 0) {
diff --git a/packages/eve/src/execution/sandbox/bindings/vercel-credentials.ts b/packages/eve/src/execution/sandbox/bindings/vercel-credentials.ts
index cc6fd5c40..176128f52 100644
--- a/packages/eve/src/execution/sandbox/bindings/vercel-credentials.ts
+++ b/packages/eve/src/execution/sandbox/bindings/vercel-credentials.ts
@@ -4,8 +4,8 @@ import { withPackageUserAgent } from "#internal/user-agent.js";
import type { VercelCreateOptions } from "#execution/sandbox/bindings/vercel-sdk-types.js";
export function getVercelSandboxFetch(createOptions: VercelCreateOptions): typeof globalThis.fetch {
- const fetchOverride = (createOptions as { readonly fetch?: typeof globalThis.fetch }).fetch;
- return withPackageUserAgent(fetchOverride);
+ const fetchOverride = Reflect.get(createOptions, "fetch");
+ return withPackageUserAgent(typeof fetchOverride === "function" ? fetchOverride : undefined);
}
export async function getVercelSandboxCredentials(
@@ -35,7 +35,7 @@ export async function getVercelSandboxCredentials(
}
function readNonEmptyString(object: object, key: string): string | undefined {
- const value = (object as Record<string, unknown>)[key];
+ const value = Reflect.get(object, key);
return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
}
diff --git a/packages/eve/src/execution/sandbox/bindings/vercel-errors.ts b/packages/eve/src/execution/sandbox/bindings/vercel-errors.ts
index 14cc7f7e0..c12ae8609 100644
--- a/packages/eve/src/execution/sandbox/bindings/vercel-errors.ts
+++ b/packages/eve/src/execution/sandbox/bindings/vercel-errors.ts
@@ -1,37 +1,37 @@
export function isVercelSnapshotUnavailableError(error: unknown): boolean {
- for (const candidate of walkErrorChain(error)) {
- const status =
- (candidate as { response?: { status?: number } }).response?.status ??
- (candidate as { status?: number }).status ??
- (candidate as { statusCode?: number }).statusCode;
- if (status === 410) {
- return true;
- }
- }
-
- return false;
+ return errorChainContainsStatus(error, 410);
}
export function isVercelSandboxMissingError(error: unknown): boolean {
+ return errorChainContainsStatus(error, 404);
+}
+
+function errorChainContainsStatus(error: unknown, expectedStatus: number): boolean {
for (const candidate of walkErrorChain(error)) {
- const status =
- (candidate as { response?: { status?: number } }).response?.status ??
- (candidate as { status?: number }).status ??
- (candidate as { statusCode?: number }).statusCode;
- if (status === 404) {
- return true;
- }
+ if (readErrorStatus(candidate) === expectedStatus) return true;
}
-
return false;
}
+function readErrorStatus(value: unknown): number | undefined {
+ if (!isRecord(value)) return undefined;
+ if (typeof value.status === "number") return value.status;
+ if (typeof value.statusCode === "number") return value.statusCode;
+ return isRecord(value.response) && typeof value.response.status === "number"
+ ? value.response.status
+ : undefined;
+}
+
function* walkErrorChain(error: unknown): Generator<unknown> {
let current = error;
const seen = new Set<unknown>();
while (current !== undefined && current !== null && !seen.has(current)) {
seen.add(current);
yield current;
- current = (current as { cause?: unknown }).cause;
+ current = isRecord(current) ? current.cause : undefined;
}
}
+
+function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
+ return typeof value === "object" && value !== null;
+}
diff --git a/packages/eve/src/execution/sandbox/bindings/vercel-lifecycle.ts b/packages/eve/src/execution/sandbox/bindings/vercel-lifecycle.ts
index a3a7d90b2..6cbb4de14 100644
--- a/packages/eve/src/execution/sandbox/bindings/vercel-lifecycle.ts
+++ b/packages/eve/src/execution/sandbox/bindings/vercel-lifecycle.ts
@@ -5,15 +5,14 @@ import {
} from "#execution/sandbox/bindings/vercel-credentials.js";
import type {
VercelCreateOptions,
- VercelGetOptions,
VercelModule,
VercelSandbox,
} from "#execution/sandbox/bindings/vercel-sdk-types.js";
export async function deleteVercelSandbox(input: {
readonly createOptions: VercelCreateOptions;
+ readonly loadDeleteSandboxModule: () => Promise<VercelModule>;
readonly sandbox: VercelSandbox;
- readonly sandboxModule: VercelModule;
readonly signal?: AbortSignal;
}): Promise<void> {
await stopVercelSandbox(input.sandbox);
@@ -22,26 +21,27 @@ export async function deleteVercelSandbox(input: {
export async function deleteUnusableVercelSandbox(input: {
readonly createOptions: VercelCreateOptions;
+ readonly loadDeleteSandboxModule: () => Promise<VercelModule>;
readonly sandbox: VercelSandbox;
- readonly sandboxModule: VercelModule;
}): Promise<void> {
await deleteVercelSandboxRecord(input);
}
async function deleteVercelSandboxRecord(input: {
readonly createOptions: VercelCreateOptions;
+ readonly loadDeleteSandboxModule: () => Promise<VercelModule>;
readonly sandbox: VercelSandbox;
- readonly sandboxModule: VercelModule;
readonly signal?: AbortSignal;
}): Promise<void> {
const credentials = await resolveVercelSandboxCredentials(input.createOptions);
- const sandbox = await input.sandboxModule.Sandbox.get({
+ const sandboxModule = await input.loadDeleteSandboxModule();
+ const sandbox = await sandboxModule.Sandbox.get({
...credentials,
fetch: getVercelSandboxFetch(input.createOptions),
name: input.sandbox.name,
resume: false,
signal: input.signal,
- } as VercelGetOptions);
+ });
await sandbox.delete({
deleteOrphanSnapshots: true,
signal: input.signal,
diff --git a/packages/eve/src/execution/sandbox/bindings/vercel-lookup.ts b/packages/eve/src/execution/sandbox/bindings/vercel-lookup.ts
index 98fbf8a09..893ee7e91 100644
--- a/packages/eve/src/execution/sandbox/bindings/vercel-lookup.ts
+++ b/packages/eve/src/execution/sandbox/bindings/vercel-lookup.ts
@@ -2,6 +2,8 @@ import {
getVercelSandboxCredentials,
getVercelSandboxFetch,
} from "#execution/sandbox/bindings/vercel-credentials.js";
+import { isVercelSandboxMissingError } from "#execution/sandbox/bindings/vercel-errors.js";
+import { errorMessage } from "#execution/sandbox/bindings/vercel-options.js";
import type {
VercelCreateOptions,
VercelGetOptions,
@@ -17,7 +19,7 @@ export async function getNamedVercelSandbox(input: {
try {
return await input.sandboxModule.Sandbox.get(await getVercelSandboxGetOptions(input));
} catch (error) {
- if (isSandboxMissingError(error)) {
+ if (isVercelSandboxMissingError(error)) {
return null;
}
@@ -46,38 +48,8 @@ async function getVercelSandboxGetOptions(input: {
...baseOptions,
...credentials,
signal: input.createOptions.signal,
- } as VercelGetOptions;
+ };
} catch {
return baseOptions;
}
}
-
-function isSandboxMissingError(error: unknown): boolean {
- if (!(error instanceof Error)) {
- return false;
- }
-
- const status =
- (error as { response?: { status?: number } }).response?.status ??
- (error as { cause?: { response?: { status?: number } } }).cause?.response?.status;
-
- return status === 404;
-}
-
-function errorMessage(error: unknown): string {
- if (error instanceof Error) {
- const responseJson = (error as { readonly json?: unknown }).json;
- const responseText = (error as { readonly text?: unknown }).text;
- const responseBody =
- typeof responseText === "string" && responseText.length > 0
- ? responseText
- : responseJson !== undefined
- ? JSON.stringify(responseJson)
- : undefined;
- if (responseBody !== undefined) {
- return `${error.message}: ${responseBody}`;
- }
- return error.message;
- }
- return String(error);
-}
diff --git a/packages/eve/src/execution/sandbox/bindings/vercel-options.ts b/packages/eve/src/execution/sandbox/bindings/vercel-options.ts
index 9f57fd9b0..80f5d97c7 100644
--- a/packages/eve/src/execution/sandbox/bindings/vercel-options.ts
+++ b/packages/eve/src/execution/sandbox/bindings/vercel-options.ts
@@ -1,16 +1,15 @@
import type { VercelCreateOptions } from "#execution/sandbox/bindings/vercel-sdk-types.js";
-import type { SandboxBackendTags } from "#public/definitions/sandbox-backend.js";
const VERCEL_SANDBOX_TAG_LIMIT = 5;
export function resolveVercelSandboxTags(
userTags: VercelCreateOptions["tags"],
- eveTags: SandboxBackendTags | undefined,
+ eveTags: Readonly<Record<string, string>> | undefined,
): Record<string, string> | undefined {
const tags: Record<string, string> = {};
if (userTags !== undefined) {
- for (const [key, value] of Object.entries(userTags as Record<string, string>)) {
+ for (const [key, value] of Object.entries(userTags)) {
tags[key] = value;
}
}
@@ -27,7 +26,7 @@ export function resolveVercelSandboxTags(
if (count > VERCEL_SANDBOX_TAG_LIMIT) {
throw new Error(
`Vercel Sandbox supports at most ${VERCEL_SANDBOX_TAG_LIMIT} tags. ` +
- 'eve reserves "agent", "channel", and "sessionId"; remove or consolidate custom tags passed to vercel().',
+ 'eve reserves "agent", "channel", and "sessionId"; remove or consolidate custom tags.',
);
}
@@ -58,8 +57,8 @@ function areVercelSandboxTagsEqual(
export function errorMessage(error: unknown): string {
if (error instanceof Error) {
- const responseJson = (error as { readonly json?: unknown }).json;
- const responseText = (error as { readonly text?: unknown }).text;
+ const responseJson = Reflect.get(error, "json");
+ const responseText = Reflect.get(error, "text");
const responseBody =
typeof responseText === "string" && responseText.length > 0
? responseText
diff --git a/packages/eve/src/execution/sandbox/bindings/vercel.test.ts b/packages/eve/src/execution/sandbox/bindings/vercel.test.ts
index c08a0f88d..e71d0f133 100644
--- a/packages/eve/src/execution/sandbox/bindings/vercel.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/vercel.test.ts
@@ -2,10 +2,10 @@ import { Readable } from "node:stream";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { SandboxTemplateNotProvisionedError } from "#public/definitions/sandbox-backend.js";
-import { vercel } from "#public/sandbox/backends/vercel.js";
+import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";
import { VERCEL_EVE_SANDBOX_IMAGE } from "#execution/sandbox/bindings/eve-image.js";
-import { createVercelSandbox } from "#execution/sandbox/bindings/vercel.js";
+import { createVercelSandbox as createVercelImplementation } from "#execution/sandbox/bindings/vercel.js";
+import { createSandboxProviderHarness } from "#internal/testing/sandbox-provider-harness.js";
// The credential fallback consults the developer's Vercel CLI auth and the
// repo's `.vercel` project link; on a linked, logged-in machine it would
@@ -95,7 +95,11 @@ function createMockSandbox(input: {
};
}
-function createTestVercelSandbox(input: Parameters<typeof createVercelSandbox>[0] = {}) {
+function createVercelSandbox(input: Parameters<typeof createVercelImplementation>[0] = {}) {
+ return createSandboxProviderHarness(createVercelImplementation(input), {});
+}
+
+function createTestVercelSandbox(input: Parameters<typeof createVercelImplementation>[0] = {}) {
return createVercelSandbox({
...input,
createSandbox: async ({ createOptions, sandboxModule }) =>
@@ -112,19 +116,17 @@ async function createTestVercelSession() {
get: vi.fn().mockResolvedValue(null),
},
};
- const backend = createTestVercelSandbox({
+ const provider = createTestVercelSandbox({
loadSandboxModule: async () => sandboxModule as never,
});
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
+ await provider.prepare({
+ appRoot: "/tmp/test-app-root",
seedFiles: [],
- templateKey: "template-key",
});
- const handle = await backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: "template-key",
+ const handle = await provider.openSession({
+ appRoot: "/tmp/test-app-root",
+ sandboxName: "session-key",
});
return { handle, sessionSandbox };
@@ -155,51 +157,70 @@ afterEach(() => {
});
describe("createVercelSandbox", () => {
- it("creates fresh Vercel sandboxes with eve's shared base image", async () => {
- const templateSandbox = createMockSandbox({ name: "template-key" });
- const fetch = vi.fn();
+ it("creates a session from the prepared snapshot artifact without looking up the template sandbox", async () => {
+ const sessionSandbox = createMockSandbox({ name: "session-key" });
const sandboxModule = {
Sandbox: {
- create: vi.fn().mockResolvedValueOnce(templateSandbox),
- get: vi.fn().mockResolvedValueOnce(null),
+ create: vi.fn().mockResolvedValue(sessionSandbox),
+ get: vi.fn().mockResolvedValue(null),
},
};
-
- const backend = createVercelSandbox({
- createOptions: {
- fetch,
- networkPolicy: "deny-all",
- ports: [3000],
- projectId: "prj_123",
- teamId: "team_123",
- timeout: 123_000,
- token: "vercel-token",
- } as never,
+ const provider = createTestVercelSandbox({
loadSandboxModule: async () => sandboxModule as never,
});
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- seedFiles: [],
- templateKey: "template-key",
+ await provider.openSession({
+ appRoot: "/tmp/test-app-root",
+ prepared: { snapshotId: "prepared-snapshot" },
+ sandboxName: "session-key",
});
- expect(fetch).not.toHaveBeenCalled();
- expect(sandboxModule.Sandbox.create).toHaveBeenCalledTimes(1);
+ expect(sandboxModule.Sandbox.get).toHaveBeenCalledTimes(1);
+ expect(sandboxModule.Sandbox.get).toHaveBeenCalledWith(
+ expect.objectContaining({ name: expect.stringMatching(/^eve-sbx-vercel-/u) }),
+ );
expect(sandboxModule.Sandbox.create).toHaveBeenCalledWith(
expect.objectContaining({
- image: VERCEL_EVE_SANDBOX_IMAGE,
- name: "template-key",
- networkPolicy: "allow-all",
- persistent: true,
- ports: [3000],
- projectId: "prj_123",
- teamId: "team_123",
- timeout: 123_000,
- token: "vercel-token",
+ name: expect.stringMatching(/^eve-sbx-vercel-/u),
+ source: { snapshotId: "prepared-snapshot", type: "snapshot" },
}),
);
- expect(templateSandbox.update).toHaveBeenCalledWith({ networkPolicy: "deny-all" });
+ });
+
+ it("reuses template identity until authored source or resources change", async () => {
+ async function prepareName(input: {
+ createOptions?: NonNullable<Parameters<typeof createVercelImplementation>[0]>["createOptions"];
+ resourcesKey?: string;
+ sourceRevision: string;
+ }) {
+ const create = vi.fn(async (options: { name: string }) =>
+ createMockSandbox({ name: options.name }),
+ );
+ const provider = createTestVercelSandbox({
+ createOptions: input.createOptions,
+ loadSandboxModule: async () =>
+ ({ Sandbox: { create, get: vi.fn().mockResolvedValue(null) } }) as never,
+ });
+ await provider.prepare({ appRoot: "/tmp/test-app-root", ...input });
+ return create.mock.calls[0]?.[0].name;
+ }
+
+ const first = await prepareName({ sourceRevision: "revision-a" });
+ const unchanged = await prepareName({ sourceRevision: "revision-a" });
+ const changedSource = await prepareName({ sourceRevision: "revision-b" });
+ const changedResources = await prepareName({
+ resourcesKey: "resources-b",
+ sourceRevision: "revision-a",
+ });
+ const explicitImage = await prepareName({
+ createOptions: { image: "registry.example/eve:custom" },
+ sourceRevision: "revision-a",
+ });
+
+ expect(unchanged).toBe(first);
+ expect(changedSource).not.toBe(first);
+ expect(changedResources).not.toBe(first);
+ expect(explicitImage).not.toBe(first);
});
it("uses an author-supplied image for fresh Vercel sandboxes", async () => {
@@ -211,15 +232,14 @@ describe("createVercelSandbox", () => {
},
};
- const backend = createVercelSandbox({
+ const provider = createVercelSandbox({
createOptions: { image: "registry.example/eve-python:1.0.0" } as never,
loadSandboxModule: async () => sandboxModule as never,
});
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
+ await provider.prepare({
+ appRoot: "/tmp/test-app-root",
seedFiles: [],
- templateKey: "template-key",
});
expect(sandboxModule.Sandbox.create).toHaveBeenCalledWith(
@@ -236,15 +256,14 @@ describe("createVercelSandbox", () => {
},
};
- const backend = createVercelSandbox({
+ const provider = createVercelSandbox({
createOptions: { __experimentalFlag: "enabled" } as never,
loadSandboxModule: async () => sandboxModule as never,
});
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
+ await provider.prepare({
+ appRoot: "/tmp/test-app-root",
seedFiles: [],
- templateKey: "template-key",
});
expect(sandboxModule.Sandbox.create).toHaveBeenCalledWith(
@@ -255,53 +274,7 @@ describe("createVercelSandbox", () => {
);
});
- it("passes resolved credentials to Vercel sandbox lookups instead of inferring scope", async () => {
- const existingTemplate = createMockSandbox({
- name: "template-key",
- snapshotId: "template-snapshot",
- });
- const sandboxModule = {
- Sandbox: {
- create: vi.fn(),
- get: vi.fn().mockImplementation(async (options: { token?: string }) => {
- if (options.token !== "vercel-token") {
- throw new Error('[{"path":["teams",1,"updatedAt"],"message":"Required"}]');
- }
- return existingTemplate;
- }),
- },
- };
-
- const backend = createTestVercelSandbox({
- createOptions: {
- projectId: "prj_123",
- teamId: "team_123",
- token: "vercel-token",
- } as never,
- loadSandboxModule: async () => sandboxModule as never,
- });
-
- await expect(
- backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- seedFiles: [],
- templateKey: "template-key",
- }),
- ).resolves.toEqual({ reused: true });
-
- expect(sandboxModule.Sandbox.get).toHaveBeenCalledWith(
- expect.objectContaining({
- name: "template-key",
- projectId: "prj_123",
- resume: false,
- teamId: "team_123",
- token: "vercel-token",
- }),
- );
- expect(sandboxModule.Sandbox.create).not.toHaveBeenCalled();
- });
-
- it("includes Vercel SDK error response bodies in backend errors", async () => {
+ it("includes Vercel SDK error response bodies in provider errors", async () => {
const sandboxModule = {
Sandbox: {
create: vi.fn(),
@@ -318,15 +291,14 @@ describe("createVercelSandbox", () => {
},
};
- const backend = createTestVercelSandbox({
+ const provider = createTestVercelSandbox({
loadSandboxModule: async () => sandboxModule as never,
});
await expect(
- backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
+ provider.prepare({
+ appRoot: "/tmp/test-app-root",
seedFiles: [],
- templateKey: "template-key",
}),
).rejects.toThrow(/The sandbox request is invalid/);
});
@@ -338,7 +310,7 @@ describe("createVercelSandbox", () => {
stdout: vi.fn().mockResolvedValue("/workspace/repository/agent/instructions.md\n"),
});
- await handle.session.writeTextFile({
+ await handle.sandbox.writeTextFile({
content: "updated instructions\n",
path: "/source/instructions.md",
});
@@ -384,12 +356,12 @@ describe("createVercelSandbox", () => {
},
};
- const backend = createTestVercelSandbox({
+ const provider = createTestVercelSandbox({
loadSandboxModule: async () => sandboxModule as never,
});
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
+ await provider.prepare({
+ appRoot: "/tmp/test-app-root",
seedFiles: [
{
content: "skill body",
@@ -404,19 +376,16 @@ describe("createVercelSandbox", () => {
path: "$HOME/.agents/skills/research/SKILL.md",
},
],
- templateKey: "template-key",
});
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
+ await provider.prepare({
+ appRoot: "/tmp/test-app-root",
seedFiles: [],
- templateKey: "template-key",
});
- await backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: "template-key",
+ await provider.openSession({
+ appRoot: "/tmp/test-app-root",
+ sandboxName: "session-key",
});
expect(templateSandbox.writeFiles).toHaveBeenCalledTimes(1);
@@ -432,137 +401,6 @@ describe("createVercelSandbox", () => {
expect(files?.[2]?.content).toEqual(Buffer.from("model skill body"));
});
- it("writes seed files before bootstrap and snapshots bootstrap outputs", async () => {
- const templateSandbox = createMockSandbox({ name: "template" });
- const sandboxModule = {
- Sandbox: {
- create: vi.fn().mockResolvedValueOnce(templateSandbox),
- get: vi.fn().mockResolvedValueOnce(null),
- },
- };
- const backend = createTestVercelSandbox({
- loadSandboxModule: async () => sandboxModule as never,
- });
-
- await backend.prewarm({
- bootstrap: async ({ use }) => {
- const sandbox = await use();
- await expect(sandbox.readTextFile({ path: "/workspace/seed.txt" })).resolves.toBe(
- "authored seed",
- );
- await sandbox.writeTextFile({
- content: "bootstrap output",
- path: "/workspace/bootstrap.txt",
- });
- },
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- seedFiles: [
- { content: "authored seed", path: "/workspace/seed.txt" },
- { content: "second seed", path: "/workspace/second.txt" },
- ],
- templateKey: "template-key",
- });
-
- const writes = vi.mocked(templateSandbox.writeFiles);
- expect(writes).toHaveBeenCalledTimes(2);
- expect(writes.mock.calls[0]?.[0].map((file) => file.path)).toEqual([
- "/workspace/seed.txt",
- "/workspace/second.txt",
- ]);
- expect(writes.mock.calls[1]?.[0].map((file) => file.path)).toEqual([
- "/workspace/bootstrap.txt",
- ]);
- expect(writes.mock.invocationCallOrder[1]).toBeLessThan(
- vi.mocked(templateSandbox.snapshot).mock.invocationCallOrder[0]!,
- );
- });
-
- it("reports a fresh build when no framework snapshot exists yet", async () => {
- const templateSandbox = createMockSandbox({ name: "template" });
- const sandboxModule = {
- Sandbox: {
- create: vi.fn().mockResolvedValueOnce(templateSandbox),
- get: vi.fn().mockResolvedValue(null),
- },
- };
-
- const backend = createTestVercelSandbox({
- loadSandboxModule: async () => sandboxModule as never,
- });
-
- const result = await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- seedFiles: [],
- templateKey: "template-key",
- });
-
- expect(result).toEqual({ reused: false });
- expect(templateSandbox.snapshot).toHaveBeenCalledTimes(1);
- });
-
- it("recreates a stale stopped Vercel template that has no snapshot", async () => {
- const staleTemplate = createMockSandbox({
- name: "template-key",
- status: "stopped",
- });
- const freshTemplate = createMockSandbox({ name: "template-key" });
- const sandboxModule = {
- Sandbox: {
- create: vi.fn().mockResolvedValueOnce(freshTemplate),
- get: vi.fn().mockResolvedValueOnce(staleTemplate),
- },
- };
-
- const backend = createTestVercelSandbox({
- loadSandboxModule: async () => sandboxModule as never,
- });
-
- const result = await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- seedFiles: [],
- templateKey: "template-key",
- });
-
- expect(result).toEqual({ reused: false });
- expect(staleTemplate.delete).toHaveBeenCalledTimes(1);
- expect(staleTemplate.runCommand).not.toHaveBeenCalled();
- expect(sandboxModule.Sandbox.create).toHaveBeenCalledWith(
- expect.objectContaining({
- name: "template-key",
- persistent: true,
- }),
- );
- expect(freshTemplate.snapshot).toHaveBeenCalledTimes(1);
- });
-
- it("reports a reuse when an existing template already carries a framework snapshot", async () => {
- const existingTemplate = createMockSandbox({
- name: "template-key",
- snapshotId: "framework-snapshot",
- });
- const sandboxModule = {
- Sandbox: {
- create: vi.fn(),
- get: vi.fn().mockResolvedValue(existingTemplate),
- },
- };
-
- const backend = createTestVercelSandbox({
- loadSandboxModule: async () => sandboxModule as never,
- });
-
- const result = await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- seedFiles: [],
- templateKey: "template-key",
- });
-
- expect(result).toEqual({ reused: true });
- // Reuse must not re-snapshot or re-create the template sandbox.
- expect(existingTemplate.snapshot).not.toHaveBeenCalled();
- expect(sandboxModule.Sandbox.create).not.toHaveBeenCalled();
- });
-
it("removes paths through the sandbox filesystem API", async () => {
const templateSandbox = createMockSandbox({ name: "template" });
const sessionSandbox = createMockSandbox({ name: "session" });
@@ -576,23 +414,21 @@ describe("createVercelSandbox", () => {
},
};
- const backend = createTestVercelSandbox({
+ const provider = createTestVercelSandbox({
loadSandboxModule: async () => sandboxModule as never,
});
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
+ await provider.prepare({
+ appRoot: "/tmp/test-app-root",
seedFiles: [],
- templateKey: "template-key",
});
- const handle = await backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: "template-key",
+ const handle = await provider.openSession({
+ appRoot: "/tmp/test-app-root",
+ sandboxName: "session-key",
});
vi.mocked(sessionSandbox.runCommand).mockClear();
- await handle.session.removePath({ force: true, path: "skills/tenant", recursive: true });
+ await handle.sandbox.removePath({ force: true, path: "skills/tenant", recursive: true });
expect(sessionSandbox.fs.rm).toHaveBeenCalledWith("/workspace/skills/tenant", {
force: true,
@@ -616,20 +452,18 @@ describe("createVercelSandbox", () => {
},
};
- const backend = createTestVercelSandbox({
+ const provider = createTestVercelSandbox({
loadSandboxModule: async () => sandboxModule as never,
});
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
+ await provider.prepare({
+ appRoot: "/tmp/test-app-root",
seedFiles: [],
- templateKey: "template-key",
});
- await backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: "template-key",
+ await provider.openSession({
+ appRoot: "/tmp/test-app-root",
+ sandboxName: "session-key",
});
expect(create).toHaveBeenCalledTimes(2);
@@ -638,638 +472,120 @@ describe("createVercelSandbox", () => {
expect(sessionArgs?.[0]).toMatchObject({ timeout: 30 * 60 * 1_000 });
});
- it("applies framework defaults to Sandbox.create when no createOptions are supplied", async () => {
- const templateSandbox = createMockSandbox({ name: "template" });
- const sessionSandbox = createMockSandbox({ name: "session" });
- const create = vi
- .fn()
- .mockResolvedValueOnce(templateSandbox)
- .mockResolvedValueOnce(sessionSandbox);
- const sandboxModule = {
- Sandbox: {
- create,
- get: vi.fn().mockResolvedValue(null),
- },
- };
-
- const backend = createTestVercelSandbox({
- loadSandboxModule: async () => sandboxModule as never,
- });
-
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- seedFiles: [],
- templateKey: "template-key",
- });
-
- await backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: "template-key",
- });
-
- expect(create).toHaveBeenCalledTimes(2);
- const [templateArgs, sessionArgs] = create.mock.calls;
- expect(templateArgs?.[0]).toMatchObject({
- name: "template-key",
- persistent: true,
- timeout: 30 * 60 * 1_000,
- });
- expect(sessionArgs?.[0]).toMatchObject({
- name: "session-key",
- persistent: true,
- timeout: 30 * 60 * 1_000,
- source: { snapshotId: "template-snapshot", type: "snapshot" },
- });
- });
-
- it("creates a fresh session without reading or snapshotting a template when templateKey is null", async () => {
- const sessionSandbox = createMockSandbox({ name: "session" });
- const create = vi.fn().mockResolvedValueOnce(sessionSandbox);
- const get = vi.fn().mockResolvedValue(null);
- const sandboxModule = {
- Sandbox: {
- create,
- get,
- },
- };
-
- const backend = createTestVercelSandbox({
- loadSandboxModule: async () => sandboxModule as never,
- });
-
- await backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: null,
- });
-
- expect(get).toHaveBeenCalledTimes(1);
- expect(get).toHaveBeenCalledWith({
- fetch: expect.any(Function),
- name: "session-key",
- resume: false,
- });
- expect(create).toHaveBeenCalledTimes(1);
- expect(create.mock.calls[0]?.[0]).toMatchObject({
- name: "session-key",
- persistent: true,
- timeout: 30 * 60 * 1_000,
- });
- expect(create.mock.calls[0]?.[0]).not.toHaveProperty("source");
- expect(sessionSandbox.snapshot).not.toHaveBeenCalled();
- });
-
- it("keeps author createOptions on template-less fresh sessions", async () => {
- const sessionSandbox = createMockSandbox({ name: "session" });
- const create = vi.fn().mockResolvedValueOnce(sessionSandbox);
- const sandboxModule = {
- Sandbox: {
- create,
- get: vi.fn().mockResolvedValue(null),
- },
- };
-
- const backend = createTestVercelSandbox({
- createOptions: {
- ports: [3000],
- source: { snapshotId: "author-snap", type: "snapshot" },
- },
- loadSandboxModule: async () => sandboxModule as never,
- });
-
- await backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: null,
- });
-
- expect(create.mock.calls[0]?.[0]).toMatchObject({
- name: "session-key",
- persistent: true,
- ports: [3000],
- source: { snapshotId: "author-snap", type: "snapshot" },
- });
- expect(sessionSandbox.snapshot).not.toHaveBeenCalled();
- });
-
- it("forwards factory createOptions to both template and session Sandbox.create", async () => {
- const templateSandbox = createMockSandbox({ name: "template" });
- const sessionSandbox = createMockSandbox({ name: "session" });
- const create = vi
- .fn()
- .mockResolvedValueOnce(templateSandbox)
- .mockResolvedValueOnce(sessionSandbox);
- const sandboxModule = {
- Sandbox: {
- create,
- get: vi.fn().mockResolvedValue(null),
- },
- };
-
- const backend = createTestVercelSandbox({
- createOptions: {
- networkPolicy: "deny-all",
- ports: [3000, 4000],
- resources: { vcpus: 2 },
- timeout: 600_000,
- },
- loadSandboxModule: async () => sandboxModule as never,
- });
-
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- seedFiles: [],
- templateKey: "template-key",
- });
-
- await backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: "template-key",
- });
-
- expect(create).toHaveBeenCalledTimes(2);
- const [templateArgs, sessionArgs] = create.mock.calls;
- expect(templateArgs?.[0]).toMatchObject({
- name: "template-key",
- networkPolicy: "allow-all",
- persistent: true,
- ports: [3000, 4000],
- resources: { vcpus: 2 },
- timeout: 600_000,
- });
- expect(sessionArgs?.[0]).toMatchObject({
- name: "session-key",
- networkPolicy: "deny-all",
- persistent: true,
- ports: [3000, 4000],
- resources: { vcpus: 2 },
- source: { snapshotId: "template-snapshot", type: "snapshot" },
- timeout: 600_000,
- });
- expect(templateSandbox.update).toHaveBeenCalledWith({ networkPolicy: "deny-all" });
- });
-
- it("resolves mounts only for a fresh live session sandbox", async () => {
- const templateSandbox = createMockSandbox({ name: "template" });
- const sessionSandbox = createMockSandbox({ name: "session" });
- const create = vi
- .fn()
- .mockResolvedValueOnce(templateSandbox)
- .mockResolvedValueOnce(sessionSandbox);
- const resolveSessionCreateOptions = vi.fn(({ session }) => ({
- mounts: {
- "/workspace/repos": { drive: `e0-${session.id}`, mode: "read-write" as const },
- },
- }));
- const backend = createTestVercelSandbox({
- loadSandboxModule: async () =>
- ({ Sandbox: { create, get: vi.fn().mockResolvedValue(null) } }) as never,
- resolveSessionCreateOptions,
- });
-
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- seedFiles: [],
- templateKey: "template-key",
- });
- await backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- tags: { sessionId: "parent-session" },
- templateKey: "template-key",
- });
-
- expect(resolveSessionCreateOptions).toHaveBeenCalledWith({
- session: { id: "parent-session" },
- });
- expect(create.mock.calls[0]?.[0]).not.toHaveProperty("mounts");
- expect(create.mock.calls[1]?.[0]).toMatchObject({
- mounts: { "/workspace/repos": { drive: "e0-parent-session", mode: "read-write" } },
- });
- });
-
- it("does not resolve session create options when resuming a sandbox", async () => {
- const existing = createMockSandbox({ name: "session-key" });
- const create = vi.fn();
- const resolveSessionCreateOptions = vi.fn();
- const backend = createTestVercelSandbox({
- loadSandboxModule: async () =>
- ({ Sandbox: { create, get: vi.fn().mockResolvedValue(existing) } }) as never,
- resolveSessionCreateOptions,
- });
-
- await backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: null,
- });
-
- expect(resolveSessionCreateOptions).not.toHaveBeenCalled();
- expect(create).not.toHaveBeenCalled();
- });
-
- it("forwards author source to template create as the base layer", async () => {
- /*
- * The real Vercel SDK pre-populates `currentSnapshotId` on a
- * freshly-created sandbox when the create call passed a snapshot
- * source. The template sandbox mock mirrors that — if eve's
- * "template already has a snapshot, reuse it" guard fires on a
- * newly-created template, it returns the author's snapshotId
- * instead of running bootstrap/seed/`sandbox.snapshot()`, so the
- * session would derive directly from the author snapshot and the
- * framework's setup would never run. That's the regression this
- * test pins.
- */
- const templateSandbox = createMockSandbox({
- name: "template",
- snapshotId: "author-snap",
- });
- const sessionSandbox = createMockSandbox({ name: "session" });
- const create = vi
- .fn()
- .mockResolvedValueOnce(templateSandbox)
- .mockResolvedValueOnce(sessionSandbox);
- const sandboxModule = {
- Sandbox: {
- create,
- get: vi.fn().mockResolvedValue(null),
- },
- };
-
- const backend = createTestVercelSandbox({
- createOptions: { source: { snapshotId: "author-snap", type: "snapshot" } },
- loadSandboxModule: async () => sandboxModule as never,
- });
-
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- seedFiles: [],
- templateKey: "template-key",
- });
-
- await backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: "template-key",
- });
-
- expect(create).toHaveBeenCalledTimes(2);
- const [templateArgs, sessionArgs] = create.mock.calls;
- expect(templateArgs?.[0]).toMatchObject({
- source: { snapshotId: "author-snap", type: "snapshot" },
- });
- expect(templateSandbox.snapshot).toHaveBeenCalledTimes(1);
- expect(sessionArgs?.[0]).toMatchObject({
- source: { snapshotId: "template-snapshot", type: "snapshot" },
- });
- });
-
- it("re-runs prewarm when an existing template still carries the author snapshot as its currentSnapshotId", async () => {
- /*
- * A previous prewarm that crashed (or just never reached
- * `sandbox.snapshot()`) leaves a named template sandbox in the
- * project whose `currentSnapshotId` is still the author's source
- * snapshot. Without explicit handling, `getNamedSandbox` would
- * find it and eve would treat the author's snapshot as the
- * framework's prewarmed snapshot, skipping setup/bootstrap/seeds
- * forever. This test pins that we ignore that exact value and
- * proceed with prewarm on the existing sandbox.
- */
- const existingTemplate = createMockSandbox({
- name: "template-key",
- snapshotId: "author-snap",
- });
- const sessionSandbox = createMockSandbox({ name: "session-key" });
- const create = vi.fn().mockResolvedValueOnce(sessionSandbox);
- const get = vi.fn().mockImplementation(async ({ name }: { name: string }) => {
- if (name === "template-key") return existingTemplate;
- if (name === "session-key") return null;
- return null;
- });
- const sandboxModule = { Sandbox: { create, get } };
-
- const backend = createTestVercelSandbox({
- createOptions: { source: { snapshotId: "author-snap", type: "snapshot" } },
- loadSandboxModule: async () => sandboxModule as never,
- });
-
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- seedFiles: [],
- templateKey: "template-key",
- });
-
- await backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: "template-key",
- });
-
- expect(existingTemplate.snapshot).toHaveBeenCalledTimes(1);
- expect(create).toHaveBeenCalledTimes(1);
- expect(create.mock.calls[0]?.[0]).toMatchObject({
- source: { snapshotId: "template-key-snapshot", type: "snapshot" },
- });
- });
-
- it("invalidates and rebuilds a Vercel template when its snapshot expired before session create", async () => {
- const staleTemplate = createMockSandbox({
- name: "template-key",
- snapshotId: "expired-template-snapshot",
- });
- const freshTemplate = createMockSandbox({ name: "template-key" });
- const sessionSandbox = createMockSandbox({ name: "session-key" });
- let templateDeleted = false;
- vi.mocked(staleTemplate.delete).mockImplementation(async () => {
- templateDeleted = true;
- });
-
- const snapshotExpiredError = Object.assign(
- new Error("Vercel sandbox create API returned 410"),
- {
- json: {
- error: {
- code: "bad_request",
- message: "Resource is gone.",
- },
- },
- response: { status: 410 },
- },
- );
- const create = vi
- .fn()
- .mockRejectedValueOnce(snapshotExpiredError)
- .mockResolvedValueOnce(freshTemplate)
- .mockResolvedValueOnce(sessionSandbox);
- const get = vi.fn().mockImplementation(async ({ name }: { name: string }) => {
- if (name === "template-key") {
- return templateDeleted ? null : staleTemplate;
- }
- if (name === "session-key") {
- return null;
- }
- return null;
- });
- const sandboxModule = { Sandbox: { create, get } };
-
- const backend = createTestVercelSandbox({
- loadSandboxModule: async () => sandboxModule as never,
- });
-
- await expect(
- backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: "template-key",
- }),
- ).rejects.toBeInstanceOf(SandboxTemplateNotProvisionedError);
- expect(staleTemplate.delete).toHaveBeenCalledTimes(1);
-
- const prewarmResult = await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- seedFiles: [],
- templateKey: "template-key",
- });
- await backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: "template-key",
- });
-
- expect(prewarmResult).toEqual({ reused: false });
- expect(freshTemplate.snapshot).toHaveBeenCalledTimes(1);
- expect(create).toHaveBeenCalledTimes(3);
- expect(create.mock.calls[0]?.[0]).toMatchObject({
- name: "session-key",
- source: { snapshotId: "expired-template-snapshot", type: "snapshot" },
- });
- expect(create.mock.calls[1]?.[0]).toMatchObject({
- name: "template-key",
- persistent: true,
- });
- expect(create.mock.calls[2]?.[0]).toMatchObject({
- name: "session-key",
- source: { snapshotId: "template-key-snapshot", type: "snapshot" },
- });
- });
-
- it("does not invalidate the shared template when a fresh session initialization returns 410", async () => {
- const templateSandbox = createMockSandbox({
- name: "template-key",
- snapshotId: "template-snapshot",
- });
- const freshSession = createMockSandbox({ name: "session-key" });
- const snapshotUnavailableError = Object.assign(new Error("Cannot initialize sandbox"), {
- response: { status: 410 },
- });
- vi.mocked(freshSession.runCommand).mockRejectedValueOnce(snapshotUnavailableError);
- const sandboxModule = {
- Sandbox: {
- create: vi.fn().mockResolvedValueOnce(freshSession),
- get: vi.fn().mockImplementation(async ({ name }: { name: string }) => {
- if (name === "template-key") return templateSandbox;
- return null;
- }),
- },
- };
- const backend = createTestVercelSandbox({
- loadSandboxModule: async () => sandboxModule as never,
- });
-
- await expect(
- backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: "template-key",
- }),
- ).rejects.toThrow('Failed to initialize sandbox session "session-key"');
-
- expect(templateSandbox.delete).not.toHaveBeenCalled();
- });
-
- it("does not invalidate the shared template for an ambiguous session-create 404", async () => {
- const templateSandbox = createMockSandbox({
- name: "template-key",
- snapshotId: "template-snapshot",
- });
- const imageNotFoundError = Object.assign(new Error("Image not found"), {
- response: { status: 404 },
- });
- const sandboxModule = {
- Sandbox: {
- create: vi.fn().mockRejectedValueOnce(imageNotFoundError),
- get: vi.fn().mockImplementation(async ({ name }: { name: string }) => {
- if (name === "template-key") return templateSandbox;
- return null;
- }),
- },
- };
- const backend = createTestVercelSandbox({
- loadSandboxModule: async () => sandboxModule as never,
- });
-
- await expect(
- backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: "template-key",
- }),
- ).rejects.toThrow('Failed to create sandbox session "session-key": Image not found');
-
- expect(templateSandbox.delete).not.toHaveBeenCalled();
- });
-
- it("rebuilds a Vercel template when the named sandbox disappears during prewarm", async () => {
- const staleTemplate = createMockSandbox({ name: "template-key" });
- const freshTemplate = createMockSandbox({ name: "template-key" });
- const missingTemplateError = Object.assign(new Error("Status code 404 is not ok"), {
- response: { status: 404 },
- });
- vi.mocked(staleTemplate.snapshot).mockRejectedValueOnce(missingTemplateError);
-
- const create = vi
- .fn()
- .mockResolvedValueOnce(staleTemplate)
- .mockResolvedValueOnce(freshTemplate);
- const sandboxModule = {
- Sandbox: {
- create,
- get: vi.fn().mockResolvedValue(null),
- },
- };
- const log = vi.fn();
-
- const backend = createTestVercelSandbox({
- loadSandboxModule: async () => sandboxModule as never,
+ it("applies mounts passed directly to open", async () => {
+ const sessionSandbox = createMockSandbox({ name: "session" });
+ const create = vi.fn().mockResolvedValue(sessionSandbox);
+ const provider = createSandboxProviderHarness(
+ createVercelImplementation({
+ loadSandboxModule: async () =>
+ ({ Sandbox: { create, get: vi.fn().mockResolvedValue(null) } }) as never,
+ }),
+ { mounts: { "/workspace/repos": { drive: "team-drive", mode: "read-write" } } },
+ );
+ await provider.openSession({
+ appRoot: "/tmp/test-app-root",
+ sandboxName: "session-key",
});
-
- await expect(
- backend.prewarm({
- log,
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- seedFiles: [],
- templateKey: "template-key",
+ expect(create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ mounts: { "/workspace/repos": { drive: "team-drive", mode: "read-write" } },
}),
- ).resolves.toEqual({ reused: false });
-
- expect(create).toHaveBeenCalledTimes(2);
- expect(staleTemplate.snapshot).toHaveBeenCalledTimes(1);
- expect(freshTemplate.snapshot).toHaveBeenCalledTimes(1);
- expect(log).toHaveBeenCalledWith("cached template disappeared; rebuilding sandbox template");
+ );
});
- it("resumes a stopped session sandbox via Sandbox.get instead of creating a new one", async () => {
+ it("forwards author source to template create as the base layer", async () => {
+ /*
+ * The real Vercel SDK pre-populates `currentSnapshotId` on a
+ * freshly-created sandbox when the create call passed a snapshot
+ * source. The template sandbox mock mirrors that — if eve's
+ * "template already has a snapshot, reuse it" guard fires on a
+ * newly-created template, it returns the author's snapshotId
+ * instead of running preparation/resource hydration/`sandbox.snapshot()`, so the
+ * session would derive directly from the author snapshot and the
+ * framework's setup would never run. That's the regression this
+ * test pins.
+ */
const templateSandbox = createMockSandbox({
- name: "template-key",
- snapshotId: "template-snapshot",
+ name: "template",
+ snapshotId: "author-snap",
});
- const sessionSandbox = createMockSandbox({ name: "persisted-sandbox-name" });
+ const sessionSandbox = createMockSandbox({ name: "session" });
+ const create = vi
+ .fn()
+ .mockResolvedValueOnce(templateSandbox)
+ .mockResolvedValueOnce(sessionSandbox);
const sandboxModule = {
Sandbox: {
- create: vi.fn(),
- get: vi.fn().mockImplementation(async ({ name }: { name: string }) => {
- if (name === "template-key") return templateSandbox;
- if (name === "persisted-sandbox-name") return sessionSandbox;
- return null;
- }),
+ create,
+ get: vi.fn().mockResolvedValue(null),
},
};
- const backend = createTestVercelSandbox({
+ const provider = createTestVercelSandbox({
+ createOptions: { source: { snapshotId: "author-snap", type: "snapshot" } },
loadSandboxModule: async () => sandboxModule as never,
});
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
+ await provider.prepare({
+ appRoot: "/tmp/test-app-root",
seedFiles: [],
- templateKey: "template-key",
});
- const handle = await backend.create({
- existingMetadata: { sandboxName: "persisted-sandbox-name" },
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: "template-key",
+ await provider.openSession({
+ appRoot: "/tmp/test-app-root",
+ sandboxName: "session-key",
});
- expect(sandboxModule.Sandbox.create).not.toHaveBeenCalled();
- expect(sandboxModule.Sandbox.get).toHaveBeenCalledWith({
- fetch: expect.any(Function),
- name: "persisted-sandbox-name",
- resume: false,
+ expect(create).toHaveBeenCalledTimes(2);
+ const [templateArgs, sessionArgs] = create.mock.calls;
+ expect(templateArgs?.[0]).toMatchObject({
+ source: { snapshotId: "author-snap", type: "snapshot" },
});
- expect(sessionSandbox.runCommand).toHaveBeenCalledTimes(1);
- expect(sessionSandbox.runCommand).toHaveBeenCalledWith({
- args: ["-lc", expect.stringContaining("ln -s /proc/self/fd /dev/fd")],
- cmd: "bash",
+ expect(templateSandbox.snapshot).toHaveBeenCalledTimes(1);
+ expect(sessionArgs?.[0]).toMatchObject({
+ source: { snapshotId: "template-snapshot", type: "snapshot" },
});
- expect(handle.session).toBeDefined();
-
- const state = await handle.captureState();
- expect(state.metadata).toEqual({ sandboxName: "persisted-sandbox-name" });
});
- it("replaces a persisted session whose snapshot is unavailable", async () => {
- const templateSandbox = createMockSandbox({
- name: "template-key",
- snapshotId: "template-snapshot",
- });
- const staleSession = createMockSandbox({ name: "persisted-sandbox-name", status: "stopped" });
- const replacementSession = createMockSandbox({ name: "session-key" });
- const snapshotUnavailableError = Object.assign(new Error("Cannot resume sandbox"), {
- response: { status: 410 },
- });
- vi.mocked(staleSession.runCommand).mockRejectedValueOnce(snapshotUnavailableError);
-
+ it("reports an unavailable prepared snapshot without mutating the build template", async () => {
+ const snapshotExpiredError = Object.assign(
+ new Error("Vercel sandbox create API returned 410"),
+ { response: { status: 410 } },
+ );
const sandboxModule = {
Sandbox: {
- create: vi.fn().mockResolvedValueOnce(replacementSession),
- get: vi.fn().mockImplementation(async ({ name }: { name: string }) => {
- if (name === "template-key") return templateSandbox;
- if (name === "persisted-sandbox-name") return staleSession;
- if (name === "session-key") return null;
- return null;
- }),
+ create: vi.fn().mockRejectedValueOnce(snapshotExpiredError),
+ get: vi.fn().mockResolvedValue(null),
},
};
- const backend = createTestVercelSandbox({
+ const provider = createTestVercelSandbox({
loadSandboxModule: async () => sandboxModule as never,
});
- const handle = await backend.create({
- existingMetadata: { sandboxName: "persisted-sandbox-name" },
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: "template-key",
- });
+ await expect(
+ provider.openSession({
+ appRoot: "/tmp/test-app-root",
+ prepared: { snapshotId: "expired-template-snapshot" },
+ sandboxName: "session-key",
+ }),
+ ).rejects.toBeInstanceOf(SandboxTemplateNotProvisionedError);
- expect(sandboxModule.Sandbox.get).toHaveBeenCalledWith({
- fetch: expect.any(Function),
- name: "persisted-sandbox-name",
- resume: false,
- signal: undefined,
- });
- expect(staleSession.delete).toHaveBeenCalledWith({
- deleteOrphanSnapshots: true,
- signal: undefined,
- });
- expect(templateSandbox.delete).not.toHaveBeenCalled();
+ expect(sandboxModule.Sandbox.get).toHaveBeenCalledTimes(1);
+ expect(sandboxModule.Sandbox.get).toHaveBeenCalledWith(
+ expect.objectContaining({ name: expect.stringMatching(/^eve-sbx-vercel-/u) }),
+ );
expect(sandboxModule.Sandbox.create).toHaveBeenCalledWith(
expect.objectContaining({
- name: "session-key",
- persistent: true,
- source: { snapshotId: "template-snapshot", type: "snapshot" },
+ name: expect.stringMatching(/^eve-sbx-vercel-/u),
+ source: { snapshotId: "expired-template-snapshot", type: "snapshot" },
}),
);
- expect((await handle.captureState()).metadata).toEqual({ sandboxName: "session-key" });
});
it("stops the session sandbox on shutdown so no VM outlives the server", async () => {
const { handle, sessionSandbox } = await createTestVercelSession();
- await handle.shutdown();
+ await handle.onRuntimeShutdown();
expect(sessionSandbox.stop).toHaveBeenCalledTimes(1);
});
@@ -1279,8 +595,8 @@ describe("createVercelSandbox", () => {
vi.mocked(sessionSandbox.runCommand).mockResolvedValue(createMockDetachedCommand() as never);
vi.mocked(sessionSandbox.runCommand).mockClear();
- await handle.stop();
- await handle.session.run({ command: "printf resumed" });
+ await handle.onSessionStop();
+ await handle.sandbox.run({ command: "printf resumed" });
expect(sessionSandbox.stop).toHaveBeenCalledTimes(1);
expect(sessionSandbox.runCommand).toHaveBeenCalledWith(
@@ -1298,12 +614,9 @@ describe("createVercelSandbox", () => {
const stableDelete = vi.fn(async () => {
order.push("sandbox-delete");
});
- const get = vi.fn(async ({ name, resume }: { name: string; resume?: boolean }) => {
- if (name === "session" && resume === false) {
- order.push("sandbox-get");
- return { delete: stableDelete };
- }
- return null;
+ const stableGet = vi.fn(async () => {
+ order.push("sandbox-get");
+ return { delete: stableDelete };
});
const sandboxModule = {
Sandbox: {
@@ -1311,28 +624,27 @@ describe("createVercelSandbox", () => {
.fn()
.mockResolvedValueOnce(templateSandbox)
.mockResolvedValueOnce(sessionSandbox),
- get,
+ get: vi.fn().mockResolvedValue(null),
},
};
- const backend = createTestVercelSandbox({
+ const provider = createTestVercelSandbox({
+ loadDeleteSandboxModule: async () => ({ Sandbox: { get: stableGet } }) as never,
loadSandboxModule: async () => sandboxModule as never,
});
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
+ await provider.prepare({
+ appRoot: "/tmp/test-app-root",
seedFiles: [],
- templateKey: "template-key",
});
- const handle = await backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: "template-key",
+ const handle = await provider.openSession({
+ appRoot: "/tmp/test-app-root",
+ sandboxName: "session-key",
});
const abortSignal = new AbortController().signal;
- await expect(handle.delete({ abortSignal })).resolves.toBeUndefined();
+ await expect(handle.onSessionDelete({ abortSignal })).resolves.toBeUndefined();
expect(order).toEqual(["stop", "sandbox-get", "sandbox-delete"]);
- expect(get).toHaveBeenCalledWith({
+ expect(stableGet).toHaveBeenCalledWith({
fetch: expect.any(Function),
name: "session",
resume: false,
@@ -1356,21 +668,19 @@ describe("createVercelSandbox", () => {
get: vi.fn().mockResolvedValue(null),
},
};
- const backend = createTestVercelSandbox({
+ const provider = createTestVercelSandbox({
loadSandboxModule: async () => sandboxModule as never,
});
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
+ await provider.prepare({
+ appRoot: "/tmp/test-app-root",
seedFiles: [],
- templateKey: "template-key",
});
- const handle = await backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: "template-key",
+ const handle = await provider.openSession({
+ appRoot: "/tmp/test-app-root",
+ sandboxName: "session-key",
});
- await handle.shutdown();
+ await handle.onRuntimeShutdown();
expect(sessionSandbox.stop).not.toHaveBeenCalled();
});
@@ -1379,209 +689,55 @@ describe("createVercelSandbox", () => {
const { handle, sessionSandbox } = await createTestVercelSession();
sessionSandbox.stop.mockRejectedValueOnce(new Error("provider unreachable"));
- await expect(handle.stop()).rejects.toThrow("provider unreachable");
+ await expect(handle.onSessionStop()).rejects.toThrow("provider unreachable");
});
- it("falls back to creating a new session when the persisted sandbox no longer exists", async () => {
- const templateSandbox = createMockSandbox({
- name: "template-key",
- snapshotId: "template-snapshot",
- });
- const newSessionSandbox = createMockSandbox({ name: "session-key" });
- const sandboxModule = {
- Sandbox: {
- create: vi.fn().mockResolvedValueOnce(newSessionSandbox),
- get: vi.fn().mockImplementation(async ({ name }: { name: string }) => {
- if (name === "template-key") return templateSandbox;
- throw Object.assign(new Error("Not found"), {
- response: { status: 404 },
- });
- }),
- },
- };
-
- const backend = createTestVercelSandbox({
- loadSandboxModule: async () => sandboxModule as never,
- });
-
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- seedFiles: [],
- templateKey: "template-key",
- });
-
- const handle = await backend.create({
- existingMetadata: { sandboxName: "deleted-sandbox" },
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: "template-key",
- });
-
- expect(sandboxModule.Sandbox.get).toHaveBeenCalledWith({
- fetch: expect.any(Function),
- name: "deleted-sandbox",
- resume: false,
- });
- expect(sandboxModule.Sandbox.create).toHaveBeenCalledTimes(1);
- expect(sandboxModule.Sandbox.create).toHaveBeenCalledWith(
- expect.objectContaining({
- name: "deleted-sandbox",
- persistent: true,
- source: { snapshotId: "template-snapshot", type: "snapshot" },
+ it("applies the open-time policy after template-less base setup", async () => {
+ const sessionSandbox = createMockSandbox({ name: "session" });
+ const create = vi.fn().mockResolvedValue(sessionSandbox);
+ const provider = createSandboxProviderHarness(
+ createVercelImplementation({
+ createSandbox: async ({ createOptions }) => {
+ await create(createOptions);
+ return sessionSandbox as never;
+ },
+ loadSandboxModule: async () =>
+ ({ Sandbox: { create, get: vi.fn().mockResolvedValue(null) } }) as never,
}),
+ { networkPolicy: "deny-all" },
+ { preparedArtifact: () => ({}) },
);
- expect(handle.session).toBeDefined();
- });
-
- it("does not call Sandbox.create on resume and does not re-apply factory createOptions", async () => {
- const templateSandbox = createMockSandbox({
- name: "template-key",
- snapshotId: "template-snapshot",
- });
- const sessionSandbox = createMockSandbox({ name: "session-key" });
- const sandboxModule = {
- Sandbox: {
- create: vi.fn(),
- get: vi.fn().mockImplementation(async ({ name }: { name: string }) => {
- if (name === "template-key") return templateSandbox;
- if (name === "session-key") return sessionSandbox;
- return null;
- }),
- },
- };
-
- const backend = createTestVercelSandbox({
- createOptions: { networkPolicy: "deny-all" },
- loadSandboxModule: async () => sandboxModule as never,
- });
-
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- seedFiles: [],
- templateKey: "template-key",
- });
-
- await backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: "template-key",
- });
-
- expect(sandboxModule.Sandbox.create).not.toHaveBeenCalled();
- // The factory's networkPolicy must NOT leak into a sandbox.update on resume.
- const updateCalls = vi.mocked(sessionSandbox.update).mock.calls;
- for (const call of updateCalls) {
- expect(call[0]).not.toHaveProperty("networkPolicy");
- }
- });
-
- it("adds eve sandbox tags to Vercel template and session creation", async () => {
- const templateSandbox = createMockSandbox({ name: "template" });
- const sessionSandbox = createMockSandbox({ name: "session" });
- const create = vi
- .fn()
- .mockResolvedValueOnce(templateSandbox)
- .mockResolvedValueOnce(sessionSandbox);
- const sandboxModule = {
- Sandbox: {
- create,
- get: vi.fn().mockResolvedValue(null),
- },
- };
-
- const backend = createTestVercelSandbox({
- loadSandboxModule: async () => sandboxModule as never,
- });
-
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- seedFiles: [],
- templateKey: "template-key",
- });
- await backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- tags: {
- agent: "weather-agent",
- channel: "slack",
- sessionId: "session_123",
- },
- templateKey: "template-key",
- });
+ await provider.start({ appRoot: "/tmp/test-app-root", sandboxName: "session-key" });
- expect(create).toHaveBeenCalledTimes(2);
- const [templateArgs, sessionArgs] = create.mock.calls;
- expect(templateArgs?.[0]).toMatchObject({
- name: "template-key",
- persistent: true,
- });
- expect(sessionArgs?.[0]).toMatchObject({
- name: "session-key",
- persistent: true,
- tags: {
- agent: "weather-agent",
- channel: "slack",
- sessionId: "session_123",
- },
- });
+ expect(create).toHaveBeenCalledWith(expect.objectContaining({ networkPolicy: "allow-all" }));
+ expect(sessionSandbox.update).toHaveBeenCalledWith({ networkPolicy: "deny-all" });
+ expect(sessionSandbox.runCommand.mock.invocationCallOrder[0]).toBeLessThan(
+ sessionSandbox.update.mock.invocationCallOrder[0]!,
+ );
});
- it("forwards networkPolicy shapes through useSessionFn to sandbox.update", async () => {
- const templateSandbox = createMockSandbox({ name: "template" });
+ it("discards a fresh template-less session when applying its policy fails", async () => {
const sessionSandbox = createMockSandbox({ name: "session" });
- const sandboxModule = {
- Sandbox: {
- create: vi
- .fn()
- .mockResolvedValueOnce(templateSandbox)
- .mockResolvedValueOnce(sessionSandbox),
- get: vi.fn().mockResolvedValue(null),
- },
- };
-
- const backend = createTestVercelSandbox({
- loadSandboxModule: async () => sandboxModule as never,
- });
-
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- seedFiles: [],
- templateKey: "template-key",
- });
-
- const handle = await backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: "template-key",
- });
-
- await handle.useSessionFn({ networkPolicy: "allow-all" });
- await handle.useSessionFn({ networkPolicy: "deny-all" });
- await handle.useSessionFn({
- networkPolicy: { allow: ["example.com", "*.vercel.app"] },
- });
- await handle.useSessionFn({
- networkPolicy: {
- allow: {
- "api.example.com": [{ transform: [{ headers: { authorization: "Bearer sk-..." } }] }],
- },
- },
- });
+ sessionSandbox.update.mockRejectedValueOnce(new Error("policy rejected"));
+ const stableDelete = vi.fn().mockResolvedValue(undefined);
+ const provider = createSandboxProviderHarness(
+ createVercelImplementation({
+ createSandbox: async () => sessionSandbox as never,
+ loadDeleteSandboxModule: async () =>
+ ({ Sandbox: { get: vi.fn().mockResolvedValue({ delete: stableDelete }) } }) as never,
+ loadSandboxModule: async () =>
+ ({ Sandbox: { get: vi.fn().mockResolvedValue(null) } }) as never,
+ }),
+ { networkPolicy: "deny-all" },
+ { preparedArtifact: () => ({}) },
+ );
- expect(sessionSandbox.update).toHaveBeenCalledTimes(4);
- expect(sessionSandbox.update).toHaveBeenNthCalledWith(1, { networkPolicy: "allow-all" });
- expect(sessionSandbox.update).toHaveBeenNthCalledWith(2, { networkPolicy: "deny-all" });
- expect(sessionSandbox.update).toHaveBeenNthCalledWith(3, {
- networkPolicy: { allow: ["example.com", "*.vercel.app"] },
- });
- expect(sessionSandbox.update).toHaveBeenNthCalledWith(4, {
- networkPolicy: {
- allow: {
- "api.example.com": [{ transform: [{ headers: { authorization: "Bearer sk-..." } }] }],
- },
- },
- });
+ await expect(
+ provider.start({ appRoot: "/tmp/test-app-root", sandboxName: "session-key" }),
+ ).rejects.toThrow("policy rejected");
+ expect(sessionSandbox.stop).toHaveBeenCalledTimes(1);
+ expect(stableDelete).toHaveBeenCalledTimes(1);
});
it("brokers credentials through the session's setNetworkPolicy to sandbox.update", async () => {
@@ -1597,23 +753,21 @@ describe("createVercelSandbox", () => {
},
};
- const backend = createTestVercelSandbox({
+ const provider = createTestVercelSandbox({
loadSandboxModule: async () => sandboxModule as never,
});
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
+ await provider.prepare({
+ appRoot: "/tmp/test-app-root",
seedFiles: [],
- templateKey: "template-key",
});
- const handle = await backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: "template-key",
+ const handle = await provider.openSession({
+ appRoot: "/tmp/test-app-root",
+ sandboxName: "session-key",
});
- await handle.session.setNetworkPolicy({
+ await handle.sandbox.setNetworkPolicy({
allow: {
"github.com": [{ transform: [{ headers: { authorization: "Basic eC1hY2Nlc3M=" } }] }],
"*": [],
@@ -1631,158 +785,6 @@ describe("createVercelSandbox", () => {
});
});
- it("forwards bootstrap use(opts) through sandbox.update on the template sandbox", async () => {
- const templateSandbox = createMockSandbox({ name: "template" });
- const sessionSandbox = createMockSandbox({ name: "session" });
- const sandboxModule = {
- Sandbox: {
- create: vi
- .fn()
- .mockResolvedValueOnce(templateSandbox)
- .mockResolvedValueOnce(sessionSandbox),
- get: vi.fn().mockResolvedValue(null),
- },
- };
-
- const backend = createTestVercelSandbox({
- loadSandboxModule: async () => sandboxModule as never,
- });
-
- await backend.prewarm({
- bootstrap: async ({ use }) => {
- await use({
- networkPolicy: "deny-all",
- ports: [3000, 4000],
- resources: { vcpus: 2 },
- timeout: 600_000,
- });
- },
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- seedFiles: [],
- templateKey: "template-key",
- });
-
- expect(templateSandbox.update).toHaveBeenCalledWith({
- networkPolicy: "deny-all",
- ports: [3000, 4000],
- resources: { vcpus: 2 },
- timeout: 600_000,
- });
- expect(templateSandbox.snapshot).toHaveBeenCalledTimes(1);
- });
-
- it("does not call sandbox.update when bootstrap use() is invoked without options", async () => {
- const templateSandbox = createMockSandbox({ name: "template" });
- const sandboxModule = {
- Sandbox: {
- create: vi.fn().mockResolvedValueOnce(templateSandbox),
- get: vi.fn().mockResolvedValue(null),
- },
- };
-
- const backend = createTestVercelSandbox({
- loadSandboxModule: async () => sandboxModule as never,
- });
-
- await backend.prewarm({
- bootstrap: async ({ use }) => {
- await use();
- },
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- seedFiles: [],
- templateKey: "template-key",
- });
-
- expect(templateSandbox.update).not.toHaveBeenCalled();
- expect(templateSandbox.snapshot).toHaveBeenCalledTimes(1);
- });
-
- it("updates tags when reattaching existing Vercel sandboxes", async () => {
- const templateSandbox = createMockSandbox({
- name: "template-key",
- snapshotId: "template-snapshot",
- tags: { agent: "old-agent" },
- });
- const sessionSandbox = createMockSandbox({
- name: "session-key",
- tags: { agent: "old-agent" },
- });
- const sandboxModule = {
- Sandbox: {
- create: vi.fn(),
- get: vi.fn().mockImplementation(async ({ name }: { name: string }) => {
- if (name === "template-key") {
- return templateSandbox;
- }
- if (name === "session-key") {
- return sessionSandbox;
- }
- return null;
- }),
- },
- };
-
- const backend = createTestVercelSandbox({
- loadSandboxModule: async () => sandboxModule as never,
- });
-
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- seedFiles: [],
- templateKey: "template-key",
- });
-
- await backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- tags: {
- agent: "weather-agent",
- channel: "slack",
- sessionId: "session_123",
- },
- templateKey: "template-key",
- });
-
- expect(sandboxModule.Sandbox.create).not.toHaveBeenCalled();
- expect(sessionSandbox.update).toHaveBeenCalledWith({
- tags: {
- agent: "weather-agent",
- channel: "slack",
- sessionId: "session_123",
- },
- });
- });
-
- it("rejects merged Vercel sandbox tags over the platform limit", async () => {
- const sandboxModule = {
- Sandbox: {
- create: vi.fn(),
- get: vi.fn().mockResolvedValue(null),
- },
- };
-
- const backend = createTestVercelSandbox({
- loadSandboxModule: async () => sandboxModule as never,
- });
-
- await expect(
- backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- tags: {
- agent: "weather-agent",
- channel: "slack",
- env: "test",
- owner: "ai",
- sessionId: "session_123",
- team: "infra",
- },
- templateKey: "template-key",
- }),
- ).rejects.toThrow(/supports at most 5 tags/);
- expect(sandboxModule.Sandbox.create).not.toHaveBeenCalled();
- });
-
it("exposes /workspace-rooted resolved paths through the public session", async () => {
const templateSandbox = createMockSandbox({ name: "template" });
const sessionSandbox = createMockSandbox({ name: "session" });
@@ -1796,26 +798,24 @@ describe("createVercelSandbox", () => {
},
};
- const backend = createTestVercelSandbox({
+ const provider = createTestVercelSandbox({
loadSandboxModule: async () => sandboxModule as never,
});
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
+ await provider.prepare({
+ appRoot: "/tmp/test-app-root",
seedFiles: [],
- templateKey: "template-key",
});
- const handle = await backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: "template-key",
+ const handle = await provider.openSession({
+ appRoot: "/tmp/test-app-root",
+ sandboxName: "session-key",
});
- expect(handle.session.resolvePath("/workspace/python-analysis/run.py")).toBe(
+ expect(handle.sandbox.resolvePath("/workspace/python-analysis/run.py")).toBe(
"/workspace/python-analysis/run.py",
);
- expect(handle.session.resolvePath("python-analysis/run.py")).toBe(
+ expect(handle.sandbox.resolvePath("python-analysis/run.py")).toBe(
"/workspace/python-analysis/run.py",
);
});
@@ -1826,7 +826,7 @@ describe("createVercelSandbox", () => {
Readable.from([Buffer.from("hello "), Buffer.from("sandbox")]),
);
- const stream = await handle.session.readFile({ path: "/workspace/message.txt" });
+ const stream = await handle.sandbox.readFile({ path: "/workspace/message.txt" });
expect(stream).not.toBeNull();
expect(await consumeWebStream(stream!)).toBe("hello sandbox");
@@ -1843,7 +843,7 @@ describe("createVercelSandbox", () => {
});
sessionSandbox.readFile.mockResolvedValueOnce(providerStream);
- const stream = await handle.session.readFile({ path: "/workspace/message.txt" });
+ const stream = await handle.sandbox.readFile({ path: "/workspace/message.txt" });
expect(stream).toBe(providerStream);
expect(await consumeWebStream(stream!)).toBe("web stream");
@@ -1852,7 +852,7 @@ describe("createVercelSandbox", () => {
it("preserves missing Vercel files as null", async () => {
const { handle } = await createTestVercelSession();
- await expect(handle.session.readFile({ path: "/workspace/missing.txt" })).resolves.toBeNull();
+ await expect(handle.sandbox.readFile({ path: "/workspace/missing.txt" })).resolves.toBeNull();
});
it("propagates Vercel file-read errors unchanged", async () => {
@@ -1860,7 +860,7 @@ describe("createVercelSandbox", () => {
const providerError = new Error("provider read failed");
sessionSandbox.readFile.mockRejectedValueOnce(providerError);
- await expect(handle.session.readFile({ path: "/workspace/message.txt" })).rejects.toBe(
+ await expect(handle.sandbox.readFile({ path: "/workspace/message.txt" })).rejects.toBe(
providerError,
);
});
@@ -1869,7 +869,7 @@ describe("createVercelSandbox", () => {
const { handle, sessionSandbox } = await createTestVercelSession();
sessionSandbox.readFile.mockResolvedValueOnce({ readable: true });
- await expect(handle.session.readFile({ path: "/workspace/message.txt" })).rejects.toThrow(
+ await expect(handle.sandbox.readFile({ path: "/workspace/message.txt" })).rejects.toThrow(
"Vercel Sandbox returned an unsupported file stream.",
);
});
@@ -1887,25 +887,23 @@ describe("createVercelSandbox", () => {
},
};
- const backend = createTestVercelSandbox({
+ const provider = createTestVercelSandbox({
loadSandboxModule: async () => sandboxModule as never,
});
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
+ await provider.prepare({
+ appRoot: "/tmp/test-app-root",
seedFiles: [],
- templateKey: "template-key",
});
- const handle = await backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: "template-key",
+ const handle = await provider.openSession({
+ appRoot: "/tmp/test-app-root",
+ sandboxName: "session-key",
});
vi.mocked(sessionSandbox.runCommand).mockResolvedValue(createMockDetachedCommand() as never);
vi.mocked(sessionSandbox.runCommand).mockClear();
- await handle.session.spawn({
+ await handle.sandbox.spawn({
command: "printenv DEPLOY_ENV",
env: { DEPLOY_ENV: "staging" },
});
@@ -1933,25 +931,23 @@ describe("createVercelSandbox", () => {
},
};
- const backend = createTestVercelSandbox({
+ const provider = createTestVercelSandbox({
loadSandboxModule: async () => sandboxModule as never,
});
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
+ await provider.prepare({
+ appRoot: "/tmp/test-app-root",
seedFiles: [],
- templateKey: "template-key",
});
- const handle = await backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: "template-key",
+ const handle = await provider.openSession({
+ appRoot: "/tmp/test-app-root",
+ sandboxName: "session-key",
});
vi.mocked(sessionSandbox.runCommand).mockResolvedValue(createMockDetachedCommand() as never);
vi.mocked(sessionSandbox.runCommand).mockClear();
- await handle.session.run({
+ await handle.sandbox.run({
command: "printenv DEPLOY_ENV",
env: { DEPLOY_ENV: "production" },
});
@@ -1966,9 +962,9 @@ describe("createVercelSandbox", () => {
);
});
- it("exposes a stable backend name", () => {
- const backend = createTestVercelSandbox();
- expect(backend.name).toBe("vercel");
+ it("exposes a stable provider name", () => {
+ const provider = createTestVercelSandbox();
+ expect(provider).toBeDefined();
});
it("prepares the base runtime during sandbox init", async () => {
@@ -1984,20 +980,18 @@ describe("createVercelSandbox", () => {
},
};
- const backend = createTestVercelSandbox({
+ const provider = createTestVercelSandbox({
loadSandboxModule: async () => sandboxModule as never,
});
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
+ await provider.prepare({
+ appRoot: "/tmp/test-app-root",
seedFiles: [],
- templateKey: "template-key",
});
- await backend.create({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
- sessionKey: "session-key",
- templateKey: "template-key",
+ await provider.openSession({
+ appRoot: "/tmp/test-app-root",
+ sandboxName: "session-key",
});
for (const sandbox of [templateSandbox, sessionSandbox]) {
@@ -2044,14 +1038,13 @@ describe("createVercelSandbox", () => {
},
};
- const backend = createTestVercelSandbox({
+ const provider = createTestVercelSandbox({
loadSandboxModule: async () => sandboxModule as never,
});
- await backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
+ await provider.prepare({
+ appRoot: "/tmp/test-app-root",
seedFiles: [],
- templateKey: "template-key",
});
expect(templateSandbox.runCommand).toHaveBeenCalledTimes(2);
@@ -2087,26 +1080,16 @@ describe("createVercelSandbox", () => {
},
};
- const backend = createTestVercelSandbox({
+ const provider = createTestVercelSandbox({
loadSandboxModule: async () => sandboxModule as never,
});
- const prewarm = backend.prewarm({
- runtimeContext: { appRoot: "/tmp/test-app-root" },
+ const prewarm = provider.prepare({
+ appRoot: "/tmp/test-app-root",
seedFiles: [],
- templateKey: "template-key",
});
await expect(prewarm).rejects.toThrow(/Failed to initialize Vercel sandbox base runtime/);
await expect(prewarm).rejects.not.toThrow(/Vercel OIDC can authenticate/);
});
});
-
-describe("vercel (public factory)", () => {
- it("returns a SandboxBackend value with name 'vercel'", () => {
- const backend = vercel();
- expect(backend.name).toBe("vercel");
- expect(typeof backend.create).toBe("function");
- expect(typeof backend.prewarm).toBe("function");
- });
-});
diff --git a/packages/eve/src/execution/sandbox/bindings/vercel.ts b/packages/eve/src/execution/sandbox/bindings/vercel.ts
index 19d7c0fa3..9efdd6105 100644
--- a/packages/eve/src/execution/sandbox/bindings/vercel.ts
+++ b/packages/eve/src/execution/sandbox/bindings/vercel.ts
@@ -1,10 +1,11 @@
+import type { MutableNetworkSandboxSession } from "#shared/sandbox-session.js";
+import { VERCEL_EVE_SANDBOX_IMAGE } from "#execution/sandbox/bindings/eve-image.js";
import {
applyInitialVercelNetworkPolicy,
createVercelNetworkPolicySetter,
ensureVercelSandboxBaseRuntime,
withBaseSetupNetworkPolicy,
} from "#execution/sandbox/bindings/vercel-base-runtime.js";
-import type { SandboxBootstrapContext } from "#public/definitions/sandbox.js";
import type {
InternalSandboxSession,
SandboxProcess,
@@ -14,26 +15,25 @@ import type {
SandboxSpawnOptions,
SandboxWriteFileOptions,
} from "#shared/sandbox-session.js";
+import {
+ isSandboxPreparedArtifactRecord,
+ sandboxProviderResourceIdentity,
+ providerResourceTargetFiles,
+ type SandboxPreparedArtifact,
+ type SandboxProviderHandle,
+ type SandboxProviderImplementation,
+ type SandboxProviderSessionContext,
+} from "#shared/sandbox-provider.js";
+import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";
import type {
- SandboxBackend,
- SandboxBackendCreateInput,
- SandboxBackendHandle,
- SandboxBackendPrewarmInput,
- SandboxBackendPrewarmResult,
- SandboxBackendTags,
- SandboxSeedFile,
-} from "#public/definitions/sandbox-backend.js";
-import { SandboxTemplateNotProvisionedError } from "#public/definitions/sandbox-backend.js";
-import type {
- VercelSandboxBootstrapUseOptions,
- VercelSandboxSessionCreateContext,
- VercelSandboxSessionCreateOptions,
- VercelSandboxSessionUseOptions,
+ VercelSandboxMountOptions,
+ VercelSandboxRuntimeOptions,
} from "#public/sandbox/vercel-sandbox.js";
import { WORKSPACE_ROOT } from "#runtime/workspace/types.js";
import { createLoggingSandboxSession } from "#execution/sandbox/logging-session.js";
import { adaptMultiplexedCommandToSandboxProcess } from "#execution/sandbox/multiplexed-command.js";
import { buildSandboxSession } from "#execution/sandbox/session.js";
+import { createSandboxProviderIdentity } from "#execution/sandbox/provider-identity.js";
import { streamToBuffer } from "#execution/sandbox/stream-utils.js";
import {
createVercelEveImageSandbox,
@@ -63,132 +63,191 @@ import type {
VercelSandbox,
} from "#execution/sandbox/bindings/vercel-sdk-types.js";
+export type VercelSandboxPreparedArtifact = {
+ readonly snapshotId?: string;
+};
+
+export type VercelSandboxSessionState = {
+ readonly sandboxName: string;
+ readonly version: 3;
+};
+
+type VercelEnvironmentOptions = VercelCreateOptions & {
+ readonly prepare?: (sandbox: SandboxSession) => Promise<void> | void;
+};
+
+export function createVercelSandboxProvider(
+ environmentOptions: Readonly<VercelEnvironmentOptions> | undefined,
+): SandboxProviderImplementation<
+ VercelSandboxRuntimeOptions,
+ VercelSandboxPreparedArtifact,
+ VercelSandboxSessionState,
+ MutableNetworkSandboxSession
+> {
+ const { prepare, ...authoredCreateOptions } = environmentOptions ?? {};
+ return createVercelSandbox({ createOptions: authoredCreateOptions, prepare });
+}
+
export interface CreateVercelSandboxInput {
readonly createSandbox?: CreateVercelSandbox;
readonly createOptions?: VercelCreateOptions;
+ readonly loadDeleteSandboxModule?: () => Promise<VercelModule>;
readonly loadSandboxModule?: () => Promise<VercelModule>;
- readonly resolveSessionCreateOptions?: (
- context: VercelSandboxSessionCreateContext,
- ) => Promise<VercelSandboxSessionCreateOptions> | VercelSandboxSessionCreateOptions;
+ readonly prepare?: (sandbox: SandboxSession) => Promise<void> | void;
+ readonly skipEmptyPreparation?: boolean;
}
-/**
- * Creates the Vercel-backed sandbox backend.
- *
- * Any author-supplied `createOptions` are forwarded to Vercel's sandbox
- * create API for every fresh sandbox the framework creates (template at
- * prewarm time, session at first-time session-create). On resume
- * (`Sandbox.get`) no create happens, so they are not re-applied.
- */
+
export function createVercelSandbox(
input: CreateVercelSandboxInput = {},
-): SandboxBackend<VercelSandboxBootstrapUseOptions, VercelSandboxSessionUseOptions> {
+): SandboxProviderImplementation<
+ VercelSandboxRuntimeOptions,
+ VercelSandboxPreparedArtifact,
+ VercelSandboxSessionState,
+ MutableNetworkSandboxSession
+> {
const loadSandboxModule =
input.loadSandboxModule ?? (async () => await import("#compiled/@vercel/sandbox/index.js"));
+ const loadDeleteSandboxModule =
+ input.loadDeleteSandboxModule ??
+ (async () => await import("#compiled/@vercel/sandbox/index.js"));
const createOptions: VercelCreateOptions = {
timeout: DEFAULT_SANDBOX_TIMEOUT_MS,
...input.createOptions,
};
const createSandbox = input.createSandbox ?? createVercelEveImageSandbox;
- const prewarmedTemplates = new Map<string, VercelSandboxTemplateRecord>();
- return {
- name: "vercel",
- async create(
- createInput: SandboxBackendCreateInput,
- ): Promise<SandboxBackendHandle<VercelSandboxSessionUseOptions>> {
- // Resolve tags up-front so tag-count validation fails fast before
- // we go to the network for the template snapshot.
- const tags = resolveVercelSandboxTags(createOptions.tags, createInput.tags);
-
- const template =
- createInput.templateKey === null
- ? null
- : await readTemplateForCreate({
- createOptions,
- loadSandboxModule,
- prewarmedTemplates,
- templateKey: createInput.templateKey,
+ async function openSession(
+ context: SandboxProviderSessionContext,
+ options: Readonly<VercelSandboxRuntimeOptions> | undefined,
+ artifactValue: SandboxPreparedArtifact,
+ sandboxName: string,
+ ) {
+ const artifact = requirePreparedVercelTemplate(artifactValue);
+ const { mounts, ...runtimeOptions } = options ?? {};
+ const sessionCreateOptions = { ...createOptions, ...runtimeOptions };
+ const tags = resolveVercelSandboxTags(sessionCreateOptions.tags, {
+ sessionId: context.session.id,
+ });
+ const sandboxModule = await loadSandboxModule();
+ const ensureSessionInput: EnsureSessionInput = {
+ createOptions: sessionCreateOptions,
+ createSandbox,
+ resolveSessionCreateOptions: mounts === undefined ? undefined : async () => ({ mounts }),
+ sandboxModule,
+ sessionKey: sandboxName,
+ snapshotId: artifact.snapshotId,
+ tags,
+ };
+ let session: VercelSandboxSessionCreateResult;
+ try {
+ session = await ensureSession(ensureSessionInput);
+ session = await ensureUsableSession({
+ input: ensureSessionInput,
+ loadDeleteSandboxModule,
+ session,
+ });
+ if (
+ session.created &&
+ artifact.snapshotId === undefined &&
+ runtimeOptions.networkPolicy !== undefined
+ ) {
+ try {
+ await applyInitialVercelNetworkPolicy(session.sandbox, runtimeOptions.networkPolicy);
+ } catch (error) {
+ try {
+ await deleteVercelSandbox({
+ createOptions: sessionCreateOptions,
+ loadDeleteSandboxModule,
+ sandbox: session.sandbox,
});
-
- const sandboxModule = await loadSandboxModule();
- const ensureSessionInput: EnsureSessionInput = {
- createOptions,
- createSandbox,
- existingMetadata: createInput.existingMetadata,
- resolveSessionCreateOptions: input.resolveSessionCreateOptions,
- sandboxModule,
- sessionId: createInput.tags?.sessionId ?? createInput.sessionKey,
- sessionKey: createInput.sessionKey,
- snapshotId: template?.snapshotId,
- tags,
- };
- let session: VercelSandboxSessionCreateResult;
- try {
- session = await ensureSession(ensureSessionInput);
- } catch (error) {
- if (template !== null && isVercelSnapshotUnavailableError(error)) {
- prewarmedTemplates.delete(template.templateKey);
- const staleTemplate = await getNamedVercelSandbox({
- createOptions,
- sandboxModule,
- sandboxName: template.sandboxName,
- });
- await staleTemplate?.delete();
- throw new SandboxTemplateNotProvisionedError({
- backendName: "vercel",
- templateKey: template.templateKey,
- });
+ } catch (cleanupError) {
+ throw new AggregateError(
+ [error, cleanupError],
+ `Failed to apply network policy and discard Vercel sandbox session "${context.session.id}".`,
+ { cause: error },
+ );
+ }
+ throw error;
}
- throw new Error(
- `Failed to create sandbox session "${createInput.sessionKey}": ${errorMessage(error)}`,
- { cause: error },
- );
}
-
- try {
- session = await ensureUsableSession({
- input: ensureSessionInput,
- session,
+ } catch (error) {
+ if (isVercelSnapshotUnavailableError(error) && artifact.snapshotId !== undefined) {
+ throw new SandboxTemplateNotProvisionedError({
+ providerName: "vercel",
+ templateKey: artifact.snapshotId,
});
- if (template === null && session.created) {
- await applyInitialVercelNetworkPolicy(session.sandbox, createOptions.networkPolicy);
- }
- } catch (error) {
- throw new Error(
- `Failed to initialize sandbox session "${createInput.sessionKey}": ${errorMessage(error)}`,
- { cause: error },
- );
}
+ throw new Error(
+ `Failed to open Vercel sandbox session "${context.session.id}": ${errorMessage(error)}`,
+ { cause: error },
+ );
+ }
+ const handle = createHandle({
+ createOptions: sessionCreateOptions,
+ loadDeleteSandboxModule,
+ sandbox: session.sandbox,
+ });
+ return handle;
+ }
- return createHandle({
- createOptions,
- sandbox: session.sandbox,
- sandboxModule,
- sessionKey: createInput.sessionKey,
- });
- },
- async prewarm(
- prewarmInput: SandboxBackendPrewarmInput<VercelSandboxBootstrapUseOptions>,
- ): Promise<SandboxBackendPrewarmResult> {
- let outcome: EnsureTemplateOutcome;
+ return {
+ async prepare(context) {
+ const seedFiles = providerResourceTargetFiles(context.resources);
+ if (
+ input.skipEmptyPreparation === true &&
+ input.prepare === undefined &&
+ seedFiles.length === 0
+ )
+ return {};
+ const templateKey = `eve-sbx-tpl-vercel-${createSandboxProviderIdentity({
+ createOptions: vercelIdentityOptions(createOptions),
+ resolvedImage:
+ createOptions.source === undefined
+ ? (createOptions.image ?? VERCEL_EVE_SANDBOX_IMAGE)
+ : undefined,
+ resources: sandboxProviderResourceIdentity(context.resources),
+ sourceRevision: context.sourceRevision,
+ version: 2,
+ }).slice(0, 32)}`;
try {
- outcome = await ensureTemplateWithUnavailableRetry({
- bootstrap: prewarmInput.bootstrap,
+ const outcome = await ensureTemplateWithUnavailableRetry({
createOptions,
createSandbox,
loadSandboxModule,
- log: prewarmInput.log,
- seedFiles: prewarmInput.seedFiles,
- templateKey: prewarmInput.templateKey,
+ log: context.log,
+ prepareSandbox: input.prepare,
+ seedFiles,
+ templateKey,
});
+ return { snapshotId: outcome.template.snapshotId };
} catch (error) {
- throw new Error(
- `Failed to prewarm Vercel sandbox template "${prewarmInput.templateKey}": ${errorMessage(error)}`,
- { cause: error },
- );
+ throw new Error(`Failed to prepare Vercel sandbox snapshot: ${errorMessage(error)}`, {
+ cause: error,
+ });
+ }
+ },
+ async resume(_context, artifact, stateValue) {
+ requirePreparedVercelTemplate(artifact);
+ const state = requireVercelSessionState(stateValue);
+ const sandboxModule = await loadSandboxModule();
+ const sandbox = await getNamedVercelSandbox({
+ createOptions,
+ sandboxModule,
+ sandboxName: state.sandboxName,
+ });
+ if (sandbox === null) {
+ throw new Error(`Vercel sandbox session "${state.sandboxName}" no longer exists.`);
}
- prewarmedTemplates.set(prewarmInput.templateKey, outcome.template);
- return { reused: outcome.reused };
+ await ensureVercelSandboxBaseRuntime(sandbox);
+ return createHandle({ createOptions, loadDeleteSandboxModule, sandbox });
+ },
+ async start(context, options, artifact) {
+ const sandboxName = vercelSessionName(context.session.id, options, artifact, createOptions);
+ const handle = await openSession(context, options, artifact, sandboxName);
+ return {
+ handle,
+ state: { sandboxName, version: 3 },
+ };
},
};
}
@@ -199,21 +258,65 @@ interface VercelSandboxTemplateRecord {
readonly templateKey: string;
}
+function vercelSessionName(
+ sessionId: string,
+ options: Readonly<VercelSandboxRuntimeOptions> | undefined,
+ artifactValue: SandboxPreparedArtifact,
+ createOptions: VercelCreateOptions,
+): string {
+ const artifact = requirePreparedVercelTemplate(artifactValue);
+ return `eve-sbx-vercel-${createSandboxProviderIdentity({
+ artifact,
+ createOptions: vercelIdentityOptions(createOptions),
+ options: vercelIdentityOptions(options),
+ sessionId,
+ version: 1,
+ }).slice(0, 32)}`;
+}
+
+function vercelIdentityOptions(options: object | undefined): object | undefined {
+ if (options === undefined) return undefined;
+ const excluded = new Set(["fetch", "projectId", "signal", "teamId", "token"]);
+ return Object.fromEntries(Object.entries(options).filter(([key]) => !excluded.has(key)));
+}
+
+function requireVercelSessionState(state: SandboxPreparedArtifact): VercelSandboxSessionState {
+ if (
+ !isSandboxPreparedArtifactRecord(state) ||
+ state.version !== 3 ||
+ typeof state.sandboxName !== "string"
+ ) {
+ throw new Error("Invalid Vercel sandbox session state.");
+ }
+ return { sandboxName: state.sandboxName, version: 3 };
+}
+
+function requirePreparedVercelTemplate(
+ artifact: SandboxPreparedArtifact,
+): VercelSandboxPreparedArtifact {
+ if (
+ !isSandboxPreparedArtifactRecord(artifact) ||
+ (artifact.snapshotId !== undefined && typeof artifact.snapshotId !== "string")
+ ) {
+ throw new Error("Invalid prepared Vercel sandbox artifact.");
+ }
+ return artifact.snapshotId === undefined ? {} : { snapshotId: artifact.snapshotId };
+}
+
interface EnsureTemplateOutcome {
- readonly reused: boolean;
readonly template: VercelSandboxTemplateRecord;
}
+type VercelSeedFile = { readonly content: string | Uint8Array; readonly path: string };
+
interface EnsureTemplateInput {
- readonly bootstrap?: (
- input: SandboxBootstrapContext<VercelSandboxBootstrapUseOptions>,
- ) => void | Promise<void>;
+ readonly prepareSandbox?: (sandbox: SandboxSession) => void | Promise<void>;
readonly createOptions: VercelCreateOptions;
readonly createSandbox: CreateVercelSandbox;
readonly loadSandboxModule: () => Promise<VercelModule>;
readonly log?: (message: string) => void;
- readonly seedFiles: ReadonlyArray<SandboxSeedFile>;
- readonly tags?: SandboxBackendTags;
+ readonly seedFiles: ReadonlyArray<VercelSeedFile>;
+ readonly tags?: Record<string, string>;
readonly templateKey: string;
}
@@ -231,62 +334,10 @@ async function ensureTemplateWithUnavailableRetry(
}
}
-async function readTemplate(input: {
- readonly createOptions: VercelCreateOptions;
- readonly loadSandboxModule: () => Promise<VercelModule>;
- readonly prewarmedTemplates: ReadonlyMap<string, VercelSandboxTemplateRecord>;
- readonly templateKey: string;
-}): Promise<VercelSandboxTemplateRecord> {
- const prewarmed = input.prewarmedTemplates.get(input.templateKey);
- if (prewarmed !== undefined) {
- return prewarmed;
- }
-
- const sandboxModule = await input.loadSandboxModule();
- const sandbox = await getNamedVercelSandbox({
- createOptions: input.createOptions,
- sandboxModule,
- sandboxName: input.templateKey,
- });
-
- if (sandbox === null || typeof sandbox.currentSnapshotId !== "string") {
- throw new SandboxTemplateNotProvisionedError({
- backendName: "vercel",
- templateKey: input.templateKey,
- });
- }
-
- return {
- sandboxName: sandbox.name,
- snapshotId: sandbox.currentSnapshotId,
- templateKey: input.templateKey,
- };
-}
-
-async function readTemplateForCreate(input: {
- readonly createOptions: VercelCreateOptions;
- readonly loadSandboxModule: () => Promise<VercelModule>;
- readonly prewarmedTemplates: ReadonlyMap<string, VercelSandboxTemplateRecord>;
- readonly templateKey: string;
-}): Promise<VercelSandboxTemplateRecord> {
- try {
- return await readTemplate(input);
- } catch (error) {
- if (SandboxTemplateNotProvisionedError.is(error)) {
- throw error;
- }
- throw new Error(
- `Failed to read sandbox template "${input.templateKey}": ${errorMessage(error)}`,
- { cause: error },
- );
- }
-}
-
/**
* Creates or refreshes one named Vercel sandbox template and returns the
* resulting snapshot metadata along with whether an existing snapshot
- * was reused. Internal — exposed only to the prewarm pipeline through
- * the backend's `prewarm` method.
+ * was reused. This runs only from the provider's preparation phase.
*/
async function ensureTemplate(input: EnsureTemplateInput): Promise<EnsureTemplateOutcome> {
const sandboxModule = await input.loadSandboxModule();
@@ -325,19 +376,20 @@ async function ensureTemplate(input: EnsureTemplateInput): Promise<EnsureTemplat
* subsequent `getNamedSandbox` reuse until we run our own snapshot.
* So we ignore that exact value: it's the author's base layer, not a
* framework snapshot, and we still owe `ensureSandboxWorkingDirectory`,
- * bootstrap, seed file writes, and `sandbox.snapshot()` on top.
+ * preparation, seed file writes, and `sandbox.snapshot()` on top.
*/
- const hasFrameworkSnapshot =
+ const frameworkSnapshotId =
typeof sandbox.currentSnapshotId === "string" &&
sandbox.currentSnapshotId.length > 0 &&
- sandbox.currentSnapshotId !== authorSnapshotId;
+ sandbox.currentSnapshotId !== authorSnapshotId
+ ? sandbox.currentSnapshotId
+ : null;
- if (hasFrameworkSnapshot) {
+ if (frameworkSnapshotId !== null) {
return {
- reused: true,
template: {
sandboxName: sandbox.name,
- snapshotId: sandbox.currentSnapshotId as string,
+ snapshotId: frameworkSnapshotId,
templateKey: input.templateKey,
},
};
@@ -348,7 +400,7 @@ async function ensureTemplate(input: EnsureTemplateInput): Promise<EnsureTemplat
await applyInitialVercelNetworkPolicy(sandbox, input.createOptions.networkPolicy);
const templateSession = buildSandboxSession(
- createVercelInternalSandboxSession(sandbox, input.templateKey),
+ createVercelInternalSandboxSession(sandbox),
createVercelNetworkPolicySetter(sandbox),
);
@@ -358,24 +410,13 @@ async function ensureTemplate(input: EnsureTemplateInput): Promise<EnsureTemplat
session: templateSession,
});
- if (input.bootstrap !== undefined) {
- input.log?.("running sandbox bootstrap");
- await input.bootstrap({
- use: async (options?: VercelSandboxBootstrapUseOptions) => {
- if (options !== undefined) {
- await sandbox.update(options);
- }
- return createLoggingSandboxSession({
- log: input.log,
- session: templateSession,
- });
- },
- });
- }
+ input.log?.("running sandbox preparation");
+ await input.prepareSandbox?.(
+ createLoggingSandboxSession({ log: input.log, session: templateSession }),
+ );
const snapshot = await sandbox.snapshot();
return {
- reused: false,
template: {
sandboxName: sandbox.name,
snapshotId: snapshot.snapshotId,
@@ -387,10 +428,10 @@ async function ensureTemplate(input: EnsureTemplateInput): Promise<EnsureTemplat
interface EnsureSessionInput {
readonly createOptions: VercelCreateOptions;
readonly createSandbox: CreateVercelSandbox;
- readonly existingMetadata?: Record<string, unknown>;
- readonly resolveSessionCreateOptions?: CreateVercelSandboxInput["resolveSessionCreateOptions"];
+ readonly resolveSessionCreateOptions?: () =>
+ | Promise<VercelSandboxMountOptions>
+ | VercelSandboxMountOptions;
readonly sandboxModule: VercelModule;
- readonly sessionId: string;
readonly sessionKey: string;
readonly snapshotId?: string;
readonly tags: Record<string, string> | undefined;
@@ -403,6 +444,7 @@ interface VercelSandboxSessionCreateResult {
async function ensureUsableSession(input: {
readonly input: EnsureSessionInput;
+ readonly loadDeleteSandboxModule: () => Promise<VercelModule>;
readonly session: VercelSandboxSessionCreateResult;
}): Promise<VercelSandboxSessionCreateResult> {
try {
@@ -416,16 +458,16 @@ async function ensureUsableSession(input: {
await deleteUnusableVercelSandbox({
createOptions: input.input.createOptions,
+ loadDeleteSandboxModule: input.loadDeleteSandboxModule,
sandbox: input.session.sandbox,
- sandboxModule: input.input.sandboxModule,
});
- const replacement = await ensureSession({ ...input.input, existingMetadata: undefined });
+ const replacement = await ensureSession(input.input);
await ensureVercelSandboxBaseRuntime(replacement.sandbox);
return replacement;
}
async function ensureSession(input: EnsureSessionInput): Promise<VercelSandboxSessionCreateResult> {
- const sandboxName = getVercelSandboxName(input.existingMetadata) ?? input.sessionKey;
+ const sandboxName = input.sessionKey;
const existing = await getNamedVercelSandbox({
createOptions: input.createOptions,
sandboxModule: input.sandboxModule,
@@ -437,9 +479,7 @@ async function ensureSession(input: EnsureSessionInput): Promise<VercelSandboxSe
return { created: false, sandbox: existing };
}
- const sessionCreateOptions = await input.resolveSessionCreateOptions?.({
- session: { id: input.sessionId },
- });
+ const sessionCreateOptions = await input.resolveSessionCreateOptions?.();
const createParams = createSessionCreateParams(input, sandboxName, sessionCreateOptions);
if (input.tags !== undefined) {
createParams.tags = input.tags;
@@ -457,9 +497,12 @@ async function ensureSession(input: EnsureSessionInput): Promise<VercelSandboxSe
function createSessionCreateParams(
input: EnsureSessionInput,
sandboxName: string,
- sessionCreateOptions: VercelSandboxSessionCreateOptions = {},
+ sessionCreateOptions: VercelSandboxMountOptions = {},
): VercelSandboxCreateParams {
- const createOptions = { ...input.createOptions, ...sessionCreateOptions } as VercelCreateOptions;
+ const createOptions: VercelCreateOptions = {
+ ...input.createOptions,
+ ...sessionCreateOptions,
+ };
if (input.snapshotId === undefined) {
return withBaseSetupNetworkPolicy({
...createOptions,
@@ -479,57 +522,39 @@ function createSessionCreateParams(
runtime: _runtime,
source: _source,
...baseSessionCreateOptions
- } = createOptions as VercelCreateOptions &
- Partial<Record<"image" | "runtime" | "source", unknown>>;
+ } = createOptions;
return {
...baseSessionCreateOptions,
name: sandboxName,
persistent: true,
- source: { snapshotId: input.snapshotId, type: "snapshot" as const },
+ source: { snapshotId: input.snapshotId, type: "snapshot" },
};
}
function createHandle(input: {
readonly createOptions: VercelCreateOptions;
+ readonly loadDeleteSandboxModule: () => Promise<VercelModule>;
readonly sandbox: VercelSandbox;
- readonly sandboxModule: VercelModule;
- readonly sessionKey: string;
-}): SandboxBackendHandle<VercelSandboxSessionUseOptions> {
- const { sandbox, sessionKey } = input;
+}): SandboxProviderHandle<MutableNetworkSandboxSession> {
+ const { sandbox } = input;
return {
- session: buildSandboxSession(
- createVercelInternalSandboxSession(sandbox, sessionKey),
+ sandbox: buildSandboxSession(
+ createVercelInternalSandboxSession(sandbox),
createVercelNetworkPolicySetter(sandbox),
),
- useSessionFn: async (options?: VercelSandboxSessionUseOptions) => {
- if (options !== undefined) {
- await sandbox.update(options);
- }
- return buildSandboxSession(
- createVercelInternalSandboxSession(sandbox, sessionKey),
- createVercelNetworkPolicySetter(sandbox),
- );
- },
- async captureState() {
- return {
- backendName: "vercel",
- metadata: { sandboxName: sandbox.name },
- sessionKey,
- };
- },
- async delete(options) {
+ async onSessionDelete(options) {
await deleteVercelSandbox({
createOptions: input.createOptions,
+ loadDeleteSandboxModule: input.loadDeleteSandboxModule,
sandbox,
- sandboxModule: input.sandboxModule,
signal: options?.abortSignal,
});
},
- async stop() {
+ async onSessionStop() {
await stopVercelSandbox(sandbox);
},
- async shutdown() {
+ async onRuntimeShutdown() {
try {
await stopVercelSandbox(sandbox);
} catch {
@@ -539,12 +564,8 @@ function createHandle(input: {
};
}
-function createVercelInternalSandboxSession(
- sandbox: VercelSandbox,
- id: string,
-): InternalSandboxSession {
+function createVercelInternalSandboxSession(sandbox: VercelSandbox): InternalSandboxSession {
return {
- id,
resolvePath: resolveVercelSandboxPath,
async spawn(options: SandboxSpawnOptions): Promise<SandboxProcess> {
const command = await sandbox.runCommand({
@@ -580,7 +601,7 @@ function createVercelInternalSandboxSession(
async function writeVercelSandboxSeedFiles(input: {
readonly sandbox: VercelSandbox;
- readonly seedFiles: ReadonlyArray<SandboxSeedFile>;
+ readonly seedFiles: ReadonlyArray<VercelSeedFile>;
readonly session: SandboxSession;
}): Promise<void> {
if (input.seedFiles.length === 0) {
@@ -649,18 +670,13 @@ function isUnprovisionedTerminalTemplateSandbox(
* pre-existing value the way snapshot sources do.
*/
function extractAuthorSnapshotId(createOptions: VercelCreateOptions): string | undefined {
- const source = (createOptions as { source?: { type?: string; snapshotId?: string } }).source;
+ const source = createOptions.source;
if (source?.type === "snapshot" && typeof source.snapshotId === "string") {
return source.snapshotId;
}
return undefined;
}
-function getVercelSandboxName(metadata: Record<string, unknown> | undefined): string | undefined {
- const sandboxName = metadata?.sandboxName;
- return typeof sandboxName === "string" ? sandboxName : undefined;
-}
-
/**
* 30 minutes. The `@vercel/sandbox` SDK defaults to 5 minutes which is
* too short for multi-step workflows — the VM expires between steps.
diff --git a/packages/eve/src/execution/sandbox/development-cleanup.test.ts b/packages/eve/src/execution/sandbox/development-cleanup.test.ts
index cecc29614..d14dc9b56 100644
--- a/packages/eve/src/execution/sandbox/development-cleanup.test.ts
+++ b/packages/eve/src/execution/sandbox/development-cleanup.test.ts
@@ -101,7 +101,7 @@ describe("stopDevelopmentSandboxResources", () => {
expect(state.dockerCli.run).toHaveBeenCalledWith(["stop", "-t", "0", "docker-container"]);
expect(state.microsandboxModule.Sandbox.listWith).toHaveBeenCalledWith({
labels: {
- "eve.backend": "microsandbox",
+ "eve.provider": "microsandbox",
devRunId: "run-123",
},
});
@@ -144,7 +144,7 @@ describe("stopDevelopmentSandboxResources", () => {
expect(state.loadMicrosandboxWithoutInstall).toHaveBeenCalledWith("/tmp/eve-test");
expect(state.microsandboxModule.Sandbox.listWith).toHaveBeenCalledWith({
labels: {
- "eve.backend": "microsandbox",
+ "eve.provider": "microsandbox",
devRunId: "run-123",
},
});
diff --git a/packages/eve/src/execution/sandbox/development-cleanup.ts b/packages/eve/src/execution/sandbox/development-cleanup.ts
index f87c5b303..b2631bebc 100644
--- a/packages/eve/src/execution/sandbox/development-cleanup.ts
+++ b/packages/eve/src/execution/sandbox/development-cleanup.ts
@@ -80,7 +80,7 @@ async function stopDevelopmentMicrosandboxResources(
const sandboxes = await module.Sandbox.listWith({
labels: {
- "eve.backend": "microsandbox",
+ "eve.provider": "microsandbox",
[EVE_DEVELOPMENT_SANDBOX_RUN_ID_TAG]: devRunId,
},
});
diff --git a/packages/eve/src/execution/sandbox/development-prewarm.test.ts b/packages/eve/src/execution/sandbox/development-prewarm.test.ts
index 33ee1b4ec..82e8386fa 100644
--- a/packages/eve/src/execution/sandbox/development-prewarm.test.ts
+++ b/packages/eve/src/execution/sandbox/development-prewarm.test.ts
@@ -9,13 +9,7 @@ import { createDiskRuntimeCompiledArtifactsSource } from "#runtime/compiled-arti
const mocks = vi.hoisted(() => ({
prewarmAppSandboxes:
- vi.fn<
- (input: {
- readonly log?: (message: string) => void;
- readonly onPrewarmSignature?: (signature: string) => void;
- readonly shouldPrewarmSignature?: (signature: string) => boolean;
- }) => Promise<void>
- >(),
+ vi.fn<(input: { readonly log?: (message: string) => void }) => Promise<void>>(),
}));
vi.mock("#execution/sandbox/prewarm.js", () => ({
@@ -147,7 +141,7 @@ describe("development sandbox prewarm coordination", () => {
appRoot,
compiledArtifactsSource,
});
- prewarmLog?.('eve: built sandbox template "root" on backend "docker".');
+ prewarmLog?.('eve: built sandbox template "root" on provider "docker".');
const logs: string[] = [];
const unsubscribe = subscribeDevelopmentSandboxPrewarmLogs({
@@ -162,7 +156,7 @@ describe("development sandbox prewarm coordination", () => {
await prewarm.promise;
expect(logs).toEqual([
- 'eve: built sandbox template "root" on backend "docker".',
+ 'eve: built sandbox template "root" on provider "docker".',
'eve: sandbox template "root" (docker): apt-get update',
]);
});
@@ -171,7 +165,7 @@ describe("development sandbox prewarm coordination", () => {
const appRoot = "/tmp/eve-completed-app";
const compiledArtifactsSource = createDiskRuntimeCompiledArtifactsSource(appRoot);
mocks.prewarmAppSandboxes.mockImplementationOnce(async (input) => {
- input.log?.('eve: built sandbox template "root" on backend "docker".');
+ input.log?.('eve: built sandbox template "root" on provider "docker".');
});
startDevelopmentSandboxPrewarmInBackground({
@@ -192,37 +186,9 @@ describe("development sandbox prewarm coordination", () => {
log: (message) => secondLogs.push(message),
});
- expect(firstLogs).toEqual(['eve: built sandbox template "root" on backend "docker".']);
+ expect(firstLogs).toEqual(['eve: built sandbox template "root" on provider "docker".']);
expect(secondLogs).toEqual([]);
});
-
- it("skips completed prewarm work when the sandbox signature is unchanged", async () => {
- const appRoot = "/tmp/eve-signature-app";
- const compiledArtifactsSource = createDiskRuntimeCompiledArtifactsSource(appRoot);
- let prewarmCount = 0;
- mocks.prewarmAppSandboxes.mockImplementation(async (input) => {
- if (input.shouldPrewarmSignature?.("signature-a") === false) {
- return;
- }
- prewarmCount += 1;
- input.onPrewarmSignature?.("signature-a");
- });
-
- startDevelopmentSandboxPrewarmInBackground({
- appRoot,
- compiledArtifactsSource,
- });
- await Promise.resolve();
- await Promise.resolve();
- startDevelopmentSandboxPrewarmInBackground({
- appRoot,
- compiledArtifactsSource,
- });
- await Promise.resolve();
- await Promise.resolve();
-
- expect(prewarmCount).toBe(1);
- });
});
function createDeferred<T>() {
diff --git a/packages/eve/src/execution/sandbox/development-prewarm.ts b/packages/eve/src/execution/sandbox/development-prewarm.ts
index 5172fc161..44cb1562f 100644
--- a/packages/eve/src/execution/sandbox/development-prewarm.ts
+++ b/packages/eve/src/execution/sandbox/development-prewarm.ts
@@ -17,7 +17,15 @@ interface DevelopmentPrewarmRecord {
const pendingDevelopmentPrewarms = new Map<string, DevelopmentPrewarmRecord>();
const retainedDevelopmentPrewarmLogs = new Map<string, readonly string[]>();
-const completedDevelopmentPrewarmSignatures = new Map<string, string>();
+
+export async function prewarmDevelopmentSandboxes(input: {
+ readonly appRoot: string;
+ readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
+ readonly log?: (message: string) => void;
+}): Promise<void> {
+ startDevelopmentSandboxPrewarmInBackground(input);
+ await waitForDevelopmentSandboxPrewarm(input);
+}
export function startDevelopmentSandboxPrewarmInBackground(input: {
readonly appRoot: string;
@@ -39,16 +47,10 @@ export function startDevelopmentSandboxPrewarmInBackground(input: {
for (const key of keys) {
retainedDevelopmentPrewarmLogs.delete(key);
}
- const signatureCacheKey = resolvePrewarmSignatureCacheKey(input);
const promise = prewarmAppSandboxes({
appRoot: input.appRoot,
compiledArtifactsSource: input.compiledArtifactsSource,
log: (message) => recordPrewarmLog(record, message, input.log),
- onPrewarmSignature: (signature) => {
- completedDevelopmentPrewarmSignatures.set(signatureCacheKey, signature);
- },
- shouldPrewarmSignature: (signature) =>
- completedDevelopmentPrewarmSignatures.get(signatureCacheKey) !== signature,
});
record.promise = promise;
registerPrewarmAliases(keys, record);
@@ -145,13 +147,6 @@ function resolvePrewarmKeys(input: {
return [...keys];
}
-function resolvePrewarmSignatureCacheKey(input: {
- readonly appRoot: string;
- readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
-}): string {
- return getRuntimeCompiledArtifactsSandboxAppRoot(input.compiledArtifactsSource) ?? input.appRoot;
-}
-
function findPendingPrewarm(keys: readonly string[]): DevelopmentPrewarmRecord | undefined {
for (const key of keys) {
const record = pendingDevelopmentPrewarms.get(key);
diff --git a/packages/eve/src/execution/sandbox/development-run.ts b/packages/eve/src/execution/sandbox/development-run.ts
index 75c19cbd9..bf355da90 100644
--- a/packages/eve/src/execution/sandbox/development-run.ts
+++ b/packages/eve/src/execution/sandbox/development-run.ts
@@ -1,7 +1,5 @@
import { randomUUID } from "node:crypto";
-import type { SandboxBackendTags } from "#shared/sandbox-backend.js";
-
export const EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV = "EVE_DEVELOPMENT_SANDBOX_RUN_ID";
export const EVE_DEVELOPMENT_SANDBOX_METADATA_PATH_TAG = "eve.metadataPath";
export const EVE_DEVELOPMENT_SANDBOX_RUN_ID_TAG = "devRunId";
@@ -16,8 +14,8 @@ export function getDevelopmentSandboxRunId(): string | undefined {
}
export function withDevelopmentSandboxTags(
- tags: SandboxBackendTags | undefined,
-): SandboxBackendTags | undefined {
+ tags: Readonly<Record<string, string>> | undefined,
+): Readonly<Record<string, string>> | undefined {
const runId = getDevelopmentSandboxRunId();
if (runId === undefined) {
return tags;
@@ -29,9 +27,9 @@ export function withDevelopmentSandboxTags(
}
export function withDevelopmentSandboxMetadataPathTag(
- tags: SandboxBackendTags | undefined,
+ tags: Readonly<Record<string, string>> | undefined,
metadataPath: string,
-): SandboxBackendTags | undefined {
+): Readonly<Record<string, string>> | undefined {
if (getDevelopmentSandboxRunId() === undefined) {
return tags;
}
diff --git a/packages/eve/src/execution/sandbox/dockerfile.integration.test.ts b/packages/eve/src/execution/sandbox/dockerfile.integration.test.ts
new file mode 100644
index 000000000..4e2a9e118
--- /dev/null
+++ b/packages/eve/src/execution/sandbox/dockerfile.integration.test.ts
@@ -0,0 +1,34 @@
+import { join } from "node:path";
+
+import { describe, expect, it } from "vitest";
+
+import { resolveSandboxDockerfile } from "#execution/sandbox/dockerfile.js";
+import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";
+import { mkdir, writeFile } from "node:fs/promises";
+
+const createScratchDirectory = useTemporaryDirectories();
+
+describe("resolveSandboxDockerfile", () => {
+ it("discovers and hashes the colocated Docker build context", async () => {
+ const agentRoot = await createScratchDirectory("eve-dockerfile-");
+ const sandboxRoot = join(agentRoot, "sandbox");
+ await mkdir(sandboxRoot, { recursive: true });
+ await writeFile(join(sandboxRoot, "Dockerfile"), "FROM alpine\nCOPY setup.sh /setup.sh\n");
+ await writeFile(join(sandboxRoot, "setup.sh"), "#!/bin/sh\n");
+
+ const first = await resolveSandboxDockerfile(agentRoot);
+ await writeFile(join(sandboxRoot, "setup.sh"), "#!/bin/sh\necho changed\n");
+ const second = await resolveSandboxDockerfile(agentRoot);
+
+ expect(first).toMatchObject({
+ contextPath: sandboxRoot,
+ path: join(sandboxRoot, "Dockerfile"),
+ });
+ expect(second?.contentHash).not.toBe(first?.contentHash);
+ });
+
+ it("returns undefined when the sandbox has no Dockerfile", async () => {
+ const agentRoot = await createScratchDirectory("eve-no-dockerfile-");
+ await expect(resolveSandboxDockerfile(agentRoot)).resolves.toBeUndefined();
+ });
+});
diff --git a/packages/eve/src/execution/sandbox/dockerfile.ts b/packages/eve/src/execution/sandbox/dockerfile.ts
new file mode 100644
index 000000000..eb887d0da
--- /dev/null
+++ b/packages/eve/src/execution/sandbox/dockerfile.ts
@@ -0,0 +1,184 @@
+import { createHash, randomUUID } from "node:crypto";
+import { access, mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
+import { dirname, join, relative } from "node:path";
+
+import type { DockerCli } from "#execution/sandbox/bindings/docker-cli.js";
+import type { SandboxProviderFiles } from "#shared/sandbox-provider.js";
+import { expectDockerSuccess } from "#execution/sandbox/bindings/docker-utils.js";
+
+export interface SandboxDockerfile {
+ readonly contextPath: string;
+ readonly contentHash: string;
+ readonly path: string;
+}
+
+export async function materializeSandboxDockerfile(input: {
+ readonly files: SandboxProviderFiles;
+ readonly storagePath: string;
+}): Promise<SandboxDockerfile | undefined> {
+ let content: Uint8Array;
+ try {
+ content = await input.files.read("Dockerfile");
+ } catch (error) {
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return undefined;
+ throw error;
+ }
+ const paths = await input.files.list();
+ const hash = createHash("sha256");
+ const contents = await Promise.all(
+ paths.map(async (path) => ({ content: await input.files.read(path), path })),
+ );
+ for (const file of contents)
+ hash.update(file.path).update("\0").update(file.content).update("\0");
+ const contentHash = hash.digest("hex");
+ const contextPath = join(input.storagePath, "dockerfiles", contentHash);
+ try {
+ await access(join(contextPath, "Dockerfile"));
+ return { contentHash, contextPath, path: join(contextPath, "Dockerfile") };
+ } catch (error) {
+ if (!isFileNotFoundError(error)) throw error;
+ }
+ const temporaryPath = `${contextPath}.${randomUUID()}.tmp`;
+ await Promise.all(
+ contents.map(async (file) => {
+ const target = join(temporaryPath, file.path);
+ await mkdir(dirname(target), { recursive: true });
+ await writeFile(target, file.content);
+ }),
+ );
+ if (!paths.includes("Dockerfile")) {
+ await mkdir(temporaryPath, { recursive: true });
+ await writeFile(join(temporaryPath, "Dockerfile"), content);
+ }
+ await mkdir(dirname(contextPath), { recursive: true });
+ try {
+ await rename(temporaryPath, contextPath);
+ } catch (error) {
+ try {
+ await access(join(contextPath, "Dockerfile"));
+ } catch {
+ throw error;
+ }
+ } finally {
+ await rm(temporaryPath, { force: true, recursive: true });
+ }
+ return { contentHash, contextPath, path: join(contextPath, "Dockerfile") };
+}
+
+export async function resolveSandboxDockerfile(
+ agentRoot: string,
+): Promise<SandboxDockerfile | undefined> {
+ const path = join(agentRoot, "sandbox", "Dockerfile");
+ try {
+ await readFile(path);
+ } catch (error) {
+ if (isFileNotFoundError(error)) return undefined;
+ throw error;
+ }
+ const contextPath = dirname(path);
+ return {
+ contextPath,
+ contentHash: await hashDirectory(contextPath),
+ path,
+ };
+}
+
+export function dockerfileImageReference(input: {
+ readonly dockerfile: SandboxDockerfile;
+ readonly templateKey: string;
+}): string {
+ return `eve-sandbox-dockerfile:${createHash("sha256")
+ .update(`${input.templateKey}:${input.dockerfile.contentHash}`)
+ .digest("hex")
+ .slice(0, 24)}`;
+}
+
+export async function buildSandboxDockerfile(input: {
+ readonly cli: DockerCli;
+ readonly dockerfile: SandboxDockerfile;
+ readonly imageReference: string;
+}): Promise<void> {
+ expectDockerSuccess(
+ await input.cli.run([
+ "build",
+ "--file",
+ input.dockerfile.path,
+ "--tag",
+ input.imageReference,
+ input.dockerfile.contextPath,
+ ]),
+ `build sandbox Dockerfile "${input.dockerfile.path}"`,
+ );
+}
+
+const LOCAL_REGISTRY_CONTAINER = "eve-sandbox-registry";
+const LOCAL_REGISTRY_HOST = "127.0.0.1:51921";
+
+export async function publishDockerImageForMicrosandbox(input: {
+ readonly cli: DockerCli;
+ readonly imageReference: string;
+}): Promise<string> {
+ const inspect = await input.cli.run([
+ "container",
+ "inspect",
+ "--format",
+ "{{.State.Running}}",
+ LOCAL_REGISTRY_CONTAINER,
+ ]);
+ if (inspect.exitCode !== 0) {
+ expectDockerSuccess(
+ await input.cli.run([
+ "run",
+ "--detach",
+ "--name",
+ LOCAL_REGISTRY_CONTAINER,
+ "--publish",
+ `${LOCAL_REGISTRY_HOST}:5000`,
+ "registry:2",
+ ]),
+ "start the local microsandbox image registry",
+ );
+ } else if (inspect.stdout.trim() !== "true") {
+ expectDockerSuccess(
+ await input.cli.run(["start", LOCAL_REGISTRY_CONTAINER]),
+ "restart the local microsandbox image registry",
+ );
+ }
+
+ const target = `${LOCAL_REGISTRY_HOST}/eve/${input.imageReference.replace(":", "-")}`;
+ expectDockerSuccess(
+ await input.cli.run(["tag", input.imageReference, target]),
+ `tag microsandbox image "${target}"`,
+ );
+ expectDockerSuccess(
+ await input.cli.run(["push", target]),
+ `publish microsandbox image "${target}"`,
+ );
+ return target;
+}
+
+function isFileNotFoundError(error: unknown): boolean {
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
+}
+
+async function hashDirectory(root: string): Promise<string> {
+ const hash = createHash("sha256");
+ const paths = await collectFilePaths(root);
+ for (const path of paths) {
+ hash.update(relative(root, path));
+ hash.update("\0");
+ hash.update(await readFile(path));
+ hash.update("\0");
+ }
+ return hash.digest("hex");
+}
+
+async function collectFilePaths(root: string): Promise<string[]> {
+ const paths: string[] = [];
+ for (const entry of await readdir(root, { withFileTypes: true })) {
+ const path = join(root, entry.name);
+ if (entry.isDirectory()) paths.push(...(await collectFilePaths(path)));
+ else if (entry.isFile()) paths.push(path);
+ }
+ return paths.sort();
+}
diff --git a/packages/eve/src/execution/sandbox/ensure.test.ts b/packages/eve/src/execution/sandbox/ensure.test.ts
index 1bf663732..72c44413a 100644
--- a/packages/eve/src/execution/sandbox/ensure.test.ts
+++ b/packages/eve/src/execution/sandbox/ensure.test.ts
@@ -1,495 +1,206 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";
-import type {
- SandboxBackend,
- SandboxBackendCreateInput,
-} from "#public/definitions/sandbox-backend.js";
-import { SandboxTemplateNotProvisionedError } from "#public/definitions/sandbox-backend.js";
-import {
- createBundledRuntimeCompiledArtifactsSource,
- createDiskRuntimeCompiledArtifactsSource,
- type RuntimeCompiledArtifactsSource,
-} from "#runtime/compiled-artifacts-source.js";
-import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";
-import type { ResolvedSandboxDefinition } from "#runtime/types.js";
-import { ContextContainer, contextStorage, loadContext } from "#context/container.js";
-import { SessionKey } from "#context/keys.js";
-import type { Session } from "#context/keys.js";
+import { afterEach, describe, expect, it, vi } from "vitest";
import {
clearActiveSandboxHandlesForTest,
countActiveSandboxHandles,
- shutdownActiveSandboxHandles,
} from "#execution/sandbox/active-handles.js";
+import { ContextContainer, contextStorage } from "#context/container.js";
+import { SessionKey } from "#context/keys.js";
import { ensureSandboxAccess } from "#execution/sandbox/ensure.js";
-import type { SandboxState } from "#sandbox/state.js";
-
-const mocks = vi.hoisted(() => ({
- prewarmAppSandboxes: vi.fn(async () => {}),
- waitForSandboxTemplatePrewarmLock: vi.fn<(input: unknown) => Promise<void>>(async () => {}),
- waitForDevelopmentSandboxPrewarm: vi.fn<(input: unknown) => Promise<void>>(async () => {}),
-}));
+import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";
+import { defineParentSandbox, defineSandbox } from "#public/definitions/sandbox.js";
+import { defineSandboxProvider } from "#shared/sandbox-provider.js";
+import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
+import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";
-vi.mock("#execution/sandbox/development-prewarm.js", () => ({
- waitForDevelopmentSandboxPrewarm: mocks.waitForDevelopmentSandboxPrewarm,
-}));
-vi.mock("#execution/sandbox/prewarm.js", () => ({
- prewarmAppSandboxes: mocks.prewarmAppSandboxes,
+vi.mock("#runtime/sandbox/prepared-artifacts.js", () => ({
+ loadSandboxPreparedArtifact: vi.fn(async () => null),
}));
-vi.mock("#execution/sandbox/template-prewarm-lock.js", () => ({
- waitForSandboxTemplatePrewarmLock: mocks.waitForSandboxTemplatePrewarmLock,
-}));
-
-function createTestRegistry(
- definition: Partial<ResolvedSandboxDefinition>,
- backend: SandboxBackend,
-): RuntimeSandboxRegistry {
- const resolved: ResolvedSandboxDefinition = {
- backend,
- logicalPath: "agent/sandbox/sandbox.ts",
- sourceHash: "test-source-hash",
- sourceId: "agent/sandbox/sandbox",
- sourceKind: "module",
- ...definition,
- };
- return {
- sandbox: {
- definition: resolved,
- workspaceResourceRoot: { logicalPath: "", rootEntries: [] },
- },
- };
-}
-
-function createBackend(options?: { readonly delete?: () => Promise<void> }): SandboxBackend {
- const sandbox = mockSandbox({ id: "sbx_session_auth" });
- const create = vi.fn(async (input: SandboxBackendCreateInput) => {
+function fixture(setup?: () => void, returnCopy = false) {
+ const deleteSandbox = vi.fn(async () => {});
+ const stopSandbox = vi.fn(async () => {});
+ const create = vi.fn(async () => {
+ const sandbox = mockSandbox();
return {
- captureState: async () => ({
- backendName: "test",
- metadata: {},
- sessionKey: input.sessionKey,
- }),
- delete: vi.fn(options?.delete ?? (async () => {})),
- stop: vi.fn(async () => {}),
- useSessionFn: async () => sandbox.session,
- shutdown: async () => {},
- session: sandbox.session,
+ sandbox: sandbox.session,
+ onSessionDelete: deleteSandbox,
+ onRuntimeShutdown: async () => {},
+ onSessionStop: stopSandbox,
};
});
-
- return { create, name: "test", prewarm: vi.fn() };
-}
-
-async function ensure(input: {
- readonly compiledArtifactsSource?: RuntimeCompiledArtifactsSource;
- readonly ownsSandbox?: boolean;
- readonly runOnSession?: (callback: () => Promise<void>) => Promise<void>;
- readonly registry: RuntimeSandboxRegistry;
- readonly state?: SandboxState;
- readonly tags?: Record<string, string>;
-}) {
- return await ensureSandboxAccess({
- compiledArtifactsSource:
- input.compiledArtifactsSource ?? createBundledRuntimeCompiledArtifactsSource(),
- nodeId: "__root__",
- ownsSandbox: input.ownsSandbox,
- registry: input.registry,
- runOnSession: input.runOnSession,
- sessionId: "session_1",
- state: input.state ?? null,
- tags: input.tags,
- });
-}
-
-function createSession(): Session {
- return {
- auth: {
- current: {
- attributes: {},
- authenticator: "slack-webhook",
- issuer: "slack:T123",
- principalId: "slack:T123:U123",
- principalType: "user",
+ const provider = defineSandboxProvider({
+ name: "test",
+ environment: () => ({
+ prepare: async () => null,
+ resume: create,
+ start: async () => ({ handle: await create(), state: null }),
+ }),
+ });
+ const environment = provider.environment();
+ const selector = defineSandbox(async () => {
+ const sandbox = await environment.open();
+ setup?.();
+ return returnCopy ? { ...sandbox } : sandbox;
+ });
+ const registry: RuntimeSandboxRegistry = {
+ sandbox: {
+ definition: {
+ environment,
+ kind: "independent",
+ logicalPath: "sandbox.ts",
+ selector,
+ revisionHash: "hash",
+ sourceId: "sandbox",
+ sourceKind: "module",
},
- initiator: null,
+ workspaceResourceRoot: { logicalPath: "", rootEntries: [] },
},
- sessionId: "session_1",
- turn: { id: "turn_1", sequence: 0 },
};
+ return { create, deleteSandbox, registry, stopSandbox };
}
-
-describe("ensureSandboxAccess", () => {
- beforeEach(() => {
- mocks.prewarmAppSandboxes.mockReset();
- mocks.prewarmAppSandboxes.mockResolvedValue(undefined);
- mocks.waitForSandboxTemplatePrewarmLock.mockReset();
- mocks.waitForSandboxTemplatePrewarmLock.mockResolvedValue(undefined);
- mocks.waitForDevelopmentSandboxPrewarm.mockReset();
- mocks.waitForDevelopmentSandboxPrewarm.mockResolvedValue(undefined);
- });
-
- it("waits for background dev prewarm before creating a templated sandbox", async () => {
- const prewarm = createDeferred<void>();
- mocks.waitForDevelopmentSandboxPrewarm.mockReturnValueOnce(prewarm.promise);
- const bootstrap = vi.fn();
- const backend = createBackend();
- const registry = createTestRegistry({ bootstrap }, backend);
- const appRoot = process.cwd();
-
- const access = await ensure({
- compiledArtifactsSource: createDiskRuntimeCompiledArtifactsSource(appRoot),
+async function open(
+ registry: RuntimeSandboxRegistry,
+ id = "session-1",
+ state: Parameters<typeof ensureSandboxAccess>[0]["state"] = null,
+ principalId?: string,
+) {
+ const context = new ContextContainer();
+ const auth =
+ principalId === undefined
+ ? null
+ : {
+ attributes: {},
+ authenticator: "test",
+ principalId,
+ principalType: "user",
+ };
+ context.set(SessionKey, {
+ auth: { current: auth, initiator: auth },
+ sessionId: id,
+ turn: { id: "turn", sequence: 0 },
+ });
+ return await contextStorage.run(context, async () => {
+ const access = await ensureSandboxAccess({
+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
+ nodeId: "__root__",
registry,
+ sessionId: id,
+ state,
});
- const getPromise = access.get();
-
- await vi.waitFor(() => {
- expect(mocks.waitForDevelopmentSandboxPrewarm).toHaveBeenCalledWith(
- expect.objectContaining({
- appRoot,
- compiledArtifactsSource: createDiskRuntimeCompiledArtifactsSource(appRoot),
- }),
- );
- });
- expect(backend.create).not.toHaveBeenCalled();
-
- prewarm.resolve();
- await getPromise;
-
- expect(backend.create).toHaveBeenCalledTimes(1);
- });
-
- it("prewarms and retries once when a templated sandbox is missing at first use", async () => {
- const backend = createBackend();
- const registry = createTestRegistry({ bootstrap: vi.fn() }, backend);
- const appRoot = process.cwd();
- const compiledArtifactsSource = createDiskRuntimeCompiledArtifactsSource(appRoot);
- vi.mocked(backend.create).mockRejectedValueOnce(
- new SandboxTemplateNotProvisionedError({
- backendName: "test",
- templateKey: "missing-template",
- }),
- );
-
- const access = await ensure({
- compiledArtifactsSource,
- registry,
- });
- await access.get();
-
- expect(mocks.prewarmAppSandboxes).toHaveBeenCalledWith(
- expect.objectContaining({
- appRoot,
- compiledArtifactsSource,
- }),
- );
- expect(backend.create).toHaveBeenCalledTimes(2);
- });
-
- it("prewarms and retries when a dev-runtime copy reports a missing template", async () => {
- const backend = createBackend();
- const registry = createTestRegistry({ bootstrap: vi.fn() }, backend);
- const appRoot = process.cwd();
- const compiledArtifactsSource = createDiskRuntimeCompiledArtifactsSource(appRoot);
- vi.mocked(backend.create).mockRejectedValueOnce({
- backendName: "test",
- message: 'Sandbox template "missing-template" is not provisioned for backend "test".',
- name: "SandboxTemplateNotProvisionedError",
- templateKey: "missing-template",
- });
-
- const access = await ensure({
- compiledArtifactsSource,
- registry,
- });
- await access.get();
-
- expect(mocks.prewarmAppSandboxes).toHaveBeenCalledTimes(1);
- expect(backend.create).toHaveBeenCalledTimes(2);
- });
-
- it("opens dev snapshot artifact sandboxes with the authored app root", async () => {
- const backend = createBackend();
- const registry = createTestRegistry({ bootstrap: vi.fn() }, backend);
- const appRoot = process.cwd();
- const snapshotRoot = `${appRoot}/.eve/dev-runtime/snapshots/current/app`;
- const compiledArtifactsSource = createDiskRuntimeCompiledArtifactsSource(snapshotRoot, {
- moduleMapLoaderPath: "/tmp/eve-package/authored-module-map-loader.ts",
- sandboxAppRoot: appRoot,
- });
-
- const access = await ensure({
- compiledArtifactsSource,
- registry,
- });
- await access.get();
-
- expect(mocks.waitForDevelopmentSandboxPrewarm).toHaveBeenCalledWith(
- expect.objectContaining({
- appRoot,
- compiledArtifactsSource,
- }),
- );
- expect(mocks.waitForSandboxTemplatePrewarmLock).toHaveBeenCalledWith(
- expect.objectContaining({
- appRoot,
- }),
- );
- expect(backend.create).toHaveBeenCalledWith(
- expect.objectContaining({
- runtimeContext: { appRoot },
- }),
- );
+ return { access, sandbox: await access.get() };
});
+}
+afterEach(() => clearActiveSandboxHandlesForTest());
- it("runs onSession inside the active eve context", async () => {
- const ctx = new ContextContainer();
- const session = createSession();
- ctx.set(SessionKey, session);
-
- let observedSession: Session | undefined;
- let observedSessionId: string | undefined;
- let observedContextKeys: string[] | undefined;
- const onSession = vi.fn((input) => {
- observedSession = loadContext().require(SessionKey);
- observedSessionId = input.ctx.session.id;
- observedContextKeys = Object.keys(input.ctx);
- });
- const backend = createBackend();
- const registry = createTestRegistry({ onSession }, backend);
-
- const access = await ensure({
- registry,
- runOnSession: async (callback) => await contextStorage.run(ctx, callback),
- });
- await access.get();
-
- expect(observedSession).toBe(session);
- expect(observedSessionId).toBe("session_1");
- expect(observedContextKeys).toEqual(["session"]);
- expect(onSession).toHaveBeenCalledWith({
- ctx: expect.objectContaining({
- session: expect.objectContaining({ id: "session_1" }),
- }),
- use: expect.any(Function),
- });
- });
-
- it("reattaches with persisted metadata and skips onSession when the session key matches", async () => {
- const ctx = new ContextContainer();
- ctx.set(SessionKey, createSession());
- const runOnSession = async (callback: () => Promise<void>) =>
- await contextStorage.run(ctx, callback);
- const onSession = vi.fn();
- const backend = createBackend();
- const registry = createTestRegistry({ onSession }, backend);
-
- const first = await ensure({ registry, runOnSession });
- await first.get();
- const state = await first.captureState();
- expect(onSession).toHaveBeenCalledTimes(1);
-
- const second = await ensure({ registry, runOnSession, state });
- await second.get();
-
- expect(onSession).toHaveBeenCalledTimes(1);
- expect(vi.mocked(backend.create).mock.calls[1]?.[0].existingMetadata).toEqual({});
- });
-
- it("re-runs onSession and drops stale metadata when the session key rotates", async () => {
- const ctx = new ContextContainer();
- ctx.set(SessionKey, createSession());
- const onSession = vi.fn();
- const backend = createBackend();
- const registry = createTestRegistry({ onSession }, backend);
-
- const access = await ensure({
- registry,
- runOnSession: async (callback) => await contextStorage.run(ctx, callback),
- state: {
- initialized: true,
- session: {
- backendName: "test",
- metadata: { sandboxName: "stale" },
- sessionKey: "eve-sbx-ses-test-stale-key",
- },
- },
+describe("ensureSandboxAccess", () => {
+ it("creates and returns a real sandbox", async () => {
+ const value = fixture();
+ expect((await open(value.registry)).sandbox).toBeTruthy();
+ expect(value.create).toHaveBeenCalledOnce();
+ });
+ it("resumes persisted provider state without invoking the selector", async () => {
+ const setup = vi.fn();
+ const value = fixture(setup);
+ await open(value.registry, "session-1", {
+ session: { providerName: "test", state: null, stateProtocolVersion: 1 },
});
- await access.get();
-
- expect(onSession).toHaveBeenCalledTimes(1);
- expect(vi.mocked(backend.create).mock.calls[0]?.[0].existingMetadata).toBeUndefined();
- });
-
- it("does not pass bootstrap or seed files to runtime create", async () => {
- const bootstrap = vi.fn();
- const backend = createBackend();
- const registry = createTestRegistry({ bootstrap, revalidationKey: "test-bootstrap" }, backend);
-
- const access = await ensure({ registry });
- await access.get();
-
- expect(bootstrap).not.toHaveBeenCalled();
- expect(backend.create).toHaveBeenCalledWith(
- expect.not.objectContaining({
- bootstrap: expect.anything(),
- seedFiles: expect.anything(),
- }),
- );
- });
-
- it("passes a null template key for sandboxes with no bootstrap or seed files", async () => {
- const backend = createBackend();
- const registry = createTestRegistry({}, backend);
-
- const access = await ensure({ registry });
- await access.get();
-
- expect(backend.create).toHaveBeenCalledWith(
- expect.objectContaining({
- templateKey: null,
- }),
- );
+ expect(setup).not.toHaveBeenCalled();
+ expect(value.create).toHaveBeenCalledOnce();
});
- it("derives an inherited sandbox from the parent owner identity", async () => {
- const parentBackend = createBackend();
- const childBackend = createBackend();
- const registry = createTestRegistry({ inheritsParent: true }, childBackend);
- const parentDefinition: ResolvedSandboxDefinition = {
- backend: parentBackend,
- logicalPath: "agent/sandbox.ts",
- sourceHash: "parent-source-hash",
- sourceId: "agent/sandbox",
- sourceKind: "module",
- };
- const inheritedRegistry: RuntimeSandboxRegistry = {
+ it("passes empty live options when a child inherits its parent sandbox", async () => {
+ const value = fixture();
+ const parent = value.registry.sandbox;
+ const registry: RuntimeSandboxRegistry = {
sandbox: {
- ...registry.sandbox,
+ definition: {
+ kind: "parent",
+ logicalPath: "sandbox.ts",
+ selector: defineParentSandbox(),
+ revisionHash: "child-hash",
+ sourceId: "child-sandbox",
+ sourceKind: "module",
+ },
inheritance: {
- definition: parentDefinition,
+ definition: parent.definition,
nodeId: "__root__",
- workspaceResourceRoot: { logicalPath: "", rootEntries: [] },
+ workspaceResourceRoot: parent.workspaceResourceRoot,
},
+ workspaceResourceRoot: { logicalPath: "", rootEntries: [] },
},
};
- const access = await ensure({ registry: inheritedRegistry });
- await access.get();
-
- expect(childBackend.create).not.toHaveBeenCalled();
- expect(parentBackend.create).toHaveBeenCalledWith(
- expect.objectContaining({
- sessionKey: expect.stringContaining("session_1-__root__"),
- }),
- );
- });
-
- it("passes runtime tags to the sandbox backend", async () => {
- const backend = createBackend();
- const registry = createTestRegistry({}, backend);
-
- const access = await ensure({
- registry,
- tags: {
- agent: "weather-agent",
- channel: "http",
- sessionId: "session_1",
- },
- });
- await access.get();
-
- expect(backend.create).toHaveBeenCalledWith(
- expect.objectContaining({
- tags: {
- agent: "weather-agent",
- channel: "http",
- sessionId: "session_1",
- },
- }),
- );
- });
-
- it("tracks created handles for server shutdown", async () => {
- clearActiveSandboxHandlesForTest();
- const backend = createBackend();
- const registry = createTestRegistry({}, backend);
-
- const access = await ensure({ registry });
- await access.get();
+ await open(registry);
- expect(countActiveSandboxHandles()).toBe(1);
- await shutdownActiveSandboxHandles();
- expect(countActiveSandboxHandles()).toBe(0);
+ expect(value.create).toHaveBeenCalledOnce();
});
- it("delegates authored stops to the backend handle", async () => {
- const backend = createBackend();
- const registry = createTestRegistry({}, backend);
-
- const access = await ensure({ registry });
- await access.stop();
-
- const handle = await vi.mocked(backend.create).mock.results[0]?.value;
- expect(handle?.stop).toHaveBeenCalledTimes(1);
+ it("rejects a fabricated sandbox", async () => {
+ const value = fixture(undefined, true);
+ await expect(open(value.registry)).rejects.toThrow("must return the sandbox it opens");
});
- it("deletes the sandbox and reprovisions a fresh handle on the next access", async () => {
- const ctx = new ContextContainer();
- ctx.set(SessionKey, createSession());
- const onSession = vi.fn();
- const backend = createBackend();
- const access = await ensure({
- registry: createTestRegistry({ onSession }, backend),
- runOnSession: async (callback) => await contextStorage.run(ctx, callback),
+ it("shares one selector invocation across concurrent first access", async () => {
+ const value = fixture();
+ const context = new ContextContainer();
+ context.set(SessionKey, {
+ auth: { current: null, initiator: null },
+ sessionId: "session-1",
+ turn: { id: "turn", sequence: 0 },
});
-
- await expect(access.delete!()).resolves.toBeUndefined();
- await expect(access.captureState()).resolves.toEqual({ initialized: false, session: null });
- await access.get();
-
- expect(backend.create).toHaveBeenCalledTimes(2);
- expect(onSession).toHaveBeenCalledTimes(2);
- const firstHandle = await vi.mocked(backend.create).mock.results[0]!.value;
- expect(firstHandle.delete).toHaveBeenCalledTimes(1);
+ await contextStorage.run(context, async () => {
+ const access = await ensureSandboxAccess({
+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
+ nodeId: "__root__",
+ registry: value.registry,
+ sessionId: "session-1",
+ state: null,
+ });
+ const [first, second] = await Promise.all([access.get(), access.get()]);
+ expect(second).toBe(first);
+ });
+ expect(value.create).toHaveBeenCalledOnce();
});
- it("preserves the current handle and state when deletion fails", async () => {
- const backend = createBackend({
- delete: async () => {
- throw new Error("provider unreachable");
- },
+ it("retries session setup after a selector failure", async () => {
+ let attempts = 0;
+ const value = fixture(() => {
+ attempts += 1;
+ if (attempts === 1) throw new Error("setup failed");
});
- const access = await ensure({ registry: createTestRegistry({}, backend) });
-
- await expect(access.delete!()).rejects.toThrow("provider unreachable");
- await access.get();
-
- expect(backend.create).toHaveBeenCalledTimes(1);
- await expect(access.captureState()).resolves.toMatchObject({
- initialized: true,
- session: { backendName: "test" },
+ const context = new ContextContainer();
+ context.set(SessionKey, {
+ auth: { current: null, initiator: null },
+ sessionId: "session-1",
+ turn: { id: "turn", sequence: 0 },
});
+ await contextStorage.run(context, async () => {
+ const access = await ensureSandboxAccess({
+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
+ nodeId: "__root__",
+ registry: value.registry,
+ sessionId: "session-1",
+ state: null,
+ });
+ await expect(access.get()).rejects.toThrow("setup failed");
+ expect(countActiveSandboxHandles()).toBe(0);
+ await expect(access.get()).resolves.toBeTruthy();
+ });
+ expect(attempts).toBe(2);
});
- it("rejects deletion from a session that does not own the shared sandbox", async () => {
- const backend = createBackend();
- const access = await ensure({ ownsSandbox: false, registry: createTestRegistry({}, backend) });
-
- await expect(access.delete!()).rejects.toThrow(
- "Only the owning session can delete a shared sandbox",
- );
-
- expect(backend.create).not.toHaveBeenCalled();
+ it("tracks dedicated handles for server shutdown", async () => {
+ const value = fixture();
+ await open(value.registry);
+ expect(countActiveSandboxHandles()).toBe(1);
});
-});
-function createDeferred<T>() {
- let resolve!: (value: T | PromiseLike<T>) => void;
- let reject!: (reason?: unknown) => void;
- const promise = new Promise<T>((promiseResolve, promiseReject) => {
- resolve = promiseResolve;
- reject = promiseReject;
+ it("deletes a dedicated sandbox and creates a fresh handle on next access", async () => {
+ const value = fixture();
+ const { access } = await open(value.registry);
+ await access.delete?.();
+ await access.get();
+ expect(value.deleteSandbox).toHaveBeenCalledOnce();
+ expect(value.create).toHaveBeenCalledTimes(2);
});
- return { promise, reject, resolve };
-}
+});
diff --git a/packages/eve/src/execution/sandbox/ensure.ts b/packages/eve/src/execution/sandbox/ensure.ts
index cc925f695..f1e7c8a4f 100644
--- a/packages/eve/src/execution/sandbox/ensure.ts
+++ b/packages/eve/src/execution/sandbox/ensure.ts
@@ -1,280 +1,293 @@
-import type { SandboxSession } from "#public/definitions/sandbox.js";
-import type {
- SandboxBackend,
- SandboxBackendCreateInput,
- SandboxBackendHandle,
- SandboxBackendTags,
-} from "#public/definitions/sandbox-backend.js";
-import { SandboxTemplateNotProvisionedError } from "#public/definitions/sandbox-backend.js";
-import { isEveDevEnvironment } from "#internal/application/optional-package-install.js";
+import { contextStorage } from "#context/container.js";
+import {
+ buildCallbackContext,
+ withRuntimeSandboxLifecycle,
+} from "#context/build-callback-context.js";
+import { trackActiveSandboxHandle } from "#execution/sandbox/active-handles.js";
+import { createSandboxProviderHost } from "#execution/sandbox/provider-host.js";
+import { resolveSandboxCacheDirectory } from "#internal/application/paths.js";
import {
getRuntimeCompiledArtifactsSandboxAppRoot,
type RuntimeCompiledArtifactsSource,
} from "#runtime/compiled-artifacts-source.js";
-import { trackActiveSandboxHandle } from "#execution/sandbox/active-handles.js";
-import { waitForDevelopmentSandboxPrewarm } from "#execution/sandbox/development-prewarm.js";
-import { prewarmAppSandboxes } from "#execution/sandbox/prewarm.js";
-import { waitForSandboxTemplatePrewarmLock } from "#execution/sandbox/template-prewarm-lock.js";
-import { buildCallbackContext } from "#context/build-callback-context.js";
-import { createRuntimeSandboxKeys } from "#runtime/sandbox/keys.js";
+import { loadSandboxPreparedArtifact } from "#runtime/sandbox/prepared-artifacts.js";
import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";
-import { createRuntimeSandboxTemplatePlan } from "#runtime/sandbox/template-plan.js";
import type { SandboxAccess, SandboxSessionState, SandboxState } from "#sandbox/state.js";
+import {
+ getSandboxEnvironmentRuntime,
+ runWithSandboxConstructorRuntime,
+} from "#shared/sandbox-environment.js";
+import {
+ isSandboxPreparedArtifact,
+ type SandboxDeleteOptions,
+ type SandboxProviderHandle,
+ type SandboxProviderRuntime,
+ type SandboxProviderSessionContext,
+} from "#shared/sandbox-provider.js";
+import type { RuntimeSandboxSession } from "#shared/sandbox-session.js";
+import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";
-/**
- * Input for creating or reattaching the live sandbox for one step execution.
- */
export interface EnsureSandboxAccessInput {
readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
readonly nodeId: string;
- /** Whether this durable session owns the sandbox lifecycle. */
readonly ownsSandbox?: boolean;
readonly registry: RuntimeSandboxRegistry;
readonly sessionId: string;
- readonly runOnSession?: (callback: () => Promise<void>) => Promise<void>;
readonly state: SandboxState | null;
- readonly tags?: SandboxBackendTags;
}
-/**
- * Creates or reattaches the live sandbox from the compiled agent bundle's
- * registry and persisted session state, returning a {@link SandboxAccess}
- * suitable for the runtime context.
- *
- * Every agent has exactly one sandbox. The sandbox carries its own
- * `SandboxBackend` value (resolved from the authored module or
- * substituted with `defaultSandbox()` when omitted), and the runtime
- * simply calls `backend.create(...)`.
- */
+interface OpenedSandbox {
+ readonly handle: SandboxProviderHandle;
+ readonly providerName: string;
+ readonly sandbox: RuntimeSandboxSession;
+}
+
export async function ensureSandboxAccess(input: EnsureSandboxAccessInput): Promise<SandboxAccess> {
- let initialized = input.state?.initialized ?? false;
- let persistedSession: SandboxSessionState | null = input.state?.session ?? null;
+ let persisted: SandboxSessionState | null = input.state?.session ?? null;
+ let opened: OpenedSandbox | undefined;
+ let opening: Promise<SandboxProviderHandle> | undefined;
+ let requiring: Promise<SandboxProviderHandle> | undefined;
const appRoot =
getRuntimeCompiledArtifactsSandboxAppRoot(input.compiledArtifactsSource) ?? process.cwd();
-
const registered = input.registry.sandbox;
- let handlePromise: Promise<SandboxBackendHandle | null> | undefined;
-
- function getHandle(): Promise<SandboxBackendHandle | null> {
- if (handlePromise !== undefined) {
- return handlePromise;
- }
- handlePromise = createHandle().catch((error) => {
- handlePromise = undefined;
- throw error;
- });
- return handlePromise;
+ if (registered === null) {
+ return {
+ async captureState() {
+ return { session: persisted };
+ },
+ async get() {
+ return null;
+ },
+ async stop() {},
+ };
}
- async function createHandle(): Promise<SandboxBackendHandle | null> {
- if (registered === null) {
- return null;
+ async function open(
+ provider: SandboxProviderRuntime,
+ options: object | undefined,
+ environment: object,
+ session: SandboxProviderSessionContext["session"],
+ ): Promise<RuntimeSandboxSession> {
+ if (opening !== undefined) throw new Error("A sandbox definition can open only one sandbox.");
+ const inherited = registered.inheritance;
+ const definition = inherited?.definition ?? registered.definition;
+ if (definition.kind !== "independent")
+ throw new Error(`Sandbox "${definition.logicalPath}" has no environment.`);
+ if (environment !== definition.environment)
+ throw new Error(`Sandbox "${definition.logicalPath}" selected a different environment.`);
+ if (provider !== getSandboxEnvironmentRuntime(definition.environment))
+ throw new Error(`Sandbox "${definition.logicalPath}" selected a different provider.`);
+ if (persisted !== null) {
+ throw new Error(`Sandbox "${definition.logicalPath}" is already initialized.`);
}
- const inheritance = registered.inheritance;
- const definition = inheritance?.definition ?? registered.definition;
- const backend = definition.backend;
- const templatePlan = createRuntimeSandboxTemplatePlan({
- definition,
- workspaceResourceRoot: inheritance?.workspaceResourceRoot ?? registered.workspaceResourceRoot,
- });
- const keys = await createRuntimeSandboxKeys({
- backendName: backend.name,
+ const artifactNodeId = inherited?.nodeId ?? input.nodeId;
+ const artifact = await loadSandboxPreparedArtifact({
compiledArtifactsSource: input.compiledArtifactsSource,
- nodeId: inheritance?.nodeId ?? input.nodeId,
- sessionId: input.sessionId,
- sourceId: definition.sourceId,
- templatePlan,
+ nodeId: artifactNodeId,
+ providerName: provider.providerName,
});
-
- if (keys.templateKey !== null) {
- await waitForDevelopmentSandboxPrewarm({
- appRoot,
- compiledArtifactsSource: input.compiledArtifactsSource,
- log: (message) =>
- logDevelopmentSandbox(
- `eve: sandbox template "${formatNodeLabel(input.nodeId)}" (${backend.name}): ${message}`,
- ),
- });
- await waitForSandboxTemplatePrewarmLock({
- appRoot,
- backendName: backend.name,
- log: (message) =>
- logDevelopmentSandbox(
- `eve: sandbox template "${formatNodeLabel(input.nodeId)}" (${backend.name}): ${message}`,
- ),
- templateKey: keys.templateKey,
+ if (artifact === undefined) {
+ throw new SandboxTemplateNotProvisionedError({
+ providerName: provider.providerName,
+ templateKey: artifactNodeId,
});
}
- // The session eve may reattach to: the persisted record is only
- // meaningful when it names the sandbox this step derived. A rotated
- // session key (the sandbox definition changed) means the backend
- // provisions a fresh sandbox, so per-session initialization must run
- // again even though the durable state says it already did.
- const reattachSession =
- persistedSession !== null &&
- persistedSession.backendName === backend.name &&
- persistedSession.sessionKey === keys.sessionKey
- ? persistedSession
- : null;
- if (reattachSession === null) {
- initialized = false;
- }
-
- const createInput: SandboxBackendCreateInput = {
- existingMetadata: reattachSession?.metadata,
- runtimeContext: { appRoot },
- sessionKey: keys.sessionKey,
- tags: input.tags,
- templateKey: keys.templateKey,
+ const context: SandboxProviderSessionContext = {
+ host: createSandboxProviderHost(appRoot),
+ session,
+ storagePath: resolveSandboxCacheDirectory(appRoot),
+ };
+ const createHandle = async () => {
+ const result = await provider.implementation.start(context, options, artifact);
+ if (!isSandboxPreparedArtifact(result.state)) {
+ throw new Error(
+ `Sandbox provider "${provider.providerName}" returned non-serializable session state.`,
+ );
+ }
+ persisted = {
+ providerName: provider.providerName,
+ state: result.state,
+ stateProtocolVersion: provider.stateProtocolVersion,
+ };
+ return result.handle;
};
+ opening = createHandle().catch((error: unknown) => {
+ opening = undefined;
+ throw error;
+ });
+
+ const handle = await opening;
+ return installHandle(provider.providerName, handle);
+ }
- const handle = await withDevelopmentSandboxProgress(
- `eve: opening sandbox session "${formatNodeLabel(input.nodeId)}" on backend "${backend.name}"...`,
- `eve: opening sandbox session "${formatNodeLabel(input.nodeId)}" on backend "${backend.name}"`,
- async () =>
- await createBackendHandleWithPrewarmRetry({
- appRoot,
- backend,
- compiledArtifactsSource: input.compiledArtifactsSource,
- createInput,
- }),
+ function installHandle(
+ providerName: string,
+ handle: SandboxProviderHandle,
+ ): RuntimeSandboxSession {
+ const sandbox = withRuntimeSandboxLifecycle(
+ handle.sandbox,
+ (deleteOptions?: SandboxDeleteOptions) => handle.onSessionDelete(deleteOptions),
+ () => handle.onSessionStop(),
);
- trackActiveSandboxHandle({
- backendName: backend.name,
- handle,
- sessionKey: keys.sessionKey,
- });
+ opened = { handle, providerName, sandbox };
+ return sandbox;
+ }
- if (!initialized) {
- await runOnSession(async () => {
- await definition.onSession?.({
- ctx: { session: buildCallbackContext().session },
- use: handle.useSessionFn,
- });
+ async function resumePersisted(
+ definition: Extract<typeof registered.definition, { readonly kind: "independent" }>,
+ session: SandboxProviderSessionContext["session"],
+ ): Promise<SandboxProviderHandle> {
+ if (persisted === null) throw new Error("Sandbox session state is missing.");
+ const provider = getSandboxEnvironmentRuntime(definition.environment);
+ if (persisted.providerName !== provider.providerName) {
+ throw new Error(
+ `Sandbox session state belongs to provider "${persisted.providerName}", not "${provider.providerName}".`,
+ );
+ }
+ if (persisted.stateProtocolVersion !== provider.stateProtocolVersion) {
+ throw new Error(
+ `Sandbox session state protocol ${persisted.stateProtocolVersion} is incompatible with provider "${provider.providerName}" protocol ${provider.stateProtocolVersion}.`,
+ );
+ }
+ const inherited = registered.inheritance;
+ const artifactNodeId = inherited?.nodeId ?? input.nodeId;
+ const artifact = await loadSandboxPreparedArtifact({
+ compiledArtifactsSource: input.compiledArtifactsSource,
+ nodeId: artifactNodeId,
+ providerName: provider.providerName,
+ });
+ if (artifact === undefined) {
+ throw new SandboxTemplateNotProvisionedError({
+ providerName: provider.providerName,
+ templateKey: artifactNodeId,
});
- initialized = true;
}
-
+ const context: SandboxProviderSessionContext = {
+ host: createSandboxProviderHost(appRoot),
+ session,
+ storagePath: resolveSandboxCacheDirectory(appRoot),
+ };
+ opening = provider.implementation
+ .resume(context, artifact, persisted.state)
+ .catch((error: unknown) => {
+ opening = undefined;
+ throw error;
+ });
+ const handle = await opening;
+ installHandle(provider.providerName, handle);
+ trackActiveSandboxHandle({
+ handle,
+ providerName: provider.providerName,
+ sessionId: input.sessionId,
+ });
return handle;
}
- async function runOnSession(callback: () => Promise<void>): Promise<void> {
- if (input.runOnSession !== undefined) {
- await input.runOnSession(callback);
- return;
- }
- await callback();
- }
+ async function resolveHandle(): Promise<SandboxProviderHandle> {
+ const inherited = registered.inheritance;
+ const definition = inherited?.definition ?? registered.definition;
+ if (definition.kind !== "independent")
+ throw new Error(`Sandbox "${definition.logicalPath}" has no resolved parent.`);
- return {
- async captureState() {
- if (handlePromise !== undefined) {
- const handle = await handlePromise;
- if (handle !== null) {
- persistedSession = await handle.captureState();
- }
- }
+ const activeSession =
+ contextStorage.getStore() === undefined
+ ? {
+ auth: { current: null, initiator: null },
+ id: input.sessionId,
+ turn: { id: "sandbox-initialization", sequence: 0 },
+ }
+ : buildCallbackContext().session;
+ const session = { ...activeSession, id: input.sessionId };
- return {
- initialized,
- session: persistedSession,
- };
- },
- async delete(options) {
- if (input.ownsSandbox === false) {
- throw new Error(
- "Only the owning session can delete a shared sandbox. Delete it from the parent session instead.",
+ if (persisted !== null) {
+ return await resumePersisted(definition, session);
+ }
+
+ if (inherited !== undefined) {
+ await open(
+ getSandboxEnvironmentRuntime(definition.environment),
+ undefined,
+ definition.environment,
+ session,
+ );
+ } else {
+ try {
+ const selected = await runWithSandboxConstructorRuntime(
+ {
+ open: ({ environment, options, provider }) =>
+ open(provider, options, environment, session),
+ },
+ async () => definition.selector({ session }),
);
+ if (opened === undefined || selected !== opened.sandbox) {
+ throw new Error(`Sandbox "${definition.logicalPath}" must return the sandbox it opens.`);
+ }
+ } catch (error) {
+ const failed = opened?.handle;
+ opened = undefined;
+ opening = undefined;
+ persisted = null;
+ if (failed !== undefined) {
+ try {
+ await failed.onSessionDelete();
+ } catch (cleanupError) {
+ throw new AggregateError(
+ [error, cleanupError],
+ `Sandbox "${definition.logicalPath}" initialization and cleanup both failed.`,
+ { cause: error },
+ );
+ }
+ }
+ throw error;
}
- const handle = await getHandle();
- if (handle === null) {
- throw new Error("The sandbox is not available in the current authored runtime context.");
- }
- await handle.delete(options);
- handlePromise = undefined;
- initialized = false;
- persistedSession = null;
- },
- async get(): Promise<SandboxSession | null> {
- const handle = await getHandle();
- if (handle === null) return null;
- return handle.session;
- },
- async stop(): Promise<void> {
- const handle = await getHandle();
- if (handle === null) {
- throw new Error("The sandbox is not available in the current authored runtime context.");
- }
- await handle.stop();
- },
- };
-}
-
-async function createBackendHandleWithPrewarmRetry(input: {
- readonly appRoot: string;
- readonly backend: SandboxBackend;
- readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
- readonly createInput: SandboxBackendCreateInput;
-}): Promise<SandboxBackendHandle> {
- try {
- return await input.backend.create(input.createInput);
- } catch (error) {
- if (
- input.createInput.templateKey === null ||
- input.compiledArtifactsSource.kind !== "disk" ||
- !SandboxTemplateNotProvisionedError.is(error)
- ) {
- throw error;
}
- await prewarmAppSandboxes({
- appRoot: input.appRoot,
- compiledArtifactsSource: input.compiledArtifactsSource,
- log: (message) => logDevelopmentSandbox(message),
- });
- await waitForSandboxTemplatePrewarmLock({
- appRoot: input.appRoot,
- backendName: input.backend.name,
- log: (message) => logDevelopmentSandbox(`eve: ${message}`),
- templateKey: input.createInput.templateKey,
+ if (opened === undefined)
+ throw new Error(`Sandbox "${definition.logicalPath}" did not open a provider handle.`);
+ trackActiveSandboxHandle({
+ handle: opened.handle,
+ providerName: opened.providerName,
+ sessionId: input.sessionId,
});
- logDevelopmentSandbox("eve: sandbox template is ready; retrying sandbox creation...");
- return await input.backend.create(input.createInput);
+ return opened.handle;
}
-}
-
-function logDevelopmentSandbox(message: string): void {
- if (isEveDevEnvironment()) {
- console.log(message);
- }
-}
-
-async function withDevelopmentSandboxProgress<T>(
- startMessage: string,
- progressMessage: string,
- callback: () => Promise<T>,
-): Promise<T> {
- logDevelopmentSandbox(startMessage);
- if (!isEveDevEnvironment()) {
- return await callback();
- }
-
- const startedAt = Date.now();
- const timer = setInterval(() => {
- const elapsedSeconds = Math.round((Date.now() - startedAt) / 1000);
- logDevelopmentSandbox(`${progressMessage} (${elapsedSeconds}s elapsed)...`);
- }, 5_000);
- timer.unref?.();
- try {
- return await callback();
- } finally {
- clearInterval(timer);
+ function requireHandle(): Promise<SandboxProviderHandle> {
+ if (requiring !== undefined) return requiring;
+ requiring = resolveHandle().catch((error: unknown) => {
+ requiring = undefined;
+ throw error;
+ });
+ return requiring;
}
-}
-function formatNodeLabel(nodeId: string): string {
- return nodeId === "__root__" ? "root" : nodeId;
+ return {
+ async captureState() {
+ if (opening !== undefined) await opening;
+ return { session: persisted };
+ },
+ async delete(deleteOptions) {
+ if (input.ownsSandbox === false)
+ throw new Error("Only the owning session can delete this sandbox.");
+ const current = await requireHandle();
+ await current.onSessionDelete(deleteOptions);
+ opened = undefined;
+ opening = undefined;
+ persisted = null;
+ requiring = undefined;
+ },
+ async get() {
+ await requireHandle();
+ return opened?.sandbox ?? null;
+ },
+ async stop() {
+ const current = await requireHandle();
+ await current.onSessionStop();
+ opened = undefined;
+ opening = undefined;
+ requiring = undefined;
+ },
+ };
}
diff --git a/packages/eve/src/execution/sandbox/lazy-backend.ts b/packages/eve/src/execution/sandbox/lazy-backend.ts
deleted file mode 100644
index 0ad934e60..000000000
--- a/packages/eve/src/execution/sandbox/lazy-backend.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
-
-/**
- * Wraps a backend-producing function in a `SandboxBackend` proxy that
- * invokes the function exactly once, on first access to any of `.name`,
- * `.create`, or `.prewarm`. Subsequent accesses return the same cached
- * underlying backend.
- *
- * Used by `defaultSandbox()` for env-conditional selection, and by the
- * authored-definition normalizer when an author passes a callback to
- * `SandboxDefinition.backend` (e.g. `backend: () => vercel({...})`)
- * so the factory runs at first use rather than at module load — while
- * still preserving backend-internal state (such as the Vercel backend's
- * prewarmed-templates map) across every framework call.
- */
-export function lazyBackend<BO, SO>(factory: () => SandboxBackend<BO, SO>): SandboxBackend<BO, SO> {
- let resolved: SandboxBackend<BO, SO> | undefined;
-
- function resolve(): SandboxBackend<BO, SO> {
- if (resolved === undefined) {
- resolved = factory();
- }
- return resolved;
- }
-
- return {
- get name() {
- return resolve().name;
- },
- create(input) {
- return resolve().create(input);
- },
- prewarm(input) {
- return resolve().prewarm(input);
- },
- };
-}
diff --git a/packages/eve/src/execution/sandbox/logging-session.test.ts b/packages/eve/src/execution/sandbox/logging-session.test.ts
index 18ff9515e..d2c8ae914 100644
--- a/packages/eve/src/execution/sandbox/logging-session.test.ts
+++ b/packages/eve/src/execution/sandbox/logging-session.test.ts
@@ -5,7 +5,7 @@ import { MAX_OUTPUT_LINES } from "#execution/sandbox/truncate-output.js";
import type { SandboxSession } from "#shared/sandbox-session.js";
describe("createLoggingSandboxSession", () => {
- it("logs bootstrap commands and file operations without logging contents", async () => {
+ it("logs preparation commands and file operations without logging contents", async () => {
const log = vi.fn();
const session = createTestSession();
const wrapped = createLoggingSandboxSession({ log, session });
@@ -16,10 +16,10 @@ describe("createLoggingSandboxSession", () => {
await wrapped.removePath({ path: "old.txt" });
expect(log.mock.calls.map((call) => call[0])).toEqual([
- "bootstrap run: echo secret-value",
- "bootstrap write text file: /workspace/config.txt (10 chars)",
- "bootstrap write binary file: asset.bin (3 bytes)",
- "bootstrap remove path: old.txt",
+ "preparation run: echo secret-value",
+ "preparation write text file: /workspace/config.txt (10 chars)",
+ "preparation write binary file: asset.bin (3 bytes)",
+ "preparation remove path: old.txt",
]);
expect(log.mock.calls.flat().join("\n")).not.toContain("do-not-log");
});
@@ -45,7 +45,7 @@ describe("createLoggingSandboxSession", () => {
],
},
};
- await wrapped.setNetworkPolicy(policy);
+ await wrapped.setNetworkPolicy?.(policy);
const message = log.mock.calls.flat().join("\n");
expect(message).toContain("api.github.com");
@@ -60,7 +60,7 @@ describe("createLoggingSandboxSession", () => {
expect(createLoggingSandboxSession({ session })).not.toBe(session);
});
- it("fails bootstrap when a run command exits with code 1", async () => {
+ it("fails preparation when a run command exits with code 1", async () => {
const session = createTestSession({
exitCode: 1,
stderr: "install failed\nmissing package\n",
@@ -70,7 +70,7 @@ describe("createLoggingSandboxSession", () => {
await expect(wrapped.run({ command: "pnpm install --frozen-lockfile" })).rejects.toThrow(
[
- "Sandbox bootstrap failed because sandbox.run command exited with code 1:",
+ "Sandbox preparation failed because sandbox.run command exited with code 1:",
"pnpm install --frozen-lockfile",
"",
"stdout:",
@@ -82,7 +82,7 @@ describe("createLoggingSandboxSession", () => {
);
});
- it("truncates bootstrap failure stdout and stderr", async () => {
+ it("truncates preparation failure stdout and stderr", async () => {
const stdout = Array.from({ length: MAX_OUTPUT_LINES + 2 }, (_, i) => `stdout ${i + 1}`).join(
"\n",
);
@@ -120,7 +120,6 @@ describe("createLoggingSandboxSession", () => {
function createTestSession(runResult = { exitCode: 0, stderr: "", stdout: "" }): SandboxSession {
return {
- id: "test-session",
resolvePath: (path) => (path.startsWith("/") ? path : `/workspace/${path}`),
run: vi.fn(async () => runResult),
spawn: vi.fn(async () => ({
diff --git a/packages/eve/src/execution/sandbox/logging-session.ts b/packages/eve/src/execution/sandbox/logging-session.ts
index 760f4cf96..3e6cea880 100644
--- a/packages/eve/src/execution/sandbox/logging-session.ts
+++ b/packages/eve/src/execution/sandbox/logging-session.ts
@@ -11,7 +11,7 @@ import type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";
import { truncateTail } from "#execution/sandbox/truncate-output.js";
const MAX_LOG_VALUE_LENGTH = 240;
-const BOOTSTRAP_FAILURE_EXIT_CODE = 1;
+const PREPARATION_FAILURE_EXIT_CODE = 1;
export function createLoggingSandboxSession(input: {
readonly log?: (message: string) => void;
@@ -22,46 +22,50 @@ export function createLoggingSandboxSession(input: {
return {
...session,
async run(options: SandboxRunOptions) {
- log?.(`bootstrap run: ${formatCommand(options.command)}`);
+ log?.(`preparation run: ${formatCommand(options.command)}`);
const result = await session.run(options);
- if (result.exitCode === BOOTSTRAP_FAILURE_EXIT_CODE) {
- throw new Error(formatBootstrapRunFailure(options.command, result));
+ if (result.exitCode === PREPARATION_FAILURE_EXIT_CODE) {
+ throw new Error(formatPreparationRunFailure(options.command, result));
}
return result;
},
async spawn(options: SandboxSpawnOptions) {
- log?.(`bootstrap spawn: ${formatCommand(options.command)}`);
+ log?.(`preparation spawn: ${formatCommand(options.command)}`);
return await session.spawn(options);
},
- async setNetworkPolicy(policy: SandboxNetworkPolicy) {
- log?.(`bootstrap set network policy: ${formatNetworkPolicy(policy)}`);
- return await session.setNetworkPolicy(policy);
- },
+ ...(session.setNetworkPolicy === undefined
+ ? {}
+ : {
+ async setNetworkPolicy(policy: SandboxNetworkPolicy) {
+ log?.(`preparation set network policy: ${formatNetworkPolicy(policy)}`);
+ return await session.setNetworkPolicy!(policy);
+ },
+ }),
async writeFile(options: SandboxWriteFileOptions) {
- log?.(`bootstrap write file: ${options.path}`);
+ log?.(`preparation write file: ${options.path}`);
return await session.writeFile(options);
},
async writeBinaryFile(options: SandboxWriteBinaryFileOptions) {
- log?.(`bootstrap write binary file: ${options.path} (${options.content.byteLength} bytes)`);
+ log?.(`preparation write binary file: ${options.path} (${options.content.byteLength} bytes)`);
return await session.writeBinaryFile(options);
},
async writeTextFile(options: SandboxWriteTextFileOptions) {
- log?.(`bootstrap write text file: ${options.path} (${options.content.length} chars)`);
+ log?.(`preparation write text file: ${options.path} (${options.content.length} chars)`);
return await session.writeTextFile(options);
},
async removePath(options: SandboxRemovePathOptions) {
- log?.(`bootstrap remove path: ${options.path}`);
+ log?.(`preparation remove path: ${options.path}`);
return await session.removePath(options);
},
};
}
-function formatBootstrapRunFailure(
+function formatPreparationRunFailure(
command: string,
result: { readonly stderr: string; readonly stdout: string },
): string {
return [
- `Sandbox bootstrap failed because sandbox.run command exited with code ${BOOTSTRAP_FAILURE_EXIT_CODE}:`,
+ `Sandbox preparation failed because sandbox.run command exited with code ${PREPARATION_FAILURE_EXIT_CODE}:`,
command,
"",
"stdout:",
diff --git a/packages/eve/src/execution/sandbox/prewarm.scenario.test.ts b/packages/eve/src/execution/sandbox/prewarm.scenario.test.ts
index ca714cb1c..7b0352162 100644
--- a/packages/eve/src/execution/sandbox/prewarm.scenario.test.ts
+++ b/packages/eve/src/execution/sandbox/prewarm.scenario.test.ts
@@ -1,18 +1,12 @@
-import { mkdir, writeFile } from "node:fs/promises";
+import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
-import { compileAgent, compileAgentInWorkspace } from "#compiler/compile-agent.js";
+import { compileAgentInWorkspace } from "#compiler/compile-agent.js";
import { resolvePackageSourceFilePath } from "#internal/application/package.js";
-import { createDevelopmentNitroArtifactsConfig } from "#internal/nitro/host/artifacts-config.js";
-import { publishDevelopmentGeneration } from "#internal/nitro/development-generation.js";
-import { resolveNitroCompiledArtifactsSource } from "#internal/nitro/routes/runtime-artifacts.js";
import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";
-import type {
- SandboxBackendPrewarmInput,
- SandboxBackendPrewarmResult,
-} from "#public/definitions/sandbox-backend.js";
+import type { SandboxProviderPrepareContext } from "#shared/sandbox-provider.js";
import { prewarmAppSandboxes } from "#execution/sandbox/prewarm.js";
import { createDiskRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
@@ -24,11 +18,26 @@ describe("prewarmAppSandboxes", () => {
vi.unstubAllEnvs();
});
- it("loads workspace seeds from an invocation-owned compiler directory", async () => {
- vi.stubEnv("VERCEL", "1");
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_isolated_build_prewarm");
-
- const appRoot = await createScenarioAppRoot();
+ it("loads a Dockerfile from the stable authored root for isolated compiler artifacts", async () => {
+ const appRoot = await createScratchDirectory("eve-prewarm-authored-dockerfile-");
+ const agentRoot = join(appRoot, "agent");
+ await mkdir(join(agentRoot, "sandbox"), { recursive: true });
+ await writeFile(
+ join(appRoot, "package.json"),
+ JSON.stringify({ name: "dockerfile-prewarm-test", type: "module" }),
+ );
+ await writeFile(join(agentRoot, "agent.ts"), 'export default { model: "openai/gpt-5.4" };');
+ await writeFile(join(agentRoot, "instructions.md"), "Use the sandbox.");
+ await writeFile(join(agentRoot, "sandbox", "Dockerfile"), "FROM alpine:3.21\n");
+ await writeFile(
+ join(agentRoot, "sandbox", "sandbox.ts"),
+ [
+ 'import { defineSandbox } from "eve/sandbox";',
+ 'import { MicrosandboxSandbox } from "eve/sandbox/microsandbox";',
+ "export const environment = MicrosandboxSandbox.dockerfile();",
+ "export default defineSandbox(() => environment.open());",
+ ].join("\n"),
+ );
const compilerAppRoot = join(appRoot, ".eve", "builds", "isolated", "compiler");
await compileAgentInWorkspace({
artifactLocations: {
@@ -37,7 +46,7 @@ describe("prewarmAppSandboxes", () => {
},
startPath: appRoot,
});
- const events = createPrewarmEvents();
+ const dockerfilePaths: string[] = [];
await prewarmAppSandboxes({
appRoot,
@@ -47,481 +56,80 @@ describe("prewarmAppSandboxes", () => {
),
sandboxAppRoot: appRoot,
}),
- dispatch: createRecordingDispatch(events),
+ dispatch: async ({ context }) => {
+ await context.files.read("Dockerfile");
+ dockerfilePaths.push(join(agentRoot, "sandbox", "Dockerfile"));
+ return { imageReference: "registry.example/eve@sha256:test" };
+ },
});
- expect(events.seededTemplateCount).toBe(2);
- expect([...events.seededFilePaths].sort()).toEqual([
- "$HOME/.agents/skills/research/SKILL.md",
- "$HOME/.agents/skills/route-weather/SKILL.md",
- ]);
- });
-
- it("prewarms the root and subagent sandbox templates with per-agent skill seeds", async () => {
- // Per-sandbox backend resolution falls back to defaultSandbox() when
- // an authored sandbox does not declare `backend`. Mark this process
- // as running on Vercel so the test sandboxes resolve to a backend
- // whose `prewarm` is called by the orchestrator.
- vi.stubEnv("VERCEL", "1");
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_execution_seed_prewarm");
-
- const appRoot = await createScenarioAppRoot();
- const events = createPrewarmEvents();
-
- await compileAgent({
- startPath: appRoot,
- });
- await prewarmAppSandboxes({
- appRoot,
- dispatch: createRecordingDispatch(events),
+ expect(dockerfilePaths).toEqual([join(agentRoot, "sandbox", "Dockerfile")]);
+ const preparedManifest = JSON.parse(
+ await readFile(
+ join(compilerAppRoot, ".eve", "compile", "sandbox-prepared-artifacts.json"),
+ "utf8",
+ ),
+ );
+ expect(preparedManifest).toMatchObject({
+ entries: [
+ {
+ artifact: { imageReference: "registry.example/eve@sha256:test" },
+ nodeId: "__root__",
+ providerName: "microsandbox",
+ },
+ ],
+ kind: "eve-sandbox-prepared-artifacts",
+ version: 2,
});
-
- // Two authored sandboxes (root + subagent), each receiving only
- // the skills authored on that agent.
- expect(events.templateKeys).toHaveLength(2);
- expect(events.seededTemplateCount).toBe(2);
- expect([...events.seededFilePaths].sort()).toEqual([
- "$HOME/.agents/skills/research/SKILL.md",
- "$HOME/.agents/skills/route-weather/SKILL.md",
- ]);
- expect([...events.bootstrapCommands].sort()).toEqual([
- "echo child-bootstrap",
- "echo root-bootstrap",
- ]);
});
- it("prewarms dev runtime snapshots with per-agent skill seeds", async () => {
+ it("loads workspace seeds from an invocation-owned compiler directory", async () => {
vi.stubEnv("VERCEL", "1");
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_execution_dev_seed_prewarm");
+ vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_isolated_build_prewarm");
const appRoot = await createScenarioAppRoot();
- const events = createPrewarmEvents();
- const compileResult = await compileAgent({
+ const compilerAppRoot = join(appRoot, ".eve", "builds", "isolated", "compiler");
+ await compileAgentInWorkspace({
+ artifactLocations: {
+ publishedRoot: join(compilerAppRoot, ".eve"),
+ writeRoot: join(compilerAppRoot, ".eve"),
+ },
startPath: appRoot,
});
- await publishDevelopmentGeneration(compileResult);
+ const events = createPrewarmEvents();
await prewarmAppSandboxes({
appRoot,
- compiledArtifactsSource: resolveNitroCompiledArtifactsSource(
- createDevelopmentNitroArtifactsConfig({ appRoot }),
- ),
+ compiledArtifactsSource: createDiskRuntimeCompiledArtifactsSource(compilerAppRoot, {
+ moduleMapLoaderPath: resolvePackageSourceFilePath(
+ "src/internal/authored-module-map-loader.ts",
+ ),
+ sandboxAppRoot: appRoot,
+ }),
dispatch: createRecordingDispatch(events),
});
- expect(events.templateKeys).toHaveLength(2);
- expect(new Set(events.runtimeContextAppRoots)).toEqual(new Set([appRoot]));
expect(events.seededTemplateCount).toBe(2);
expect([...events.seededFilePaths].sort()).toEqual([
"$HOME/.agents/skills/research/SKILL.md",
"$HOME/.agents/skills/route-weather/SKILL.md",
]);
});
-
- it("skips framework default sandbox templates when nodes have no seeds or bootstrap", async () => {
- vi.stubEnv("VERCEL", "1");
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_default_per_node");
-
- const appRoot = await createDefaultGraphAppRoot();
- const events = createPrewarmEvents();
-
- await compileAgent({
- startPath: appRoot,
- });
- await prewarmAppSandboxes({
- appRoot,
- dispatch: createRecordingDispatch(events),
- });
-
- expect(events.templateKeys).toHaveLength(0);
- });
-
- it("skips empty default subagent templates when only the root authors a sandbox", async () => {
- vi.stubEnv("VERCEL", "1");
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_root_authored_subagent_defaults");
-
- const appRoot = await createDefaultGraphAppRoot({
- rootSandbox: true,
- });
- const events = createPrewarmEvents();
-
- await compileAgent({
- startPath: appRoot,
- });
- await prewarmAppSandboxes({
- appRoot,
- dispatch: createRecordingDispatch(events),
- });
-
- expect(events.templateKeys).toHaveLength(1);
- expect([...events.bootstrapCommands]).toEqual(["echo root-bootstrap"]);
- });
-
- it("prewarms one template per node when every node authors a sandbox", async () => {
- vi.stubEnv("VERCEL", "1");
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_all_authored_sandboxes");
-
- const appRoot = await createDefaultGraphAppRoot({
- rootSandbox: true,
- subagentSandboxes: true,
- });
- const events = createPrewarmEvents();
-
- await compileAgent({
- startPath: appRoot,
- });
- await prewarmAppSandboxes({
- appRoot,
- dispatch: createRecordingDispatch(events),
- });
-
- expect(events.templateKeys).toHaveLength(4);
- expect(new Set(events.templateKeys)).toHaveLength(4);
- expect([...events.bootstrapCommands].sort()).toEqual([
- "echo alpha-bootstrap",
- "echo bravo-bootstrap",
- "echo charlie-bootstrap",
- "echo root-bootstrap",
- ]);
- });
-
- it("skips the single empty root framework default sandbox template", async () => {
- vi.stubEnv("VERCEL", "1");
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_single_default_root");
-
- const appRoot = await createDefaultGraphAppRoot({
- subagentNames: [],
- });
- const events = createPrewarmEvents();
-
- await compileAgent({
- startPath: appRoot,
- });
- await prewarmAppSandboxes({
- appRoot,
- dispatch: createRecordingDispatch(events),
- });
-
- expect(events.templateKeys).toHaveLength(0);
- });
-
- it("uses skill content to key seed-only sandbox templates across deploy roots", async () => {
- vi.stubEnv("VERCEL", "1");
- vi.stubEnv("VERCEL_PROJECT_ID", "prj_seed_only_templates");
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_seed_only_one");
-
- const firstAppRoot = await createSkillOnlyAppRoot({
- skillBody: "Route weather content.",
- });
- const firstEvents = createPrewarmEvents();
-
- await compileAgent({
- startPath: firstAppRoot,
- });
- await prewarmAppSandboxes({
- appRoot: firstAppRoot,
- dispatch: createRecordingDispatch(firstEvents),
- });
-
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_seed_only_two");
-
- const secondAppRoot = await createSkillOnlyAppRoot({
- skillBody: "Route weather content.",
- });
- const secondEvents = createPrewarmEvents();
-
- await compileAgent({
- startPath: secondAppRoot,
- });
- await prewarmAppSandboxes({
- appRoot: secondAppRoot,
- dispatch: createRecordingDispatch(secondEvents),
- });
-
- const changedAppRoot = await createSkillOnlyAppRoot({
- skillBody: "Changed route weather content.",
- });
- const changedEvents = createPrewarmEvents();
-
- await compileAgent({
- startPath: changedAppRoot,
- });
- await prewarmAppSandboxes({
- appRoot: changedAppRoot,
- dispatch: createRecordingDispatch(changedEvents),
- });
-
- expect(firstEvents.templateKeys).toHaveLength(1);
- expect(secondEvents.templateKeys).toEqual(firstEvents.templateKeys);
- expect(changedEvents.templateKeys[0]).not.toBe(firstEvents.templateKeys[0]);
- expect(firstEvents.seededFilePaths).toEqual(["$HOME/.agents/skills/route-weather/SKILL.md"]);
- });
-
- it("uses compiled bootstrap revalidation keys across deploy roots without re-evaluating at prewarm", async () => {
- vi.stubEnv("VERCEL", "1");
- vi.stubEnv("VERCEL_PROJECT_ID", "prj_bootstrap_templates");
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_bootstrap_one");
-
- const firstAppRoot = await createBootstrapRevalidationKeyAppRoot({
- revalidationKeyExpression: '() => "bootstrap-revalidation-v1"',
- skillBody: "Route weather content.",
- });
- const firstEvents = createPrewarmEvents();
-
- await compileAgent({
- startPath: firstAppRoot,
- });
- await writeBootstrapRevalidationKeySandbox({
- appRoot: firstAppRoot,
- revalidationKeyExpression:
- '() => { throw new Error("revalidationKey should not run during prewarm"); }',
- });
- await prewarmAppSandboxes({
- appRoot: firstAppRoot,
- dispatch: createRecordingDispatch(firstEvents),
- });
-
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_bootstrap_two");
-
- const secondAppRoot = await createBootstrapRevalidationKeyAppRoot({
- revalidationKeyExpression: '() => "bootstrap-revalidation-v1"',
- skillBody: "Route weather content.",
- });
- const secondEvents = createPrewarmEvents();
-
- await compileAgent({
- startPath: secondAppRoot,
- });
- await prewarmAppSandboxes({
- appRoot: secondAppRoot,
- dispatch: createRecordingDispatch(secondEvents),
- });
-
- const changedKeyAppRoot = await createBootstrapRevalidationKeyAppRoot({
- revalidationKeyExpression: '() => "bootstrap-revalidation-v2"',
- skillBody: "Route weather content.",
- });
- const changedKeyEvents = createPrewarmEvents();
-
- await compileAgent({
- startPath: changedKeyAppRoot,
- });
- await prewarmAppSandboxes({
- appRoot: changedKeyAppRoot,
- dispatch: createRecordingDispatch(changedKeyEvents),
- });
-
- const changedSeedAppRoot = await createBootstrapRevalidationKeyAppRoot({
- revalidationKeyExpression: '() => "bootstrap-revalidation-v1"',
- skillBody: "Changed route weather content.",
- });
- const changedSeedEvents = createPrewarmEvents();
-
- await compileAgent({
- startPath: changedSeedAppRoot,
- });
- await prewarmAppSandboxes({
- appRoot: changedSeedAppRoot,
- dispatch: createRecordingDispatch(changedSeedEvents),
- });
-
- const changedSourceAppRoot = await createBootstrapRevalidationKeyAppRoot({
- bootstrapCommand: "echo bootstrap-revalidation-key-changed-source",
- revalidationKeyExpression: '() => "bootstrap-revalidation-v1"',
- skillBody: "Route weather content.",
- });
- const changedSourceEvents = createPrewarmEvents();
-
- await compileAgent({
- startPath: changedSourceAppRoot,
- });
- await prewarmAppSandboxes({
- appRoot: changedSourceAppRoot,
- dispatch: createRecordingDispatch(changedSourceEvents),
- });
-
- expect(firstEvents.templateKeys).toHaveLength(1);
- expect(secondEvents.templateKeys).toEqual(firstEvents.templateKeys);
- expect(changedKeyEvents.templateKeys[0]).not.toBe(firstEvents.templateKeys[0]);
- expect(changedSeedEvents.templateKeys[0]).not.toBe(firstEvents.templateKeys[0]);
- expect(changedSourceEvents.templateKeys[0]).not.toBe(firstEvents.templateKeys[0]);
- expect(firstEvents.bootstrapCommands).toEqual(["echo bootstrap-revalidation-key"]);
- });
-
- it("keeps unseeded bootstrap templates stable across deploy roots and instruction changes", async () => {
- vi.stubEnv("VERCEL", "1");
- vi.stubEnv("VERCEL_PROJECT_ID", "prj_bootstrap_templates");
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_bootstrap_empty_one");
-
- const firstAppRoot = await createBootstrapRevalidationKeyAppRoot({
- revalidationKeyExpression: undefined,
- });
- const firstEvents = createPrewarmEvents();
- const first = await compileAgent({ startPath: firstAppRoot });
- await prewarmAppSandboxes({
- appRoot: firstAppRoot,
- dispatch: createRecordingDispatch(firstEvents),
- });
-
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_bootstrap_empty_two");
- const secondAppRoot = await createBootstrapRevalidationKeyAppRoot({
- revalidationKeyExpression: undefined,
- });
- await writeFile(join(secondAppRoot, "agent", "instructions.md"), "Changed system prompt.\n");
- const secondEvents = createPrewarmEvents();
- const second = await compileAgent({ startPath: secondAppRoot });
- await prewarmAppSandboxes({
- appRoot: secondAppRoot,
- dispatch: createRecordingDispatch(secondEvents),
- });
-
- expect(first.manifest.workspaceResourceRoot.contentHash).toBeUndefined();
- expect(second.manifest.workspaceResourceRoot.contentHash).toBeUndefined();
- expect(second.metadata.discovery.sourceGraphHash).not.toBe(
- first.metadata.discovery.sourceGraphHash,
- );
- expect(firstEvents.templateKeys).toHaveLength(1);
- expect(secondEvents.templateKeys).toEqual(firstEvents.templateKeys);
- expect(firstEvents.seededFilePaths).toEqual([]);
- expect(secondEvents.seededFilePaths).toEqual([]);
- });
-
- it("uses authored sandbox source when bootstrap omits revalidationKey", async () => {
- vi.stubEnv("VERCEL", "1");
- vi.stubEnv("VERCEL_PROJECT_ID", "prj_bootstrap_templates");
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_bootstrap_no_key_one");
-
- const firstAppRoot = await createBootstrapRevalidationKeyAppRoot({
- revalidationKeyExpression: undefined,
- skillBody: "Route weather content.",
- });
- const firstEvents = createPrewarmEvents();
-
- await compileAgent({
- startPath: firstAppRoot,
- });
- await prewarmAppSandboxes({
- appRoot: firstAppRoot,
- dispatch: createRecordingDispatch(firstEvents),
- });
-
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_bootstrap_no_key_two");
-
- const secondAppRoot = await createBootstrapRevalidationKeyAppRoot({
- revalidationKeyExpression: undefined,
- skillBody: "Route weather content.",
- });
- const secondEvents = createPrewarmEvents();
-
- await compileAgent({
- startPath: secondAppRoot,
- });
- await prewarmAppSandboxes({
- appRoot: secondAppRoot,
- dispatch: createRecordingDispatch(secondEvents),
- });
-
- const changedSourceAppRoot = await createBootstrapRevalidationKeyAppRoot({
- bootstrapCommand: "echo bootstrap-without-revalidation-key-changed-source",
- revalidationKeyExpression: undefined,
- skillBody: "Route weather content.",
- });
- const changedSourceEvents = createPrewarmEvents();
-
- await compileAgent({
- startPath: changedSourceAppRoot,
- });
- await prewarmAppSandboxes({
- appRoot: changedSourceAppRoot,
- dispatch: createRecordingDispatch(changedSourceEvents),
- });
-
- expect(firstEvents.templateKeys).toHaveLength(1);
- expect(secondEvents.templateKeys).toEqual(firstEvents.templateKeys);
- expect(changedSourceEvents.templateKeys[0]).not.toBe(firstEvents.templateKeys[0]);
- expect(firstEvents.bootstrapCommands).toEqual(["echo bootstrap-revalidation-key"]);
- });
-
- it("authored default override produces a single prewarm target, not two", async () => {
- vi.stubEnv("VERCEL", "1");
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_authored_default_override");
-
- const appRoot = await createAuthoredOverrideAppRoot();
- const events = createPrewarmEvents();
- const log = vi.fn();
-
- await compileAgent({
- startPath: appRoot,
- });
- await prewarmAppSandboxes({
- appRoot,
- dispatch: createRecordingDispatch(events),
- log,
- });
-
- // Only one prewarm target for a single-node graph: the root
- // authored default.
- expect(events.templateKeys).toHaveLength(1);
- expect(log.mock.calls.map(([message]) => message)).toEqual([
- "eve: initializing 1 sandbox template...",
- "eve: initialized 1 sandbox template (0 reused, 1 built).",
- ]);
- expect(log).not.toHaveBeenCalledWith(expect.stringContaining("framework"));
- expect([...events.bootstrapCommands]).toEqual(["echo default-bootstrap"]);
- });
-
- it("does not report reused templates in the build log", async () => {
- vi.stubEnv("VERCEL", "1");
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_authored_default_reused");
-
- const appRoot = await createAuthoredOverrideAppRoot();
- const events = createPrewarmEvents();
- const log = vi.fn();
-
- await compileAgent({
- startPath: appRoot,
- });
- await prewarmAppSandboxes({
- appRoot,
- dispatch: createRecordingDispatch(events, { reused: true }),
- log,
- });
-
- expect(events.templateKeys).toHaveLength(1);
- expect(log).not.toHaveBeenCalledWith(expect.stringContaining("reused cached"));
- expect(log).not.toHaveBeenCalledWith(expect.stringContaining("built sandbox template"));
- });
-
- it("authored default override receives skill seed files in its single target", async () => {
- vi.stubEnv("VERCEL", "1");
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_authored_default_skills");
-
- const appRoot = await createAuthoredOverrideAppRoot({
- withSkills: true,
- });
- const events = createPrewarmEvents();
-
- await compileAgent({
- startPath: appRoot,
- });
- await prewarmAppSandboxes({
- appRoot,
- dispatch: createRecordingDispatch(events),
- });
-
- // Still only one target — the authored default with skill seeds merged in.
- expect(events.templateKeys).toHaveLength(1);
- expect(events.seededTemplateCount).toBe(1);
- expect([...events.seededFilePaths].sort()).toEqual(
- [
- "$HOME/.agents/skills/route-weather/SKILL.md",
- "$HOME/.agents/skills/route-weather/references/checklist.md",
- ].sort(),
- );
- expect([...events.bootstrapCommands]).toEqual(["echo default-bootstrap"]);
- });
});
+function preparedSandboxSource(command: string): string {
+ return [
+ 'import { DefaultSandbox, defineSandbox } from "eve/sandbox";',
+ "export const environment = DefaultSandbox.environment({",
+ " prepare: async (sandbox) => {",
+ ` await sandbox.run({ command: ${JSON.stringify(command)} });`,
+ " },",
+ "});",
+ "export default defineSandbox(() => environment.open());",
+ "",
+ ].join("\n");
+}
+
async function createScenarioAppRoot(): Promise<string> {
const appRoot = await createScratchDirectory("eve-prewarm-");
const agentRoot = join(appRoot, "agent");
@@ -559,19 +167,7 @@ async function createScenarioAppRoot(): Promise<string> {
);
await writeFile(
join(agentRoot, "sandbox", "sandbox.ts"),
- [
- "export default {",
- ' revalidationKey: () => "root-bootstrap-v1",',
- " async bootstrap({ use }) {",
- " const sandbox = await use();",
- ' await sandbox.run({ command: "echo root-bootstrap" });',
- " },",
- " onSession() {",
- ' throw new Error("root onSession should not run during build prewarm");',
- " },",
- "};",
- "",
- ].join("\n"),
+ preparedSandboxSource("echo root-prepare"),
);
await writeFile(
join(subagentRoot, "agent.ts"),
@@ -590,345 +186,39 @@ async function createScenarioAppRoot(): Promise<string> {
);
await writeFile(
join(subagentRoot, "sandbox", "sandbox.ts"),
- [
- "export default {",
- ' revalidationKey: () => "child-bootstrap-v1",',
- " async bootstrap({ use }) {",
- " const sandbox = await use();",
- ' await sandbox.run({ command: "echo child-bootstrap" });',
- " },",
- " onSession() {",
- ' throw new Error("child onSession should not run during build prewarm");',
- " },",
- "};",
- "",
- ].join("\n"),
- );
-
- return appRoot;
-}
-
-async function createDefaultGraphAppRoot(
- input: {
- readonly rootSandbox?: boolean;
- readonly subagentSandboxes?: boolean;
- readonly subagentNames?: readonly string[];
- } = {},
-): Promise<string> {
- const appRoot = await createScratchDirectory("eve-prewarm-graph-");
- const agentRoot = join(appRoot, "agent");
- const subagentNames = input.subagentNames ?? ["alpha", "bravo", "charlie"];
-
- await mkdir(agentRoot, {
- recursive: true,
- });
-
- await writeFile(
- join(appRoot, "package.json"),
- JSON.stringify(
- {
- name: "execution-sandbox-prewarm-default-graph-test",
- type: "module",
- },
- null,
- 2,
- ),
- );
- await writeFile(join(agentRoot, "agent.ts"), 'export default { model: "openai/gpt-5.4" };\n');
- await writeFile(join(agentRoot, "instructions.md"), "Root system prompt.\n");
-
- if (input.rootSandbox === true) {
- await mkdir(join(agentRoot, "sandbox"), {
- recursive: true,
- });
- await writeFile(
- join(agentRoot, "sandbox", "sandbox.ts"),
- [
- "export default {",
- ' revalidationKey: () => "root-bootstrap-v1",',
- " async bootstrap({ use }) {",
- " const sandbox = await use();",
- ' await sandbox.run({ command: "echo root-bootstrap" });',
- " },",
- "};",
- "",
- ].join("\n"),
- );
- }
-
- for (const name of subagentNames) {
- const subagentRoot = join(agentRoot, "subagents", name);
- await mkdir(subagentRoot, {
- recursive: true,
- });
- await writeFile(
- join(subagentRoot, "agent.ts"),
- [
- "export default {",
- ' model: "openai/gpt-5.4",',
- ` description: "Handle ${name} tasks.",`,
- "};",
- "",
- ].join("\n"),
- );
- await writeFile(join(subagentRoot, "instructions.md"), `${name} system prompt.\n`);
-
- if (input.subagentSandboxes === true) {
- await mkdir(join(subagentRoot, "sandbox"), {
- recursive: true,
- });
- await writeFile(
- join(subagentRoot, "sandbox", "sandbox.ts"),
- [
- "export default {",
- ` revalidationKey: () => "${name}-bootstrap-v1",`,
- " async bootstrap({ use }) {",
- " const sandbox = await use();",
- ` await sandbox.run({ command: "echo ${name}-bootstrap" });`,
- " },",
- "};",
- "",
- ].join("\n"),
- );
- }
- }
-
- return appRoot;
-}
-
-async function createAuthoredOverrideAppRoot(
- input: { readonly withSkills?: boolean } = {},
-): Promise<string> {
- const appRoot = await createScratchDirectory("eve-prewarm-override-");
- const agentRoot = join(appRoot, "agent");
-
- await mkdir(join(agentRoot, "sandbox"), {
- recursive: true,
- });
-
- if (input.withSkills) {
- await mkdir(join(agentRoot, "skills"), {
- recursive: true,
- });
- }
-
- await writeFile(
- join(appRoot, "package.json"),
- JSON.stringify(
- {
- name: "execution-sandbox-prewarm-default-override-test",
- type: "module",
- },
- null,
- 2,
- ),
- );
- await writeFile(join(agentRoot, "agent.ts"), 'export default { model: "openai/gpt-5.4" };\n');
- await writeFile(join(agentRoot, "instructions.md"), "Root system prompt.\n");
- await writeFile(
- join(agentRoot, "sandbox", "sandbox.ts"),
- [
- "export default {",
- ' revalidationKey: () => "default-bootstrap-v1",',
- " async bootstrap({ use }) {",
- " const sandbox = await use();",
- ' await sandbox.run({ command: "echo default-bootstrap" });',
- " },",
- " onSession() {",
- ' throw new Error("onSession should not run during build prewarm");',
- " },",
- "};",
- "",
- ].join("\n"),
+ preparedSandboxSource("echo child-prepare"),
);
- if (input.withSkills) {
- await writeFile(
- join(agentRoot, "skills", "route-weather.mjs"),
- [
- "export default {",
- ' description: "Route weather requests.",',
- ' markdown: "Route weather content.",',
- ' files: { "references/checklist.md": "Check the forecast source.\\n" },',
- "};",
- "",
- ].join("\n"),
- );
- }
-
return appRoot;
}
-async function createSkillOnlyAppRoot(input: { readonly skillBody: string }): Promise<string> {
- const appRoot = await createScratchDirectory("eve-prewarm-skill-only-");
- const agentRoot = join(appRoot, "agent");
-
- await mkdir(join(agentRoot, "skills"), {
- recursive: true,
- });
- await writeFile(
- join(appRoot, "package.json"),
- JSON.stringify(
- {
- name: "execution-sandbox-prewarm-skill-only-test",
- type: "module",
- },
- null,
- 2,
- ),
- );
- await writeFile(join(agentRoot, "agent.ts"), 'export default { model: "openai/gpt-5.4" };\n');
- await writeFile(join(agentRoot, "instructions.md"), "Root system prompt.\n");
- await writeFile(
- join(agentRoot, "skills", "route-weather.md"),
- ["---", "description: Route weather requests.", "---", input.skillBody].join("\n"),
- );
-
- return appRoot;
-}
-
-async function createBootstrapRevalidationKeyAppRoot(input: {
- readonly bootstrapCommand?: string;
- readonly revalidationKeyExpression: string | undefined;
- readonly skillBody?: string;
-}): Promise<string> {
- const appRoot = await createScratchDirectory("eve-prewarm-bootstrap-revalidation-key-");
- const agentRoot = join(appRoot, "agent");
-
- await mkdir(join(agentRoot, "sandbox"), {
- recursive: true,
- });
- await writeFile(
- join(appRoot, "package.json"),
- JSON.stringify(
- {
- name: "execution-sandbox-prewarm-bootstrap-revalidation-key-test",
- type: "module",
- },
- null,
- 2,
- ),
- );
- await writeFile(join(agentRoot, "agent.ts"), 'export default { model: "openai/gpt-5.4" };\n');
- await writeFile(join(agentRoot, "instructions.md"), "Root system prompt.\n");
- if (input.skillBody !== undefined) {
- await mkdir(join(agentRoot, "skills"), { recursive: true });
- await writeFile(
- join(agentRoot, "skills", "route-weather.md"),
- ["---", "description: Route weather requests.", "---", input.skillBody].join("\n"),
- );
- }
- await writeBootstrapRevalidationKeySandbox({
- appRoot,
- bootstrapCommand: input.bootstrapCommand,
- revalidationKeyExpression: input.revalidationKeyExpression,
- });
-
- return appRoot;
-}
-
-async function writeBootstrapRevalidationKeySandbox(input: {
- readonly appRoot: string;
- readonly bootstrapCommand?: string;
- readonly revalidationKeyExpression: string | undefined;
-}): Promise<void> {
- const bootstrapCommand = input.bootstrapCommand ?? "echo bootstrap-revalidation-key";
- const revalidationKeyLine =
- input.revalidationKeyExpression === undefined
- ? []
- : [` revalidationKey: ${input.revalidationKeyExpression},`];
- await writeFile(
- join(input.appRoot, "agent", "sandbox", "sandbox.ts"),
- [
- "export default {",
- ...revalidationKeyLine,
- " async bootstrap({ use }) {",
- " const sandbox = await use();",
- ` await sandbox.run({ command: ${JSON.stringify(bootstrapCommand)} });`,
- " },",
- "};",
- "",
- ].join("\n"),
- );
-}
-
-function createRecordingDispatch(
- events: ReturnType<typeof createPrewarmEvents>,
- options: { readonly reused?: boolean } = {},
-) {
- return async ({
- input,
- }: {
- input: SandboxBackendPrewarmInput;
- }): Promise<SandboxBackendPrewarmResult> => {
- events.templateKeys.push(input.templateKey);
- events.runtimeContextAppRoots.push(input.runtimeContext.appRoot);
-
- const seedFiles = input.seedFiles ?? [];
- if (seedFiles.length > 0) {
+function createRecordingDispatch(events: ReturnType<typeof createPrewarmEvents>) {
+ return async ({ context }: { context: SandboxProviderPrepareContext }) => {
+ events.templateKeys.push(context.storagePath);
+ events.runtimeContextAppRoots.push(context.storagePath);
+
+ const resourceFiles = [
+ ...(context.resources.workspace?.files.map((file) => ({
+ ...file,
+ path: `${context.resources.workspace?.targetPath}/${file.relativePath}`,
+ })) ?? []),
+ ...(context.resources.skills?.files.map((file) => ({
+ ...file,
+ path: `${context.resources.skills?.targetPath}/${file.relativePath}`,
+ })) ?? []),
+ ];
+ if (resourceFiles.length > 0) {
events.seededTemplateCount += 1;
- events.seededFilePaths.push(...seedFiles.map((file) => file.path));
- }
-
- if (input.bootstrap !== undefined) {
- await input.bootstrap({
- use: async () => ({
- id: "test-prewarm-session",
- async readFile() {
- return null;
- },
- async readBinaryFile() {
- return null;
- },
- async readTextFile() {
- return null;
- },
- async setNetworkPolicy() {},
- async removePath() {},
- resolvePath(path: string) {
- return path;
- },
- async run({ command }: { command: string }) {
- events.bootstrapCommands.push(command);
- return {
- exitCode: 0,
- stderr: "",
- stdout: "",
- };
- },
- async spawn({ command }: { command: string }) {
- events.bootstrapCommands.push(command);
- return {
- stdout: new ReadableStream<Uint8Array>({
- start(controller) {
- controller.close();
- },
- }),
- stderr: new ReadableStream<Uint8Array>({
- start(controller) {
- controller.close();
- },
- }),
- async wait() {
- return { exitCode: 0 };
- },
- async kill() {},
- };
- },
- async writeFile() {},
- async writeBinaryFile() {},
- async writeTextFile() {},
- }),
- });
+ events.seededFilePaths.push(...resourceFiles.map((file) => file.path));
}
- return { reused: options.reused ?? false };
+ return { storagePath: context.storagePath };
};
}
function createPrewarmEvents() {
return {
- bootstrapCommands: [] as string[],
+ preparationCommands: [] as string[],
runtimeContextAppRoots: [] as string[],
seededFilePaths: [] as string[],
seededTemplateCount: 0,
diff --git a/packages/eve/src/execution/sandbox/prewarm.test.ts b/packages/eve/src/execution/sandbox/prewarm.test.ts
index 9f4338792..d176f5362 100644
--- a/packages/eve/src/execution/sandbox/prewarm.test.ts
+++ b/packages/eve/src/execution/sandbox/prewarm.test.ts
@@ -1,19 +1,19 @@
import { afterEach, describe, expect, it, vi } from "vitest";
-import { prewarmAppSandboxes } from "#execution/sandbox/prewarm.js";
-import type {
- SandboxBackend,
- SandboxBackendPrewarmInput,
- SandboxBackendPrewarmResult,
-} from "#public/definitions/sandbox-backend.js";
+import {
+ prewarmAppSandboxes,
+ type SandboxPreparedArtifactStore,
+} from "#execution/sandbox/prewarm.js";
+import {
+ defineSandboxProvider,
+ type SandboxProviderPrepareContext,
+} from "#shared/sandbox-provider.js";
import { createDiskRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import { ROOT_RUNTIME_AGENT_NODE_ID, type ResolvedAgentGraphBundle } from "#runtime/graph.js";
import type { ResolvedSandboxDefinition } from "#runtime/types.js";
+import { defineSandbox } from "#public/definitions/sandbox.js";
+import { resolveSandboxCacheDirectory } from "#internal/application/paths.js";
-vi.mock("#execution/sandbox/template-prewarm-lock.js", () => ({
- withSandboxTemplatePrewarmLock: async (_input: unknown, callback: () => Promise<unknown>) =>
- await callback(),
-}));
const mocks = vi.hoisted(() => ({
materializeWorkspaceDirectory: vi.fn<
(path: string) => Promise<readonly { readonly content: Buffer; readonly path: string }[]>
@@ -35,8 +35,8 @@ describe("prewarmAppSandboxes", () => {
const appRoot = process.cwd();
const firstSnapshotRoot = `${appRoot}/.eve/dev-runtime/snapshots/one/app`;
const secondSnapshotRoot = `${appRoot}/.eve/dev-runtime/snapshots/two/app`;
- const firstInputs: SandboxBackendPrewarmInput[] = [];
- const secondInputs: SandboxBackendPrewarmInput[] = [];
+ const firstInputs: SandboxProviderPrepareContext[] = [];
+ const secondInputs: SandboxProviderPrepareContext[] = [];
const workspaceResourceRoot = {
contentHash: "workspace-content-hash",
logicalPath: "empty-resource-root",
@@ -51,6 +51,7 @@ describe("prewarmAppSandboxes", () => {
}),
dispatch: recordPrewarmInputs(firstInputs),
loadAgentGraph: async () => createGraph({ workspaceResourceRoot }),
+ preparedArtifactStore: createMemoryArtifactStore(),
});
await prewarmAppSandboxes({
appRoot,
@@ -60,42 +61,24 @@ describe("prewarmAppSandboxes", () => {
}),
dispatch: recordPrewarmInputs(secondInputs),
loadAgentGraph: async () => createGraph({ workspaceResourceRoot }),
+ preparedArtifactStore: createMemoryArtifactStore(),
});
expect(firstInputs).toHaveLength(1);
expect(secondInputs).toHaveLength(1);
- expect(firstInputs[0]?.runtimeContext.appRoot).toBe(appRoot);
- expect(secondInputs[0]?.runtimeContext.appRoot).toBe(appRoot);
- expect(firstInputs[0]?.templateKey).toBe(secondInputs[0]?.templateKey);
- });
-
- it("skips backend prewarm when the sandbox signature is already warm", async () => {
- const appRoot = process.cwd();
- const inputs: SandboxBackendPrewarmInput[] = [];
- const signatures: string[] = [];
-
- await prewarmAppSandboxes({
- appRoot,
- compiledArtifactsSource: createDiskRuntimeCompiledArtifactsSource(appRoot),
- dispatch: recordPrewarmInputs(inputs),
- loadAgentGraph: async () => createGraph(),
- shouldPrewarmSignature: (signature) => {
- signatures.push(signature);
- return false;
- },
- });
-
- expect(inputs).toHaveLength(0);
- expect(signatures).toHaveLength(1);
+ expect(firstInputs[0]?.storagePath).toBe(resolveSandboxCacheDirectory(appRoot));
+ expect(secondInputs[0]?.storagePath).toBe(resolveSandboxCacheDirectory(appRoot));
+ expect(firstInputs[0]?.sourceRevision).toBe("sandbox-source-hash");
+ expect(secondInputs[0]?.sourceRevision).toBe("sandbox-source-hash");
});
it.each(["docker", "microsandbox"])(
"explains that %s is unavailable during Vercel prewarm",
- async (backendName) => {
+ async (providerName) => {
vi.stubEnv("VERCEL", "1");
const appRoot = process.cwd();
- const cause = new Error("backend host check failed");
+ const cause = new Error("provider host check failed");
const log = vi.fn();
await expect(
@@ -105,13 +88,13 @@ describe("prewarmAppSandboxes", () => {
dispatch: async () => {
throw cause;
},
- loadAgentGraph: async () => createGraph({ backendName }),
+ loadAgentGraph: async () => createGraph({ providerName }),
log,
}),
).rejects.toMatchObject({
cause,
message: expect.stringContaining(
- `The ${backendName} sandbox backend is not available when deploying on Vercel.`,
+ `The ${providerName} sandbox provider is not available when deploying on Vercel.`,
),
});
@@ -119,32 +102,31 @@ describe("prewarmAppSandboxes", () => {
expect(messages).toEqual([
"eve: initializing 1 sandbox template...",
expect.stringContaining(
- `The ${backendName} sandbox backend is not available when deploying on Vercel.`,
+ `The ${providerName} sandbox provider is not available when deploying on Vercel.`,
),
]);
- expect(messages[1]).toContain("Use defaultBackend()");
- expect(messages[1]).toContain("Vercel-compatible backend explicitly, such as vercel()");
+ expect(messages[1]).toContain("Use DefaultSandbox.environment()");
+ expect(messages[1]).toContain("VercelSandbox.environment() explicitly");
expect(messages[1]).toContain("Original");
expect(messages[1]).toContain(cause.message);
},
);
});
-function recordPrewarmInputs(inputs: SandboxBackendPrewarmInput[]) {
- return async ({
- input,
- }: {
- backend: SandboxBackend;
- input: SandboxBackendPrewarmInput;
- }): Promise<SandboxBackendPrewarmResult> => {
- inputs.push(input);
- return { reused: true };
+function createMemoryArtifactStore(): SandboxPreparedArtifactStore {
+ return { async write() {} };
+}
+
+function recordPrewarmInputs(inputs: SandboxProviderPrepareContext[]) {
+ return async ({ context }: { context: SandboxProviderPrepareContext }) => {
+ inputs.push(context);
+ return null;
};
}
function createGraph(
input: {
- readonly backendName?: string;
+ readonly providerName?: string;
readonly workspaceResourceRoot?: {
readonly contentHash?: string;
readonly logicalPath: string;
@@ -152,25 +134,32 @@ function createGraph(
};
} = {},
): ResolvedAgentGraphBundle {
- const backend: SandboxBackend = {
- async create() {
- throw new Error("Unexpected create call.");
- },
- name: input.backendName ?? "test",
- async prewarm() {
- return { reused: true };
- },
- };
+ const provider = defineSandboxProvider({
+ name: input.providerName ?? "test",
+ environment: () => ({
+ async prepare() {
+ return null;
+ },
+ async resume() {
+ throw new Error("Unexpected resume call.");
+ },
+ async start() {
+ throw new Error("Unexpected start call.");
+ },
+ }),
+ });
+ const environment = provider.environment();
const definition: ResolvedSandboxDefinition = {
- async bootstrap() {},
- backend,
+ environment,
+ kind: "independent",
logicalPath: "agent/sandbox/sandbox.ts",
- revalidationKey: "stable-bootstrap",
- sourceHash: "sandbox-source-hash",
+ selector: defineSandbox(() => environment.open()),
+ revisionHash: "sandbox-source-hash",
sourceId: "agent/sandbox/sandbox",
sourceKind: "module",
};
const root = {
+ agent: { metadata: { agentRoot: process.cwd(), appRoot: process.cwd() } },
nodeId: ROOT_RUNTIME_AGENT_NODE_ID,
sandboxRegistry: {
sandbox: {
diff --git a/packages/eve/src/execution/sandbox/prewarm.ts b/packages/eve/src/execution/sandbox/prewarm.ts
index 9ce083a90..08ee688c5 100644
--- a/packages/eve/src/execution/sandbox/prewarm.ts
+++ b/packages/eve/src/execution/sandbox/prewarm.ts
@@ -1,57 +1,76 @@
-import { join } from "node:path";
+import { join, relative, resolve } from "node:path";
import type { CompiledWorkspaceResourceRoot } from "#compiler/manifest.js";
import { loadCompiledModuleMapFromAuthoredSource } from "#internal/authored-module-map-loader.js";
-import { resolvePackageSourceFilePath } from "#internal/application/package.js";
import { createAuthoredSourceRuntimeCompiledArtifactsSource } from "#internal/application/runtime-compiled-artifacts-source.js";
-import type {
- SandboxBackend,
- SandboxBackendPrewarmInput,
- SandboxBackendPrewarmResult,
- SandboxSeedFile,
-} from "#public/definitions/sandbox-backend.js";
import {
- createBundledRuntimeCompiledArtifactsSource,
- createDiskRuntimeCompiledArtifactsSource,
+ createSandboxProviderResources,
+ type SandboxPreparedArtifact,
+ type SandboxProviderPrepareContext,
+ type SandboxProviderRuntime,
+} from "#shared/sandbox-provider.js";
+import {
getRuntimeCompiledArtifactsSandboxAppRoot,
type RuntimeCompiledArtifactsSource,
type RuntimeDiskCompiledArtifactsSource,
} from "#runtime/compiled-artifacts-source.js";
-import { type ResolvedAgentGraphBundle, ROOT_RUNTIME_AGENT_NODE_ID } from "#runtime/graph.js";
-import { loadCompileMetadata } from "#runtime/loaders/compile-metadata.js";
-import { withBundledCompiledArtifacts } from "#runtime/loaders/bundled-artifacts.js";
+import {
+ getResolvedRuntimeAgentNode,
+ type ResolvedAgentGraphBundle,
+ ROOT_RUNTIME_AGENT_NODE_ID,
+} from "#runtime/graph.js";
import { loadCompiledManifest } from "#runtime/loaders/manifest.js";
import { resolveRuntimeCompilerArtifactPaths } from "#runtime/loaders/artifact-paths.js";
import { resolveRuntimeAgentGraph } from "#runtime/resolve-agent-graph.js";
-import { createRuntimeSandboxTemplateKey } from "#runtime/sandbox/keys.js";
+import { createSandboxProviderFiles } from "#execution/sandbox/provider-files.js";
+import { createDevelopmentSandboxProviderHost } from "#execution/sandbox/provider-host-development.js";
+import { resolveSandboxCacheDirectory } from "#internal/application/paths.js";
import type { RuntimeRegisteredSandbox } from "#runtime/sandbox/registry.js";
-import { createRuntimeSandboxTemplatePlan } from "#runtime/sandbox/template-plan.js";
+import type { SandboxPreparedArtifactEntry } from "#shared/sandbox-prepared-artifacts.js";
+import { writeSandboxPreparedArtifactsManifest } from "#runtime/sandbox/prepared-artifacts.js";
import { materializeWorkspaceDirectory } from "#runtime/workspace/seed-files.js";
import { toErrorMessage } from "#shared/errors.js";
-import { withSandboxTemplatePrewarmLock } from "./template-prewarm-lock.js";
+import { getSandboxEnvironmentRuntime } from "#shared/sandbox-environment.js";
+
+export interface SandboxPreparedArtifactStore {
+ write(input: {
+ readonly compileDirectoryPath: string;
+ readonly entries: readonly SandboxPreparedArtifactEntry[];
+ }): Promise<void>;
+}
+
+const diskPreparedArtifactStore: SandboxPreparedArtifactStore = {
+ async write(input) {
+ await writeSandboxPreparedArtifactsManifest(input);
+ },
+};
interface PrewarmTarget {
- readonly backend: SandboxBackend;
+ readonly context: SandboxProviderPrepareContext;
readonly label: string;
- readonly input: SandboxBackendPrewarmInput;
- readonly signature: string;
+ readonly nodeId: string;
+ readonly provider: SandboxProviderRuntime;
}
interface NodeSandbox extends RuntimeRegisteredSandbox {
+ readonly definition: Extract<
+ RuntimeRegisteredSandbox["definition"],
+ { readonly kind: "independent" }
+ >;
readonly nodeId: string;
}
/**
- * Optional dispatch override that intercepts every `backend.prewarm`
+ * Optional dispatch override that intercepts every provider `prepare()`
* call. Production code never supplies this; the orchestrator dispatches
- * directly to the backend. Tests inject a recorder to verify which
- * templates the orchestrator emits and what bootstrap calls flow through
+ * directly to the provider. Tests inject a recorder to verify which
+ * templates the orchestrator emits and what preparation calls flow through
* them.
*/
-export type SandboxBackendPrewarmDispatch = (input: {
- readonly backend: SandboxBackend;
- readonly input: SandboxBackendPrewarmInput;
-}) => Promise<SandboxBackendPrewarmResult>;
+export type SandboxProviderPrepareDispatch = (input: {
+ readonly context: SandboxProviderPrepareContext;
+ readonly provider: SandboxProviderRuntime;
+}) => Promise<SandboxPreparedArtifact>;
interface PrewarmSandboxesInput {
readonly appRoot: string;
@@ -59,17 +78,16 @@ interface PrewarmSandboxesInput {
readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
readonly graph: ResolvedAgentGraphBundle;
readonly log?: (message: string) => void;
- readonly dispatch?: SandboxBackendPrewarmDispatch;
- readonly onPrewarmSignature?: (signature: string) => void;
- readonly shouldPrewarmSignature?: (signature: string) => boolean;
+ readonly dispatch?: SandboxProviderPrepareDispatch;
+ readonly preparedArtifactStore?: SandboxPreparedArtifactStore;
}
/**
- * Prewarms every backend sandbox template required by one compiled
+ * Prepares every provider sandbox template required by one compiled
* runtime graph.
*
- * Iterates every registered sandbox and invokes `backend.prewarm(...)`
- * for each backend template.
+ * Iterates every registered sandbox and invokes `provider.prepare(...)`
+ * for each provider template.
*/
export async function prewarmSandboxes(input: PrewarmSandboxesInput): Promise<void> {
const targets = await collectPrewarmTargets(input);
@@ -78,70 +96,52 @@ export async function prewarmSandboxes(input: PrewarmSandboxesInput): Promise<vo
return;
}
- const signature = createPrewarmSignature(targets);
- if (input.shouldPrewarmSignature?.(signature) === false) {
- return;
- }
-
+ const preparedArtifactStore = input.preparedArtifactStore ?? diskPreparedArtifactStore;
const dispatch =
input.dispatch ??
- (async ({ backend, input: prewarmInput }) => {
- return await backend.prewarm(prewarmInput);
- });
+ (async ({ context, provider }) => await provider.implementation.prepare(context));
input.log?.(`eve: initializing ${formatSandboxTemplateCount(targets.length)}...`);
const results = await Promise.all(
- targets.map(async ({ backend, label, input: prewarmInput }) => {
- const logBackendProgress = (message: string) => {
- if (!shouldLogSandboxPrewarmProgress(message)) {
- return;
- }
- input.log?.(`eve: sandbox template "${label}" (${backend.name}): ${message}`);
+ targets.map(async ({ context, label, nodeId, provider }) => {
+ const logProviderProgress = (message: string) => {
+ if (!shouldLogSandboxPrewarmProgress(message)) return;
+ input.log?.(`eve: sandbox template "${label}" (${provider.providerName}): ${message}`);
};
- let result: SandboxBackendPrewarmResult;
try {
- result = await withSandboxTemplatePrewarmLock(
- {
- appRoot: prewarmInput.runtimeContext.appRoot,
- backendName: backend.name,
- templateKey: prewarmInput.templateKey,
+ const result = await dispatch({
+ context: {
+ ...context,
+ log: input.log === undefined ? undefined : logProviderProgress,
},
- async () => {
- return await dispatch({
- backend,
- input: {
- ...prewarmInput,
- log: input.log === undefined ? undefined : logBackendProgress,
- },
- });
- },
- );
+ provider,
+ });
+ return { nodeId, provider, result };
} catch (error) {
const prewarmError = formatPrewarmFailureForEnvironment({
- backendName: backend.name,
+ providerName: provider.providerName,
error,
});
input.log?.(
- `eve: failed to initialize sandbox template "${label}" on backend "${backend.name}": ${toErrorMessage(prewarmError)}`,
+ `eve: failed to initialize sandbox template "${label}" on provider "${provider.providerName}": ${toErrorMessage(prewarmError)}`,
);
throw prewarmError;
}
- return result;
}),
);
- const reusedCount = results.filter((result) => result.reused).length;
- input.log?.(
- `eve: initialized ${formatSandboxTemplateCount(targets.length)} (${reusedCount} reused, ${
- targets.length - reusedCount
- } built).`,
- );
- input.onPrewarmSignature?.(signature);
+ const entries = results.map(({ nodeId, provider, result }) => ({
+ artifact: result,
+ nodeId,
+ providerName: provider.providerName,
+ }));
+ await preparedArtifactStore.write({ compileDirectoryPath: input.compileDirectoryPath, entries });
+ input.log?.(`eve: initialized ${formatSandboxTemplateCount(targets.length)}.`);
}
/**
* Loads the compiled runtime graph for one authored app root and
- * prewarms every backend's sandbox templates required by that graph.
+ * prepares every provider sandbox template required by that graph.
*
* Hydrates the module map directly from authored source so callers
* don't need a pre-existing `module-map.mjs` import in Node's cache.
@@ -157,9 +157,8 @@ export async function prewarmAppSandboxes(input: {
}>,
) => Promise<ResolvedAgentGraphBundle>;
readonly log?: (message: string) => void;
- readonly dispatch?: SandboxBackendPrewarmDispatch;
- readonly onPrewarmSignature?: (signature: string) => void;
- readonly shouldPrewarmSignature?: (signature: string) => boolean;
+ readonly dispatch?: SandboxProviderPrepareDispatch;
+ readonly preparedArtifactStore?: SandboxPreparedArtifactStore;
}): Promise<void> {
const compiledArtifactsSource =
input.compiledArtifactsSource ??
@@ -179,119 +178,60 @@ export async function prewarmAppSandboxes(input: {
dispatch: input.dispatch,
graph,
log: input.log,
- onPrewarmSignature: input.onPrewarmSignature,
- shouldPrewarmSignature: input.shouldPrewarmSignature,
+ preparedArtifactStore: input.preparedArtifactStore,
});
}
-/**
- * Loads one built app's bundled compiled artifacts and prewarms the sandbox
- * templates that its production Nitro runtime will request.
- */
-export async function prewarmBuiltAppSandboxes(input: {
- readonly appRoot: string;
- readonly log?: (message: string) => void;
- readonly dispatch?: SandboxBackendPrewarmDispatch;
-}): Promise<void> {
- const builtArtifactsRoot = join(input.appRoot, ".output");
- const builtArtifactsSource = createDiskRuntimeCompiledArtifactsSource(builtArtifactsRoot, {
- moduleMapLoaderPath: resolvePackageSourceFilePath("src/internal/authored-module-map-loader.ts"),
- sandboxAppRoot: input.appRoot,
- });
- const [metadata, manifest, moduleMap] = await Promise.all([
- loadCompileMetadata({
- compiledArtifactsSource: builtArtifactsSource,
- }),
- loadCompiledManifest({
- compiledArtifactsSource: builtArtifactsSource,
- }),
- loadCompiledModuleMapFromAuthoredSource({
- authoredAppRoot: input.appRoot,
- compiledArtifactsSource: builtArtifactsSource,
- }),
- ]);
-
- await withBundledCompiledArtifacts(
- {
- manifest,
- metadata: metadata ?? undefined,
- moduleMap,
- sessionId: "built-app-prewarm",
- },
- async () => {
- const compiledArtifactsSource = createBundledRuntimeCompiledArtifactsSource();
- const graph = await resolveRuntimeAgentGraph({
- manifest,
- moduleMap,
- });
-
- await prewarmSandboxes({
- appRoot: input.appRoot,
- compileDirectoryPath:
- resolveRuntimeCompilerArtifactPaths(builtArtifactsRoot).compileDirectoryPath,
- compiledArtifactsSource,
- dispatch: input.dispatch,
- graph,
- log: input.log,
- });
- },
- );
-}
-
async function collectPrewarmTargets(input: {
readonly appRoot: string;
readonly compileDirectoryPath: string;
readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
readonly graph: ResolvedAgentGraphBundle;
}): Promise<readonly PrewarmTarget[]> {
- const runtimeContext = { appRoot: input.appRoot };
-
const targets: PrewarmTarget[] = [];
await Promise.all(
collectNodeSandboxes(input.graph).map(async ({ definition, nodeId, workspaceResourceRoot }) => {
- const templatePlan = createRuntimeSandboxTemplatePlan({
- definition,
+ const agent = getResolvedRuntimeAgentNode(input.graph, nodeId).agent;
+ const sandboxRoot = join(
+ resolve(input.appRoot, relative(agent.metadata.appRoot, agent.metadata.agentRoot)),
+ "sandbox",
+ );
+ const provider = getSandboxEnvironmentRuntime(definition.environment);
+ const seedFiles = await loadResourceRootSeedFiles({
+ compileDirectoryPath: input.compileDirectoryPath,
workspaceResourceRoot,
});
- const templateKey = await createRuntimeSandboxTemplateKey({
- backendName: definition.backend.name,
- compiledArtifactsSource: input.compiledArtifactsSource,
- nodeId,
- sourceId: definition.sourceId,
- templatePlan,
- });
-
- if (templateKey === null) {
- return;
- }
-
targets.push({
- backend: definition.backend,
- label: formatLabel(nodeId),
- input: {
- bootstrap: definition.bootstrap,
- seedFiles: await loadResourceRootSeedFiles({
- compileDirectoryPath: input.compileDirectoryPath,
- workspaceResourceRoot,
+ context: {
+ files: createSandboxProviderFiles(sandboxRoot),
+ host: createDevelopmentSandboxProviderHost(input.appRoot),
+ resources: createSandboxProviderResources({
+ resourcesKey: workspaceResourceRoot.contentHash,
+ resourcesPath:
+ workspaceResourceRoot.contentHash === undefined
+ ? undefined
+ : `${input.compileDirectoryPath}/${workspaceResourceRoot.logicalPath}`,
+ seedFiles,
}),
- runtimeContext,
- templateKey,
+ sourceRevision: definition.revisionHash,
+ storagePath: resolveSandboxCacheDirectory(input.appRoot),
},
- signature: `${definition.backend.name}:${nodeId}:${templateKey}`,
+ label: formatLabel(nodeId),
+ nodeId,
+ provider,
});
}),
);
- // Template keys factor in nodeId (see runtime/sandbox/keys.ts), so each
- // node already produces a distinct templateKey; no dedup is needed.
+ // Each graph node owns one manifest entry, so no deduplication is needed.
return targets.sort((left, right) => left.label.localeCompare(right.label));
}
/**
* Resolves the per-node compiled workspace resource root to an absolute
* disk path under `.eve/compile/` and materializes its contents into the
- * `{path, content}` shape consumed by sandbox backends.
+ * `{path, content}` shape consumed by sandbox providers.
*
* Returns an empty array when the resource root descriptor advertises no
* root entries (the materializer would emit no files anyway).
@@ -299,7 +239,7 @@ async function collectPrewarmTargets(input: {
async function loadResourceRootSeedFiles(input: {
readonly compileDirectoryPath: string;
readonly workspaceResourceRoot: CompiledWorkspaceResourceRoot;
-}): Promise<readonly SandboxSeedFile[]> {
+}): Promise<readonly { readonly content: Uint8Array; readonly path: string }[]> {
if (
input.workspaceResourceRoot.contentHash === undefined &&
input.workspaceResourceRoot.rootEntries.length === 0
@@ -333,7 +273,14 @@ async function loadGraphFromArtifacts(input: {
function collectNodeSandboxes(graph: ResolvedAgentGraphBundle): readonly NodeSandbox[] {
return [...graph.nodesByNodeId.entries()].flatMap(([nodeId, node]) => {
const registered = node.sandboxRegistry.sandbox;
- return registered.definition.inheritsParent === true ? [] : [{ ...registered, nodeId }];
+ if (registered.definition.kind === "parent") return [];
+ return [
+ {
+ ...registered,
+ definition: registered.definition,
+ nodeId,
+ },
+ ];
});
}
@@ -341,13 +288,6 @@ function formatLabel(nodeId: string): string {
return nodeId === ROOT_RUNTIME_AGENT_NODE_ID ? "root" : nodeId;
}
-function createPrewarmSignature(targets: readonly PrewarmTarget[]): string {
- return targets
- .map((target) => target.signature)
- .sort()
- .join("\n");
-}
-
function formatSandboxTemplateCount(count: number): string {
return `${count} sandbox ${count === 1 ? "template" : "templates"}`;
}
@@ -362,19 +302,19 @@ function shouldLogSandboxPrewarmProgress(message: string): boolean {
}
function formatPrewarmFailureForEnvironment(input: {
- readonly backendName: string;
+ readonly providerName: string;
readonly error: unknown;
}): unknown {
- if (!isVercelEnvironment() || !isLocalSandboxBackend(input.backendName)) {
+ if (!isVercelEnvironment() || !isLocalSandboxProvider(input.providerName)) {
return input.error;
}
return new Error(
- `The ${input.backendName} sandbox backend is not available when deploying on Vercel. ` +
+ `The ${input.providerName} sandbox provider is not available when deploying on Vercel. ` +
"Vercel build containers cannot run local Docker containers or microsandbox VMs. " +
- "Use defaultBackend() so eve selects Vercel Sandbox on Vercel, or configure a " +
- "Vercel-compatible backend explicitly, such as vercel(). " +
- `Original ${input.backendName} error: ${toErrorMessage(input.error)}`,
+ "Use DefaultSandbox.environment() so eve selects Vercel Sandbox on Vercel, or configure " +
+ "VercelSandbox.environment() explicitly. " +
+ `Original ${input.providerName} error: ${toErrorMessage(input.error)}`,
{ cause: input.error },
);
}
@@ -383,6 +323,6 @@ function isVercelEnvironment(): boolean {
return Boolean(process.env.VERCEL?.trim());
}
-function isLocalSandboxBackend(backendName: string): boolean {
- return backendName === "docker" || backendName === "microsandbox";
+function isLocalSandboxProvider(providerName: string): boolean {
+ return providerName === "docker" || providerName === "microsandbox";
}
diff --git a/packages/eve/src/execution/sandbox/provider-files.ts b/packages/eve/src/execution/sandbox/provider-files.ts
new file mode 100644
index 000000000..4eba5dc39
--- /dev/null
+++ b/packages/eve/src/execution/sandbox/provider-files.ts
@@ -0,0 +1,49 @@
+import { readdir, readFile, realpath } from "node:fs/promises";
+import { relative, resolve, sep } from "node:path";
+
+import type { SandboxProviderFiles } from "#shared/sandbox-provider.js";
+
+export function createSandboxProviderFiles(root: string): SandboxProviderFiles {
+ const resolvedRoot = resolve(root);
+
+ async function resolvePath(path: string): Promise<string> {
+ const candidate = resolve(resolvedRoot, path);
+ const relativePath = relative(resolvedRoot, candidate);
+ if (relativePath === "" || (!relativePath.startsWith(`..${sep}`) && relativePath !== "..")) {
+ return candidate;
+ }
+ throw new Error(`Sandbox provider file path escapes the authored sandbox root: ${path}`);
+ }
+
+ return {
+ async list() {
+ const entries = await readdir(resolvedRoot, { recursive: true, withFileTypes: true }).catch(
+ (error: unknown) => {
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return [];
+ throw error;
+ },
+ );
+ return entries
+ .filter((entry) => entry.isFile())
+ .map((entry) => relative(resolvedRoot, resolve(entry.parentPath, entry.name)))
+ .sort();
+ },
+ async read(path) {
+ const candidate = await resolvePath(path);
+ const [canonicalRoot, canonical] = await Promise.all([
+ realpath(resolvedRoot),
+ realpath(candidate),
+ ]);
+ const relativePath = relative(canonicalRoot, canonical);
+ if (relativePath.startsWith(`..${sep}`) || relativePath === "..") {
+ throw new Error(
+ `Sandbox provider file resolves outside the authored sandbox root: ${path}`,
+ );
+ }
+ return await readFile(canonical);
+ },
+ async readText(path) {
+ return Buffer.from(await this.read(path)).toString("utf8");
+ },
+ };
+}
diff --git a/packages/eve/src/execution/sandbox/provider-host-development.ts b/packages/eve/src/execution/sandbox/provider-host-development.ts
new file mode 100644
index 000000000..2d56f7e31
--- /dev/null
+++ b/packages/eve/src/execution/sandbox/provider-host-development.ts
@@ -0,0 +1,15 @@
+import { resolve } from "node:path";
+
+import { loadOptionalEnginePackage } from "#internal/application/optional-package-install.js";
+import type { SandboxProviderHost } from "#shared/sandbox-provider.js";
+
+export function createDevelopmentSandboxProviderHost(appRoot: string): SandboxProviderHost {
+ return {
+ async loadOptionalPackage(input) {
+ return await loadOptionalEnginePackage({ appRoot, ...input });
+ },
+ resolveProjectPath(path) {
+ return resolve(appRoot, path);
+ },
+ };
+}
diff --git a/packages/eve/src/execution/sandbox/provider-host.ts b/packages/eve/src/execution/sandbox/provider-host.ts
new file mode 100644
index 000000000..542f7f020
--- /dev/null
+++ b/packages/eve/src/execution/sandbox/provider-host.ts
@@ -0,0 +1,18 @@
+import { resolve } from "node:path";
+
+import type { SandboxProviderHost } from "#shared/sandbox-provider.js";
+
+export function createSandboxProviderHost(appRoot: string): SandboxProviderHost {
+ return {
+ async loadOptionalPackage(input) {
+ try {
+ return await input.importModule();
+ } catch (error) {
+ throw new Error(input.missingMessage, { cause: error });
+ }
+ },
+ resolveProjectPath(path) {
+ return resolve(appRoot, path);
+ },
+ };
+}
diff --git a/packages/eve/src/execution/sandbox/provider-identity.ts b/packages/eve/src/execution/sandbox/provider-identity.ts
new file mode 100644
index 000000000..f43455d23
--- /dev/null
+++ b/packages/eve/src/execution/sandbox/provider-identity.ts
@@ -0,0 +1,31 @@
+import { createHash } from "node:crypto";
+
+export function createSandboxProviderIdentity(value: unknown): string {
+ return createHash("sha256").update(serialize(value, new WeakSet())).digest("hex");
+}
+
+function serialize(value: unknown, seen: WeakSet<object>): string {
+ if (
+ value === null ||
+ typeof value === "boolean" ||
+ typeof value === "number" ||
+ typeof value === "string"
+ ) {
+ return JSON.stringify(value);
+ }
+ if (typeof value === "undefined") return "undefined";
+ if (typeof value === "function") return `function:${value.toString()}`;
+ if (Array.isArray(value)) return `[${value.map((entry) => serialize(entry, seen)).join(",")}]`;
+ if (typeof value !== "object") {
+ throw new Error(`Unsupported sandbox provider identity value: ${typeof value}`);
+ }
+ if (seen.has(value)) throw new Error("Sandbox provider identity values cannot be circular.");
+ seen.add(value);
+ const result = `{${Object.entries(value)
+ .filter(([, entry]) => entry !== undefined)
+ .sort(([left], [right]) => left.localeCompare(right))
+ .map(([key, entry]) => `${JSON.stringify(key)}:${serialize(entry, seen)}`)
+ .join(",")}}`;
+ seen.delete(value);
+ return result;
+}
diff --git a/packages/eve/src/execution/sandbox/ripgrep-probe.ts b/packages/eve/src/execution/sandbox/ripgrep-probe.ts
index 08ab59f70..9eeb7150c 100644
--- a/packages/eve/src/execution/sandbox/ripgrep-probe.ts
+++ b/packages/eve/src/execution/sandbox/ripgrep-probe.ts
@@ -1,45 +1,15 @@
import type { SandboxSession } from "#public/definitions/sandbox.js";
-/**
- * Memoizes the result of probing for a compatible `rg` (ripgrep) once per
- * sandbox session, regardless of how many grep/glob tool calls happen.
- */
-const probes = new Map<string, Promise<boolean>>();
-
const RIPGREP_PROBE_COMMAND =
"command -v rg >/dev/null 2>&1 || exit 127; " +
"rg --line-number --color=never --hidden --glob '!.git/*' --max-count 1 -- " +
"'__eve_ripgrep_probe_never_matches__' /workspace";
-/**
- * Returns `true` when `rg` is on PATH and supports the options used by eve,
- * `false` otherwise. Result is cached per session.
- *
- * Framework `grep` and `glob` tools call this to decide whether to use
- * ripgrep or the POSIX `grep`/`find` fallback.
- */
export async function ripgrepIsAvailable(session: SandboxSession): Promise<boolean> {
- const existing = probes.get(session.id);
- if (existing !== undefined) {
- return existing;
- }
-
- const pending = runProbe(session);
- probes.set(session.id, pending);
-
try {
- return await pending;
+ const result = await session.run({ command: RIPGREP_PROBE_COMMAND });
+ return (result.exitCode === 0 || result.exitCode === 1) && result.stderr.trim().length === 0;
} catch {
- // If the probe itself threw, treat rg as unavailable and clear the
- // cache so a later call can retry. A failed probe usually means the
- // sandbox session is in a bad state; letting the next call retry is
- // safer than permanently marking rg as missing.
- probes.delete(session.id);
return false;
}
}
-
-async function runProbe(session: SandboxSession): Promise<boolean> {
- const result = await session.run({ command: RIPGREP_PROBE_COMMAND });
- return (result.exitCode === 0 || result.exitCode === 1) && result.stderr.trim().length === 0;
-}
diff --git a/packages/eve/src/execution/sandbox/session.test.ts b/packages/eve/src/execution/sandbox/session.test.ts
index 37808dfcc..07c3cdecc 100644
--- a/packages/eve/src/execution/sandbox/session.test.ts
+++ b/packages/eve/src/execution/sandbox/session.test.ts
@@ -28,7 +28,6 @@ function createTestPrimitives(
overrides: Partial<InternalSandboxSession> = {},
): InternalSandboxSession {
return {
- id: overrides.id ?? "test-session-id",
readFile: overrides.readFile ?? vi.fn(async () => null),
removePath: overrides.removePath ?? vi.fn(async () => {}),
resolvePath: overrides.resolvePath ?? ((path: string) => `/resolved/${path}`),
@@ -38,16 +37,6 @@ function createTestPrimitives(
}
describe("buildSandboxSession", () => {
- // ---------------------------------------------------------------------------
- // id
- // ---------------------------------------------------------------------------
-
- it("exposes the primitives id as the public session id", () => {
- const session = buildSandboxSession(createTestPrimitives({ id: "sbx-123" }));
-
- expect(session.id).toBe("sbx-123");
- });
-
// ---------------------------------------------------------------------------
// setNetworkPolicy
// ---------------------------------------------------------------------------
@@ -62,15 +51,13 @@ describe("buildSandboxSession", () => {
},
};
- await session.setNetworkPolicy(policy);
+ await session.setNetworkPolicy?.(policy);
expect(apply).toHaveBeenCalledWith(policy);
});
- it("defaults setNetworkPolicy to a no-op when no applier is supplied", async () => {
- const session = buildSandboxSession(createTestPrimitives());
-
- await expect(session.setNetworkPolicy("deny-all")).resolves.toBeUndefined();
+ it("omits setNetworkPolicy when no applier is supplied", () => {
+ expect(buildSandboxSession(createTestPrimitives()).setNetworkPolicy).toBeUndefined();
});
// ---------------------------------------------------------------------------
diff --git a/packages/eve/src/execution/sandbox/session.ts b/packages/eve/src/execution/sandbox/session.ts
index 048f13295..54c7b07f1 100644
--- a/packages/eve/src/execution/sandbox/session.ts
+++ b/packages/eve/src/execution/sandbox/session.ts
@@ -1,5 +1,6 @@
import type {
InternalSandboxSession,
+ MutableNetworkSandboxSession,
SandboxProcess,
SandboxReadBinaryFileOptions,
SandboxReadFileOptions,
@@ -18,21 +19,25 @@ import { bufferToStream, streamToBuffer } from "./stream-utils.js";
export type { InternalSandboxSession };
/**
- * Builds a public {@link SandboxSession} from backend-specific primitives.
+ * Builds a public {@link SandboxSession} from provider-specific primitives.
*
* Encoding handling, line-range slicing, and the binary/text/stream
- * variants live here so each backend only has to implement byte-oriented
+ * variants live here so each provider only has to implement byte-oriented
* read/write primitives. `run` is implemented as a thin wrapper over the
- * backend's `spawn`: collect stdout/stderr to strings, await `wait()`,
+ * provider's `spawn`: collect stdout/stderr to strings, await `wait()`,
* then return the combined result.
*
- * `setNetworkPolicy` applies a firewall policy to the live sandbox. It
- * defaults to a no-op so backends without a firewall (and test doubles)
- * need not supply one; the Vercel backend wires it to `sandbox.update`.
+ * Providers without mutable firewall support omit `setNetworkPolicy`; the
+ * dedicated Vercel provider wires it to `sandbox.update`.
*/
export function buildSandboxSession(
primitives: InternalSandboxSession,
- setNetworkPolicy: (policy: SandboxNetworkPolicy) => Promise<void> = async () => {},
+ setNetworkPolicy: (policy: SandboxNetworkPolicy) => Promise<void>,
+): MutableNetworkSandboxSession;
+export function buildSandboxSession(primitives: InternalSandboxSession): SandboxSession;
+export function buildSandboxSession(
+ primitives: InternalSandboxSession,
+ setNetworkPolicy?: (policy: SandboxNetworkPolicy) => Promise<void>,
): SandboxSession {
async function run(options: SandboxRunOptions) {
const process = await primitives.spawn(options);
@@ -43,8 +48,7 @@ export function buildSandboxSession(
]);
return { exitCode, stderr, stdout };
}
- return {
- id: primitives.id,
+ const session: { -readonly [Key in keyof SandboxSession]: SandboxSession[Key] } = {
resolvePath(path: string): string {
return primitives.resolvePath(path);
},
@@ -111,8 +115,9 @@ export function buildSandboxSession(
recursive: options.recursive,
});
},
- setNetworkPolicy,
};
+ if (setNetworkPolicy !== undefined) session.setNetworkPolicy = setNetworkPolicy;
+ return session;
}
/**
diff --git a/packages/eve/src/execution/sandbox/template-prewarm-lock.ts b/packages/eve/src/execution/sandbox/template-prewarm-lock.ts
deleted file mode 100644
index 1b562c8d9..000000000
--- a/packages/eve/src/execution/sandbox/template-prewarm-lock.ts
+++ /dev/null
@@ -1,132 +0,0 @@
-import { mkdir, rm, stat, writeFile } from "node:fs/promises";
-import { dirname, join } from "node:path";
-
-import { resolveSandboxCacheDirectory } from "#internal/application/paths.js";
-
-const LOCK_POLL_MS = 250;
-const LOCK_TIMEOUT_MS = 15 * 60 * 1000;
-const STALE_LOCK_MS = 30 * 60 * 1000;
-
-export interface SandboxTemplatePrewarmLockInput {
- readonly appRoot: string;
- readonly backendName: string;
- readonly log?: (message: string) => void;
- readonly templateKey: string;
-}
-
-export async function waitForSandboxTemplatePrewarmLock(
- input: SandboxTemplatePrewarmLockInput,
-): Promise<void> {
- await waitForLockRelease(resolveSandboxTemplatePrewarmLockPath(input), input.log);
-}
-
-export async function withSandboxTemplatePrewarmLock<T>(
- input: SandboxTemplatePrewarmLockInput,
- callback: () => Promise<T>,
-): Promise<T> {
- const lockPath = resolveSandboxTemplatePrewarmLockPath(input);
- await acquireLock(lockPath);
- try {
- return await callback();
- } finally {
- await rm(lockPath, { force: true, recursive: true }).catch(() => {});
- }
-}
-
-function resolveSandboxTemplatePrewarmLockPath(input: SandboxTemplatePrewarmLockInput): string {
- return join(
- resolveSandboxCacheDirectory(input.appRoot),
- "template-locks",
- input.backendName,
- `${input.templateKey}.lock`,
- );
-}
-
-async function acquireLock(lockPath: string): Promise<void> {
- const startedAt = Date.now();
- for (;;) {
- await mkdir(dirname(lockPath), { recursive: true });
- try {
- await mkdir(lockPath);
- await writeFile(
- join(lockPath, "owner.json"),
- `${JSON.stringify({ createdAt: new Date().toISOString(), pid: process.pid })}\n`,
- );
- return;
- } catch (error) {
- if (!isFileExistsError(error)) {
- throw error;
- }
- await waitForExistingLock(lockPath, startedAt, undefined);
- }
- }
-}
-
-async function waitForLockRelease(
- lockPath: string,
- log: ((message: string) => void) | undefined,
-): Promise<void> {
- const startedAt = Date.now();
- let nextLogAt = startedAt + 10_000;
- for (;;) {
- try {
- await stat(lockPath);
- } catch (error) {
- if (isNotFoundError(error)) {
- return;
- }
- throw error;
- }
- const now = Date.now();
- if (log !== undefined && now >= nextLogAt) {
- const elapsedSeconds = Math.round((now - startedAt) / 1000);
- log(
- elapsedSeconds === 0
- ? "waiting for sandbox template prewarm to finish"
- : `waiting for sandbox template prewarm to finish (${elapsedSeconds}s elapsed)`,
- );
- nextLogAt = now + 10_000;
- }
- await waitForExistingLock(lockPath, startedAt, log);
- }
-}
-
-async function waitForExistingLock(
- lockPath: string,
- startedAt: number,
- log: ((message: string) => void) | undefined,
-): Promise<void> {
- const lockStat = await stat(lockPath).catch((error: unknown) => {
- if (isNotFoundError(error)) {
- return null;
- }
- throw error;
- });
- if (lockStat === null) {
- return;
- }
-
- const lockAgeMs = Date.now() - lockStat.mtimeMs;
- if (lockAgeMs > STALE_LOCK_MS) {
- log?.("removing stale sandbox template prewarm lock");
- await rm(lockPath, { force: true, recursive: true }).catch(() => {});
- return;
- }
-
- const elapsedMs = Date.now() - startedAt;
- if (elapsedMs > LOCK_TIMEOUT_MS) {
- throw new Error(
- `Timed out waiting for sandbox template prewarm lock "${lockPath}" after ${LOCK_TIMEOUT_MS}ms.`,
- );
- }
-
- await new Promise((resolve) => setTimeout(resolve, LOCK_POLL_MS));
-}
-
-function isFileExistsError(error: unknown): boolean {
- return typeof error === "object" && error !== null && "code" in error && error.code === "EEXIST";
-}
-
-function isNotFoundError(error: unknown): boolean {
- return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
-}
diff --git a/packages/eve/src/execution/session-reset.integration.test.ts b/packages/eve/src/execution/session-reset.integration.test.ts
index 16b092208..106a16cba 100644
--- a/packages/eve/src/execution/session-reset.integration.test.ts
+++ b/packages/eve/src/execution/session-reset.integration.test.ts
@@ -1,7 +1,7 @@
import { sessionInboxHookToken } from "#execution/session-inbox/address.js";
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
-import { ContextContainer, contextStorage } from "#context/container.js";
+import { ContextContainer } from "#context/container.js";
import { SessionKey } from "#context/keys.js";
import { ensureSandboxAccess } from "#execution/sandbox/ensure.js";
import { clearActiveSandboxHandlesForTest } from "#execution/sandbox/active-handles.js";
@@ -10,11 +10,16 @@ import { waitForHook } from "#internal/testing/workflow-test-helpers.js";
import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";
import { start } from "#internal/workflow/runtime.js";
import { createWorkflowRuntime } from "#execution/workflow-runtime.js";
-import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
+import { defineSandboxProvider } 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";
+
+vi.mock("#runtime/sandbox/prepared-artifacts.js", () => ({
+ loadSandboxPreparedArtifact: vi.fn(async () => null),
+}));
import type { ResolvedSandboxDefinition } from "#runtime/types.js";
+import { defineSandbox } from "#public/definitions/sandbox.js";
describe("session reset integration", () => {
it("releases a parked continuation token and initializes a fresh sandbox", async () => {
@@ -27,7 +32,7 @@ describe("session reset integration", () => {
try {
await waitForHook(first, { token: sessionInboxHookToken(continuationToken) });
- await expect(sandboxes.open(first.runId)).resolves.toMatchObject({ id: "sandbox-1" });
+ await expect(sandboxes.open(first.runId)).resolves.toBeTruthy();
await expect(
runtime.dispatchContinuation({
@@ -49,7 +54,7 @@ describe("session reset integration", () => {
await expect(runtime.resolveContinuation(continuationToken)).resolves.toEqual({
sessionId: second.runId,
});
- await expect(sandboxes.open(second.runId)).resolves.toMatchObject({ id: "sandbox-2" });
+ await expect(sandboxes.open(second.runId)).resolves.toBeTruthy();
expect(sandboxes.initializedSessionIds).toEqual([first.runId, second.runId]);
expect(sandboxes.sessionKeys).toHaveLength(2);
expect(sandboxes.sessionKeys[0]).not.toBe(sandboxes.sessionKeys[1]);
@@ -68,33 +73,39 @@ function createSessionSandboxHarness() {
const initializedSessionIds: string[] = [];
const sessionKeys: string[] = [];
let sandboxCount = 0;
- const backend: SandboxBackend = {
- async create(input) {
- sessionKeys.push(input.sessionKey);
- sandboxCount += 1;
- const sandbox = mockSandbox({ id: `sandbox-${sandboxCount}` });
- return {
- captureState: async () => ({
- backendName: "session-reset-test",
- metadata: {},
- sessionKey: input.sessionKey,
- }),
- delete: async () => {},
- session: sandbox.session,
- stop: async () => {},
- shutdown: async () => {},
- useSessionFn: async () => sandbox.session,
- };
- },
+ const provider = defineSandboxProvider({
name: "session-reset-test",
- prewarm: async () => ({ reused: false }),
- };
+ environment: () => ({
+ async resume(context) {
+ return createHandle(context.session.id);
+ },
+ async start(context) {
+ sessionKeys.push(context.session.id);
+ sandboxCount += 1;
+ const sandbox = mockSandbox({ id: `sandbox-${sandboxCount}` });
+ return { handle: createHandle(context.session.id, sandbox), state: null };
+ },
+ prepare: async () => null,
+ }),
+ });
+ function createHandle(sessionId: string, value = mockSandbox({ id: sessionId })) {
+ return {
+ sandbox: value.session,
+ async onSessionDelete() {},
+ async onSessionStop() {},
+ async onRuntimeShutdown() {},
+ };
+ }
+ const environment = provider.environment();
const definition: ResolvedSandboxDefinition = {
- backend,
+ environment,
+ kind: "independent",
logicalPath: "agent/sandbox/sandbox.ts",
- onSession({ ctx }) {
- initializedSessionIds.push(ctx.session.id);
- },
+ selector: defineSandbox(({ session }) => {
+ initializedSessionIds.push(session.id);
+ return environment.open();
+ }),
+ revisionHash: "session-reset-sandbox-v1",
sourceId: "agent/sandbox/sandbox",
sourceKind: "module",
};
@@ -119,7 +130,6 @@ function createSessionSandboxHarness() {
compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
nodeId: "__root__",
registry,
- runOnSession: async (callback) => await contextStorage.run(context, callback),
sessionId,
state: null,
});
diff --git a/packages/eve/src/execution/session/entry.integration.test.ts b/packages/eve/src/execution/session/entry.integration.test.ts
index 0069e0f1d..bb1596dfb 100644
--- a/packages/eve/src/execution/session/entry.integration.test.ts
+++ b/packages/eve/src/execution/session/entry.integration.test.ts
@@ -27,6 +27,7 @@ import { createWorkflowRuntime, waitForCommandHookOwner } from "#execution/workf
import { normalizeEveAttributes } from "#runtime/attributes/normalize.js";
import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";
import { ConnectionAuthorizationRequiredError } from "#connections/errors.js";
+import { defineHook } from "#public/definitions/hook.js";
import type { MessageStreamEvent } from "#protocol/message.js";
import { isEventId } from "#protocol/event-id.js";
import type { ToolContext } from "#tools/definition.js";
@@ -37,7 +38,6 @@ import type {
} from "#shared/connection-types.js";
import type { ResolvedToolDefinition } from "#runtime/types.js";
import { toInputSchema } from "#tools/schema.js";
-import { defineHook } from "#public/definitions/hook.js";
import { ConversationContextKey } from "#shared/conversation-context.js";
import { SessionTitleKey } from "#context/keys.js";
@@ -233,7 +233,6 @@ describe("workflowEntry integration", () => {
default: defineHook({
events: {
async "session.started"(_event, ctx) {
- await ctx.getSandbox();
initializedSessions += 1;
initializedAuth = ctx.session.auth.current;
initializedInitiator = ctx.session.auth.initiator;
@@ -1807,6 +1806,8 @@ describe("workflowEntry integration", () => {
// make ingress wait for the successor instead of reporting the session
// gone (which would let the channel start a replacement session).
let gapDelivery: Promise<unknown> | undefined;
+ const createBatch = world.events.createBatch;
+ world.events.createBatch = undefined;
const createEvent = world.events.create.bind(world.events);
const spy = vi.spyOn(world.events, "create").mockImplementation(async (...args) => {
const [runId, event] = args;
@@ -1874,6 +1875,8 @@ describe("workflowEntry integration", () => {
sessionId: anchor.runId,
});
} finally {
+ spy.mockRestore();
+ world.events.createBatch = createBatch;
stream.dispose();
await anchor.cancel();
}
@@ -2077,49 +2080,6 @@ describe("workflowEntry integration", () => {
});
});
- it("can delete the sandbox from a session.completed hook", async () => {
- let deletions = 0;
- const runtime = await createTestRuntime({
- agent: { name: "workflow-entry-task-delete-sandbox" },
- modules: [
- {
- logicalPath: "hooks/delete-sandbox.ts",
- loadNamespace: async () => ({
- default: defineHook({
- events: {
- async "session.completed"(_event, ctx) {
- const sandbox = await ctx.getSandbox();
- await sandbox.delete();
- deletions += 1;
- },
- },
- }),
- }),
- },
- ],
- });
-
- await runtime.run(async () => {
- const run = await start(workflowEntry, [
- {
- kind: "initial",
- ownerDeploymentId: "dpl_inline",
- input: { message: "hello there" },
- serializedContext: buildSerializedContext({
- channelKind: "http",
- continuationToken: "http:workflow-entry-task-delete-sandbox",
- mode: "task",
- }),
- },
- ]);
-
- await expect(run.returnValue).resolves.toEqual({
- output: expect.stringContaining("hello there"),
- });
- expect(deletions).toBe(1);
- });
- });
-
it("returns agent-declared structured output in task mode", async () => {
const outputSchema = {
properties: {
diff --git a/packages/eve/src/execution/session/handoff-steps.test.ts b/packages/eve/src/execution/session/handoff-steps.test.ts
index 73da2cef3..9cb9b6472 100644
--- a/packages/eve/src/execution/session/handoff-steps.test.ts
+++ b/packages/eve/src/execution/session/handoff-steps.test.ts
@@ -64,7 +64,7 @@ describe("validateSessionCheckpointStep", () => {
);
});
- it.each([4, 5, 7])(
+ it.each([4, 5, 6, 8])(
"rejects checkpoint version %s before reading nested state",
async (version) => {
const checkpoint = createCheckpoint();
@@ -93,7 +93,7 @@ describe("validateSessionCheckpointStep", () => {
function createCheckpoint(): SessionCheckpoint {
return {
- version: 6,
+ version: 7,
sessionTimeoutMs: false,
mode: "conversation",
serializedContext: {},
diff --git a/packages/eve/src/execution/session/handoff-steps.ts b/packages/eve/src/execution/session/handoff-steps.ts
index e9531f53d..2ca5161d0 100644
--- a/packages/eve/src/execution/session/handoff-steps.ts
+++ b/packages/eve/src/execution/session/handoff-steps.ts
@@ -7,7 +7,9 @@ import {
type SessionOwnerActivation,
} from "#execution/session/handoff.js";
import { resumeHook } from "#internal/workflow/runtime.js";
+import { getResolvedRuntimeAgentNode } from "#runtime/graph.js";
import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
+import { getSandboxEnvironmentRuntime } from "#shared/sandbox-environment.js";
import { isObject } from "#shared/guards.js";
import { getAgentHandleStore } from "#subagents/handles/store.js";
@@ -74,7 +76,25 @@ export async function validateSessionCheckpointStep(input: {
)
throw new Error("Session checkpoint contains an invalid timeout duration.");
const context = await deserializeContext(checkpoint.serializedContext);
- context.require(BundleKey);
+ const bundle = context.require(BundleKey);
+ const session = readDurableSession(checkpoint.sessionState);
+ const sandboxState = session.sandboxState?.session;
+ if (sandboxState !== null && sandboxState !== undefined) {
+ const definition =
+ getResolvedRuntimeAgentNode(bundle.graph, bundle.nodeId).sandboxRegistry.sandbox.inheritance
+ ?.definition ??
+ getResolvedRuntimeAgentNode(bundle.graph, bundle.nodeId).sandboxRegistry.sandbox.definition;
+ if (definition.kind !== "independent") {
+ throw new Error("Session checkpoint sandbox has no resolved provider.");
+ }
+ const provider = getSandboxEnvironmentRuntime(definition.environment);
+ if (
+ sandboxState.providerName !== provider.providerName ||
+ sandboxState.stateProtocolVersion !== provider.stateProtocolVersion
+ ) {
+ throw new Error("Session checkpoint sandbox provider state is incompatible.");
+ }
+ }
if (!isSessionStateIdleForHandoff(checkpoint.sessionState)) {
throw new Error("Session checkpoint contains pending work and cannot be handed off.");
}
diff --git a/packages/eve/src/execution/session/handoff.test.ts b/packages/eve/src/execution/session/handoff.test.ts
index 741f6a349..32b9edcf7 100644
--- a/packages/eve/src/execution/session/handoff.test.ts
+++ b/packages/eve/src/execution/session/handoff.test.ts
@@ -44,7 +44,7 @@ describe("SessionHandoff", () => {
checkpoint: expect.objectContaining({
mode: "conversation",
sessionTimeoutMs: 60_000,
- version: 6,
+ version: 7,
}),
delivery: trigger.delivery,
targetDeploymentId: "deployment-b",
diff --git a/packages/eve/src/execution/session/handoff.ts b/packages/eve/src/execution/session/handoff.ts
index 1e63ebf7b..cfaf1f734 100644
--- a/packages/eve/src/execution/session/handoff.ts
+++ b/packages/eve/src/execution/session/handoff.ts
@@ -20,7 +20,7 @@ import type { RunMode } from "#shared/run-mode.js";
* an incompatible successor rejects the handoff instead of misreading state.
* The shared workflow tool run registry replaces the separate task and waiting-run records.
*/
-export const SESSION_CHECKPOINT_VERSION = 6;
+export const SESSION_CHECKPOINT_VERSION = 7;
/** Everything a successor needs to continue an idle session. Hooks are derived from the state. */
export interface SessionCheckpoint {
diff --git a/packages/eve/src/execution/tools/subagent/invoke-preparation.ts b/packages/eve/src/execution/tools/subagent/invoke-preparation.ts
index 135dbbe0a..552a85743 100644
--- a/packages/eve/src/execution/tools/subagent/invoke-preparation.ts
+++ b/packages/eve/src/execution/tools/subagent/invoke-preparation.ts
@@ -94,7 +94,7 @@ export async function prepareOwnerAgentInvocation(input: {
session,
}),
],
- planSharesSandbox: ({ bundle, plan }) => ownerPlanSharesSandbox({ bundle, plan }),
+ planReusesOwnerSandbox: ({ bundle, plan }) => ownerPlanReusesSandbox({ bundle, plan }),
serializedContext: input.serializedContext,
});
}
@@ -209,7 +209,7 @@ function classifyFreshStart(input: {
};
}
-function ownerPlanSharesSandbox(input: {
+function ownerPlanReusesSandbox(input: {
readonly bundle: CompiledBundle;
readonly plan: readonly OwnerAgentDispatchPlanEntry[];
}): boolean {
@@ -222,7 +222,7 @@ function ownerPlanSharesSandbox(input: {
return (
isSelfDelegation ||
input.bundle.graph?.nodesByNodeId.get(action.nodeId)?.sandboxRegistry.sandbox.definition
- .inheritsParent === true
+ .kind === "parent"
);
});
}
diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.ts
index 7484a250e..517ee870c 100644
--- a/packages/eve/src/execution/workflow-runtime.test.ts
+++ b/packages/eve/src/execution/workflow-runtime.test.ts
@@ -160,7 +160,7 @@ describe("session owner starts", () => {
getRunMock.mockReturnValue({ getWritable: () => sessionWritable });
startMock.mockResolvedValue({ runId: "owner-2" });
const checkpoint = {
- version: 6,
+ version: 7,
mode: "conversation",
serializedContext: {},
sessionState: { continuationToken: "continuation-1", sessionId: "session-1" },
diff --git a/packages/eve/src/framework/sources/modules/sandbox.ts b/packages/eve/src/framework/sources/modules/sandbox.ts
index 9a57a016e..857bb7fa2 100644
--- a/packages/eve/src/framework/sources/modules/sandbox.ts
+++ b/packages/eve/src/framework/sources/modules/sandbox.ts
@@ -1,3 +1,5 @@
import { defineSandbox } from "#public/definitions/sandbox.js";
+import { DefaultSandbox } from "#sandbox/providers.js";
-export default defineSandbox({});
+export const environment = DefaultSandbox.environment();
+export default defineSandbox(() => environment.open());
diff --git a/packages/eve/src/internal/application/compiled-artifacts.ts b/packages/eve/src/internal/application/compiled-artifacts.ts
index 3f3732466..75019dbca 100644
--- a/packages/eve/src/internal/application/compiled-artifacts.ts
+++ b/packages/eve/src/internal/application/compiled-artifacts.ts
@@ -1,4 +1,4 @@
-import { copyFile, mkdir, writeFile } from "node:fs/promises";
+import { copyFile, mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import type { AuthoredWorkflowModules } from "#internal/workflow-bundle/builder-support.js";
@@ -11,6 +11,10 @@ import {
} from "#internal/application/package.js";
import { buildPackageUserAgent } from "#internal/user-agent.js";
import type { AgentWorkflowWorldDefinition } from "#shared/agent-definition.js";
+import {
+ sandboxPreparedArtifactsManifestSchema,
+ type SandboxPreparedArtifactsManifest,
+} from "#shared/sandbox-prepared-artifacts.js";
import {
prepareAuthoredRuntimeModules,
type PreparedAuthoredRuntimeModules,
@@ -73,6 +77,9 @@ export async function writeCompiledArtifactsFiles(input: {
const moduleMapPath = join(input.outDir, "compiled-artifacts-module-map.mjs");
const instrumentationPluginPath = join(input.outDir, "compiled-artifacts-instrumentation.mjs");
const workflowWorldPluginPath = join(input.outDir, "compiled-artifacts-workflow-world.mjs");
+ const sandboxPreparedArtifacts = sandboxPreparedArtifactsManifestSchema.parse(
+ JSON.parse(await readFile(input.compileResult.paths.sandboxPreparedArtifactsPath, "utf8")),
+ );
const prepared = await prepareAuthoredRuntimeModules({
manifest: input.compileResult.manifest,
moduleMapPath: input.compileResult.paths.moduleMapPath,
@@ -87,6 +94,7 @@ export async function writeCompiledArtifactsFiles(input: {
installModulePath: resolvePackageSourceFilePath("src/runtime/loaders/bundled-artifacts.ts"),
metadata: input.compileResult.metadata,
moduleMapImportPath: moduleMapPath,
+ sandboxPreparedArtifacts,
}),
);
await writeFile(
@@ -251,6 +259,7 @@ export function createCompiledArtifactsBootstrapSource(input: {
installModulePath: string;
metadata: CompileMetadata;
moduleMapImportPath: string;
+ sandboxPreparedArtifacts: SandboxPreparedArtifactsManifest;
}): string {
const agentName = input.compileResult.manifest.config.name;
@@ -266,6 +275,8 @@ export function createCompiledArtifactsBootstrapSource(input: {
"",
`const manifest = ${JSON.stringify(input.compileResult.manifest, null, 2)};`,
"",
+ `const sandboxPreparedArtifacts = ${JSON.stringify(input.sandboxPreparedArtifacts, null, 2)};`,
+ "",
"export { moduleMap };",
"",
"export function installCompiledArtifactsBootstrap() {",
@@ -273,6 +284,7 @@ export function createCompiledArtifactsBootstrapSource(input: {
" manifest,",
" metadata,",
" moduleMap,",
+ " sandboxPreparedArtifacts,",
" });",
"}",
"",
diff --git a/packages/eve/src/internal/authored-definition/sandbox.ts b/packages/eve/src/internal/authored-definition/sandbox.ts
deleted file mode 100644
index fc0d9f15c..000000000
--- a/packages/eve/src/internal/authored-definition/sandbox.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import {
- expectFunction,
- expectObjectRecord,
- expectOnlyKnownKeys,
-} from "#internal/authored-module.js";
-import { lazyBackend } from "#execution/sandbox/lazy-backend.js";
-import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
-import type { SandboxDefinition, SandboxRevalidationKeyFn } from "#public/definitions/sandbox.js";
-
-type NormalizedSandboxDefinition = Readonly<Omit<SandboxDefinition, "backend">> & {
- readonly backend?: SandboxBackend;
- readonly description?: string;
- readonly revalidationKey?: SandboxRevalidationKeyFn;
-};
-
-/**
- * Normalizes one authored sandbox definition into the canonical internal
- * shape. If the author supplied a `backend` callback (e.g.
- * `backend: () => vercel({...})`), it is wrapped via
- * {@link lazyBackend} so downstream consumers always see a plain
- * `SandboxBackend` value — the callback fires exactly once on first
- * access and the resulting backend is memoized.
- */
-export function normalizeSandboxDefinition(
- value: unknown,
- message: string,
-): NormalizedSandboxDefinition {
- const record = expectObjectRecord(value, message);
- expectOnlyKnownKeys(
- record,
- ["backend", "bootstrap", "description", "onSession", "revalidationKey"],
- message,
- );
- const definition: {
- backend?: NormalizedSandboxDefinition["backend"];
- description?: NormalizedSandboxDefinition["description"];
- bootstrap?: NormalizedSandboxDefinition["bootstrap"];
- onSession?: NormalizedSandboxDefinition["onSession"];
- revalidationKey?: NormalizedSandboxDefinition["revalidationKey"];
- } = {};
-
- if (record.backend !== undefined) {
- definition.backend = expectSandboxBackend(record.backend, message);
- }
-
- if (record.description !== undefined) {
- if (typeof record.description !== "string") {
- throw new Error(`${message} The "description" field must be a string when set.`);
- }
- definition.description = record.description;
- }
-
- if (record.bootstrap !== undefined) {
- definition.bootstrap = expectFunction(record.bootstrap, message);
- }
-
- if (record.revalidationKey !== undefined) {
- definition.revalidationKey = expectFunction(record.revalidationKey, message);
- }
-
- if (definition.bootstrap === undefined && definition.revalidationKey !== undefined) {
- throw new Error(
- `${message} The "revalidationKey" field can only be set when "bootstrap" is set.`,
- );
- }
-
- if (record.onSession !== undefined) {
- definition.onSession = expectFunction(record.onSession, message);
- }
-
- return definition;
-}
-
-function expectSandboxBackend(value: unknown, message: string): SandboxBackend {
- if (typeof value === "function") {
- return lazyBackend(value as () => SandboxBackend);
- }
-
- const record = expectObjectRecord(
- value,
- `${message} The "backend" field must be a SandboxBackend value (use docker(), vercel(), or your own factory) or a zero-arg function returning one.`,
- );
-
- if (typeof record.name !== "string" || record.name.length === 0) {
- throw new Error(
- `${message} The "backend" value must expose a non-empty string "name" identifier.`,
- );
- }
-
- if (typeof record.create !== "function") {
- throw new Error(`${message} The "backend" value must expose a "create" function.`);
- }
-
- if (record.prewarm !== undefined && typeof record.prewarm !== "function") {
- throw new Error(`${message} The "backend.prewarm" property must be a function when set.`);
- }
-
- return record as unknown as SandboxBackend;
-}
diff --git a/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts b/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts
index 48af9c529..89d7511c3 100644
--- a/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts
+++ b/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts
@@ -292,13 +292,11 @@ describe("development generation artifacts", () => {
}
const sandbox = modules[child.agent.sandbox.sourceId] as {
- defineSelfModificationSandbox(options: { backend: { name: string } }): {
- backend(): { name: string };
- };
+ defineSelfModificationSandbox(): Function;
};
- const backend = { name: "disabled-local-test" };
- // Local mode ignores this backend and installs the writable host filesystem instead.
- expect(sandbox.defineSelfModificationSandbox({ backend }).backend()).toBe(backend);
+ const selector = await sandbox.defineSelfModificationSandbox();
+ expect(selector).toBeTypeOf("function");
+ expect("backend" in selector).toBe(false);
} finally {
if (previousDev === undefined) delete process.env.EVE_DEV;
else process.env.EVE_DEV = previousDev;
diff --git a/packages/eve/src/internal/nitro/host/artifacts-config.ts b/packages/eve/src/internal/nitro/host/artifacts-config.ts
index 7b6b405c3..b21f4d08b 100644
--- a/packages/eve/src/internal/nitro/host/artifacts-config.ts
+++ b/packages/eve/src/internal/nitro/host/artifacts-config.ts
@@ -1,4 +1,7 @@
+import { createHash } from "node:crypto";
+
import { resolvePackageSourceFilePath } from "#internal/application/package.js";
+import { createDiskRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import { resolveDevelopmentRuntimeArtifactsPointerPath } from "#internal/nitro/dev-runtime-artifacts.js";
import type {
DevelopmentNitroArtifactsConfig,
@@ -12,6 +15,20 @@ import type { AgentWorkflowWorldDefinition } from "#shared/agent-definition.js";
* artifacts from the authored app root via the snapshot pointer so hot
* reload can swap them.
*/
+export function createDevelopmentGenerationArtifactsSource(input: {
+ readonly appRoot: string;
+ readonly configuredWorld?: AgentWorkflowWorldDefinition;
+ readonly runtimeAppRoot: string;
+}) {
+ return createDiskRuntimeCompiledArtifactsSource(input.runtimeAppRoot, {
+ durableReference: usesParentDevelopmentWorkflowWorld(input.configuredWorld)
+ ? "development-generation"
+ : undefined,
+ moduleMapLoaderPath: resolvePackageSourceFilePath("src/internal/authored-module-map-loader.ts"),
+ sandboxAppRoot: input.appRoot,
+ });
+}
+
export function createDevelopmentNitroArtifactsConfig(input: {
readonly appRoot: string;
readonly configuredWorld?: AgentWorkflowWorldDefinition;
@@ -34,8 +51,11 @@ export function createDevelopmentNitroArtifactsConfig(input: {
* Runtime-artifacts wiring for built output: routes require the artifacts
* bundled into the server at build time and never touch the filesystem.
*/
-export function createProductionNitroArtifactsConfig(): ProductionNitroArtifactsConfig {
+export function createProductionNitroArtifactsConfig(
+ appRoot: string,
+): ProductionNitroArtifactsConfig {
return {
kind: "production",
+ sandboxScope: createHash("sha256").update(appRoot).digest("hex").slice(0, 16),
};
}
diff --git a/packages/eve/src/internal/nitro/host/build-application.scenario.test.ts b/packages/eve/src/internal/nitro/host/build-application.scenario.test.ts
index cdb509bb3..32c261ab4 100644
--- a/packages/eve/src/internal/nitro/host/build-application.scenario.test.ts
+++ b/packages/eve/src/internal/nitro/host/build-application.scenario.test.ts
@@ -85,6 +85,7 @@ const buildNitroMock = vi.fn(async (nitro: Nitro) => {
const copyPublicAssetsMock = vi.fn(async () => undefined);
const createProductionApplicationNitroMock = vi.fn();
const prepareProductionApplicationHostMock = vi.fn();
+const refreshProductionCompiledArtifactsMock = vi.fn(async () => undefined);
const prepareMock = vi.fn(async () => undefined);
const prerenderMock = vi.fn(async () => undefined);
const resolveDiscoveryProjectMock = vi.fn(async (appRoot: string) => ({
@@ -92,6 +93,7 @@ const resolveDiscoveryProjectMock = vi.fn(async (appRoot: string) => ({
appRoot,
layout: "nested" as const,
}));
+const prewarmAppSandboxesMock = vi.fn(async () => undefined);
const runVercelBuildPrewarmMock = vi.fn(async () => undefined);
vi.mock("nitro/builder", () => ({
@@ -107,6 +109,7 @@ vi.mock("./create-application-nitro.js", () => ({
vi.mock("./prepare-application-host.js", () => ({
prepareProductionApplicationHost: prepareProductionApplicationHostMock,
+ refreshProductionCompiledArtifacts: refreshProductionCompiledArtifactsMock,
}));
vi.mock("#discover/project.js", () => ({
@@ -117,6 +120,10 @@ vi.mock("./vercel-build-prewarm.js", () => ({
runVercelBuildPrewarm: runVercelBuildPrewarmMock,
}));
+vi.mock("#execution/sandbox/prewarm.js", () => ({
+ prewarmAppSandboxes: prewarmAppSandboxesMock,
+}));
+
const createScratchDirectory = useTemporaryDirectories();
const DEPLOYABLE_BUILD_OPTIONS = { skipVercelSandboxPrewarm: false } as const;
@@ -232,6 +239,21 @@ describe("buildApplication", () => {
)}\n`,
);
expect(runVercelBuildPrewarmMock).not.toHaveBeenCalled();
+ expect(prewarmAppSandboxesMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ appRoot,
+ compiledArtifactsSource: expect.objectContaining({
+ kind: "disk",
+ sandboxAppRoot: appRoot,
+ }),
+ }),
+ );
+ expect(prewarmAppSandboxesMock.mock.invocationCallOrder[0]).toBeLessThan(
+ refreshProductionCompiledArtifactsMock.mock.invocationCallOrder[0]!,
+ );
+ expect(refreshProductionCompiledArtifactsMock.mock.invocationCallOrder[0]).toBeLessThan(
+ buildNitroMock.mock.invocationCallOrder[0]!,
+ );
await expect(
readFile(join(appRoot, ".eve", "compile", "compiled-agent-manifest.json"), "utf8"),
).rejects.toThrow();
@@ -545,6 +567,7 @@ describe("buildApplication", () => {
expect(outputDir).toBe(join(appRoot, ".vercel", "output"));
expect(runVercelBuildPrewarmMock).not.toHaveBeenCalled();
+ expect(prewarmAppSandboxesMock).not.toHaveBeenCalled();
expect(buildNitroMock).toHaveBeenCalledTimes(1);
});
diff --git a/packages/eve/src/internal/nitro/host/build-application.ts b/packages/eve/src/internal/nitro/host/build-application.ts
index f0554a590..19168e9c1 100644
--- a/packages/eve/src/internal/nitro/host/build-application.ts
+++ b/packages/eve/src/internal/nitro/host/build-application.ts
@@ -34,8 +34,13 @@ import { emitVercelAgentSummary } from "#internal/nitro/host/build-vercel-agent-
import { tryReadExtensionBuildConfig } from "#internal/nitro/host/build-extension.js";
import { copyHostMiddlewareFunctions } from "#internal/nitro/host/copy-host-middleware.js";
import { normalizeVercelServiceCrons } from "#internal/nitro/host/normalize-vercel-service-crons.js";
-import { prepareProductionApplicationHost } from "#internal/nitro/host/prepare-application-host.js";
+import {
+ prepareProductionApplicationHost,
+ refreshProductionCompiledArtifacts,
+} from "#internal/nitro/host/prepare-application-host.js";
+import { createProductionNitroArtifactsConfig } from "#internal/nitro/host/artifacts-config.js";
import { runVercelBuildPrewarm } from "#internal/nitro/host/vercel-build-prewarm.js";
+import { prewarmAppSandboxes } from "#execution/sandbox/prewarm.js";
import type { ApplicationBuildOptions } from "#internal/nitro/host/types.js";
import { findClosestVercelOutputDirectory } from "#shared/vercel-output-directory.js";
import { toErrorMessage } from "#shared/errors.js";
@@ -311,6 +316,7 @@ async function buildApplicationInWorkspace(
);
}
const publicRoutePrefix = options.publicRoutePrefix ?? inferredPublicRoutePrefix;
+ const sandboxScope = createProductionNitroArtifactsConfig(workspace.appRoot).sandboxScope;
const nitro = await measureBuildPhase(profiler, "nitro.create", () =>
createProductionApplicationNitro(preparedHost, {
buildDir: workspace.nitro.buildDir,
@@ -321,26 +327,33 @@ async function buildApplicationInWorkspace(
);
try {
- // Run sandbox prewarm before bundling so a prewarm failure aborts the
- // build before we spend time producing output we would never deploy.
- if (isVercelBuild && !options.skipVercelSandboxPrewarm) {
- await measureBuildPhase(profiler, "sandbox.prewarm", () =>
- runVercelBuildPrewarm({
- appRoot: preparedHost.appRoot,
- compiledArtifactsSource: createDiskRuntimeCompiledArtifactsSource(
- workspace.compiler.rootDir,
- {
- moduleMapLoaderPath: resolvePackageSourceFilePath(
- "src/internal/authored-module-map-loader.ts",
- ),
- sandboxAppRoot: preparedHost.appRoot,
- },
- ),
- log(message) {
- console.log(message);
+ // Complete sandbox preparation before bundling so runtime never needs to
+ // mutate or repair the prepared artifacts embedded in production output.
+ if (!options.skipVercelSandboxPrewarm) {
+ const prewarmInput = {
+ appRoot: preparedHost.appRoot,
+ compiledArtifactsSource: createDiskRuntimeCompiledArtifactsSource(
+ workspace.compiler.rootDir,
+ {
+ moduleMapLoaderPath: resolvePackageSourceFilePath(
+ "src/internal/authored-module-map-loader.ts",
+ ),
+ sandboxAppRoot: preparedHost.appRoot,
+ sandboxScope,
},
- }),
- );
+ ),
+ log(message: string) {
+ console.log(message);
+ },
+ };
+ await measureBuildPhase(profiler, "sandbox.prewarm", async () => {
+ if (isVercelBuild) {
+ await runVercelBuildPrewarm(prewarmInput);
+ } else {
+ await prewarmAppSandboxes(prewarmInput);
+ }
+ });
+ await refreshProductionCompiledArtifacts(preparedHost, workspace.host.artifactsDir);
}
await buildNitroOutput(nitro, profiler, "nitro");
if (isVercelBuild) {
diff --git a/packages/eve/src/internal/nitro/host/compiled-sandbox-backend-prune-plugin.test.ts b/packages/eve/src/internal/nitro/host/compiled-sandbox-backend-prune-plugin.test.ts
deleted file mode 100644
index 7e659a15a..000000000
--- a/packages/eve/src/internal/nitro/host/compiled-sandbox-backend-prune-plugin.test.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { createCompiledSandboxBackendPrunePlugin } from "./compiled-sandbox-backend-prune-plugin.js";
-
-describe("createCompiledSandboxBackendPrunePlugin", () => {
- it("keeps the hosted local-backend stub aligned with the local facade exports", () => {
- const plugin = createCompiledSandboxBackendPrunePlugin();
- const resolved = plugin.resolveId?.(
- "/repo/packages/eve/dist/src/execution/sandbox/bindings/local.js",
- undefined,
- );
- if (resolved == null) {
- throw new Error("Expected local backend binding to resolve to the pruned stub.");
- }
- const id = typeof resolved === "object" ? resolved.id : resolved;
-
- const source = plugin.load?.(id);
-
- expect(source).toContain("export const isLinuxDockerDaemonAvailableSync = () => false;");
- expect(source).toContain("export const stopDevelopmentSandboxResources = pruned;");
- });
-});
diff --git a/packages/eve/src/internal/nitro/host/compiled-sandbox-backend-prune-plugin.ts b/packages/eve/src/internal/nitro/host/compiled-sandbox-backend-prune-plugin.ts
deleted file mode 100644
index 5334dcaba..000000000
--- a/packages/eve/src/internal/nitro/host/compiled-sandbox-backend-prune-plugin.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-const PRUNED_LOCAL_SANDBOX_MODULE_ID = "\0eve-pruned-local-sandbox-backends";
-const LOCAL_BINDING_SOURCE_RE = /[/\\]bindings[/\\]local\.js$/;
-
-interface BundlerPluginShape {
- readonly name: string;
- load?(id: string): string | null | undefined;
- resolveId?(
- source: string,
- importer: string | undefined,
- ): string | { id: string } | null | undefined;
-}
-
-/**
- * Creates the bundler plugin that prunes the local sandbox backends
- * (Docker, just-bash, microsandbox) from hosted Nitro server bundles.
- * Every local-engine export flows through `bindings/local.js`, so
- * stubbing that one module removes all of them; the stub mirrors the
- * facade's export surface.
- */
-export function createCompiledSandboxBackendPrunePlugin(): BundlerPluginShape {
- return {
- name: "eve-hosted-sandbox-backend-prune",
- load(id) {
- if (id !== PRUNED_LOCAL_SANDBOX_MODULE_ID) {
- return null;
- }
-
- return [
- "function pruned() {",
- ' throw new Error("Local sandbox backends are pruned from hosted server bundles.");',
- "}",
- "export const createDockerSandboxBackend = pruned;",
- "export const createJustBashSandboxBackend = pruned;",
- "export const createMicrosandboxSandboxBackend = pruned;",
- 'export const DOCKER_BACKEND_NAME = "docker";',
- 'export const JUST_BASH_BACKEND_NAME = "just-bash";',
- 'export const MICROSANDBOX_BACKEND_NAME = "microsandbox";',
- "export const isLinuxDockerDaemonAvailableSync = () => false;",
- "export const isMicrosandboxPlatformSupported = () => false;",
- "export const pruneDockerSandboxTemplates = pruned;",
- "export const pruneJustBashSandboxTemplates = pruned;",
- "export const pruneMicrosandboxTemplates = pruned;",
- "export const pruneLocalSandboxTemplates = pruned;",
- "export const pruneLocalSandboxTemplatesInBackground = pruned;",
- "export const stopDevelopmentSandboxResources = pruned;",
- "",
- ].join("\n");
- },
- resolveId(source) {
- if (!LOCAL_BINDING_SOURCE_RE.test(source)) {
- return null;
- }
-
- return PRUNED_LOCAL_SANDBOX_MODULE_ID;
- },
- };
-}
diff --git a/packages/eve/src/internal/nitro/host/compiled-sandbox-provider-prune-plugin.test.ts b/packages/eve/src/internal/nitro/host/compiled-sandbox-provider-prune-plugin.test.ts
new file mode 100644
index 000000000..5127294af
--- /dev/null
+++ b/packages/eve/src/internal/nitro/host/compiled-sandbox-provider-prune-plugin.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from "vitest";
+
+import { createCompiledSandboxProviderPrunePlugin } from "./compiled-sandbox-provider-prune-plugin.js";
+
+describe("createCompiledSandboxProviderPrunePlugin", () => {
+ it("replaces framework default selection with the hosted Vercel provider", () => {
+ const plugin = createCompiledSandboxProviderPrunePlugin();
+ const source = plugin.load?.("/repo/packages/eve/src/sandbox/providers/default.ts");
+
+ expect(source).toContain('DefaultSandbox = { name: "default", environment }');
+ expect(source).toContain("options.vercel");
+ expect(source).toContain("prepare: options.prepare");
+ });
+
+ it("replaces local provider constructors with hosted stubs", () => {
+ const plugin = createCompiledSandboxProviderPrunePlugin();
+ const source = plugin.load?.("/repo/packages/eve/src/sandbox/providers/microsandbox.ts");
+
+ expect(source).toContain("MicrosandboxSandbox");
+ });
+
+ it.each(["docker.ts", "just-bash.ts", "local.js", "local.ts", "microsandbox.ts"])(
+ "keeps the hosted local-backend stub aligned for %s",
+ (fileName) => {
+ const plugin = createCompiledSandboxProviderPrunePlugin();
+ const resolved = plugin.resolveId?.(
+ `/repo/packages/eve/dist/src/execution/sandbox/bindings/${fileName}`,
+ undefined,
+ );
+ if (resolved == null) {
+ throw new Error("Expected local backend binding to resolve to the pruned stub.");
+ }
+ const id = typeof resolved === "object" ? resolved.id : resolved;
+
+ const source = plugin.load?.(id);
+
+ expect(source).toContain("export const isLinuxDockerDaemonAvailableSync = () => false;");
+ expect(source).toContain("export const stopDevelopmentSandboxResources = pruned;");
+ },
+ );
+});
diff --git a/packages/eve/src/internal/nitro/host/compiled-sandbox-provider-prune-plugin.ts b/packages/eve/src/internal/nitro/host/compiled-sandbox-provider-prune-plugin.ts
new file mode 100644
index 000000000..d7c2aee79
--- /dev/null
+++ b/packages/eve/src/internal/nitro/host/compiled-sandbox-provider-prune-plugin.ts
@@ -0,0 +1,116 @@
+const PRUNED_DEFAULT_SANDBOX_MODULE_ID = "\0eve-pruned-default-sandbox-provider";
+const PRUNED_LOCAL_SANDBOX_MODULE_ID = "\0eve-pruned-local-sandbox-providers";
+const PRUNED_LOCAL_SANDBOX_PROVIDER_MODULE_ID = "\0eve-pruned-local-sandbox-provider-constructors";
+const PRUNED_OPTIONAL_ENGINE_INSTALL_MODULE_ID = "\0eve-pruned-optional-engine-install";
+const DEFAULT_PROVIDER_SOURCE_RE = /(?:^|[/\\#])sandbox[/\\]providers[/\\]default\.(?:js|ts)$/;
+const LOCAL_BINDING_SOURCE_RE =
+ /[/\\]bindings[/\\](?:docker|just-bash|local|microsandbox)\.(?:js|ts)$/;
+const LOCAL_PROVIDER_SOURCE_RE =
+ /(?:^|[/\\#])sandbox[/\\]providers[/\\](?:docker|just-bash|microsandbox)\.(?:js|ts)$/;
+const OPTIONAL_ENGINE_INSTALL_SOURCE_RE =
+ /[/\\]internal[/\\]application[/\\]optional-package-install\.(?:js|ts)$/;
+
+interface BundlerPluginShape {
+ readonly enforce?: "pre";
+ readonly name: string;
+ load?(id: string): string | null | undefined;
+ resolveId?(
+ source: string,
+ importer: string | undefined,
+ ): string | { id: string } | null | undefined;
+}
+
+/**
+ * Creates the bundler plugin that prunes the local sandbox providers
+ * (Docker, just-bash, microsandbox) from hosted Nitro server bundles.
+ * Stubs both the aggregate local facade and individual provider bindings so
+ * framework default selection cannot retain local engine implementations.
+ */
+export function createCompiledSandboxProviderPrunePlugin(): BundlerPluginShape {
+ return {
+ enforce: "pre",
+ name: "eve-hosted-sandbox-provider-prune",
+ load(id) {
+ const sourcePath = id.split(/[?#]/u, 1)[0] ?? id;
+ if (id === PRUNED_DEFAULT_SANDBOX_MODULE_ID || DEFAULT_PROVIDER_SOURCE_RE.test(sourcePath)) {
+ return [
+ 'import { createDefaultVercelEnvironment } from "#sandbox/providers/vercel.js";',
+ "function environment(options = {}) {",
+ " const vercelOptions = Object.assign({}, options.vercel, options.prepare === undefined ? {} : { prepare: options.prepare });",
+ " return createDefaultVercelEnvironment(vercelOptions);",
+ "}",
+ 'export const DefaultSandbox = { name: "default", environment };',
+ "export const SANDBOX_PROVIDER_PROBES = {};",
+ 'export function defineDefaultSandboxProvider() { return { name: "default", environment }; }',
+ "",
+ ].join("\n");
+ }
+ if (
+ id === PRUNED_OPTIONAL_ENGINE_INSTALL_MODULE_ID ||
+ OPTIONAL_ENGINE_INSTALL_SOURCE_RE.test(sourcePath)
+ ) {
+ return [
+ "function pruned() {",
+ ' throw new Error("Optional local sandbox engines cannot be installed in hosted server runtimes.");',
+ "}",
+ "export const detectProjectPackageManager = pruned;",
+ "export const importInstalledEnginePackage = pruned;",
+ "export const installPackageIntoProject = pruned;",
+ "export const loadOptionalEnginePackage = pruned;",
+ "",
+ ].join("\n");
+ }
+ if (
+ id === PRUNED_LOCAL_SANDBOX_PROVIDER_MODULE_ID ||
+ LOCAL_PROVIDER_SOURCE_RE.test(sourcePath)
+ ) {
+ return [
+ "function pruned() {",
+ ' throw new Error("Local sandbox providers are pruned from hosted server bundles.");',
+ "}",
+ 'export const DockerSandbox = { name: "docker", environment: pruned, dockerfile: pruned, image: pruned };',
+ 'export const JustBashSandbox = { name: "just-bash", environment: pruned };',
+ 'export const MicrosandboxSandbox = { name: "microsandbox", environment: pruned, dockerfile: pruned, image: pruned };',
+ "",
+ ].join("\n");
+ }
+ if (id !== PRUNED_LOCAL_SANDBOX_MODULE_ID && !LOCAL_BINDING_SOURCE_RE.test(sourcePath)) {
+ return null;
+ }
+
+ return [
+ "function pruned() {",
+ ' throw new Error("Local sandbox providers are pruned from hosted server bundles.");',
+ "}",
+ "export const createDockerSandboxProvider = pruned;",
+ "export const createJustBashSandboxProvider = pruned;",
+ "export const createMicrosandboxSandboxProvider = pruned;",
+ 'export const DOCKER_PROVIDER_NAME = "docker";',
+ 'export const DOCKER_TEMPLATE_IMAGE_REPOSITORY = "eve-sandbox-template";',
+ 'export const JUST_BASH_PROVIDER_NAME = "just-bash";',
+ 'export const MICROSANDBOX_PROVIDER_NAME = "microsandbox";',
+ "export const isLinuxDockerDaemonAvailableSync = () => false;",
+ "export const isMicrosandboxPlatformSupported = () => false;",
+ "export const pruneDockerSandboxTemplates = pruned;",
+ "export const pruneJustBashSandboxTemplates = pruned;",
+ "export const pruneMicrosandboxTemplates = pruned;",
+ "export const pruneLocalSandboxTemplates = pruned;",
+ "export const pruneLocalSandboxTemplatesInBackground = pruned;",
+ "export const stopDevelopmentSandboxResources = pruned;",
+ "",
+ ].join("\n");
+ },
+ resolveId(source) {
+ const sourcePath = source.split(/[?#]/u, 1)[0] ?? source;
+ if (DEFAULT_PROVIDER_SOURCE_RE.test(sourcePath)) return PRUNED_DEFAULT_SANDBOX_MODULE_ID;
+ if (LOCAL_PROVIDER_SOURCE_RE.test(sourcePath)) {
+ return PRUNED_LOCAL_SANDBOX_PROVIDER_MODULE_ID;
+ }
+ if (OPTIONAL_ENGINE_INSTALL_SOURCE_RE.test(sourcePath)) {
+ return PRUNED_OPTIONAL_ENGINE_INSTALL_MODULE_ID;
+ }
+ if (!LOCAL_BINDING_SOURCE_RE.test(sourcePath)) return null;
+ return PRUNED_LOCAL_SANDBOX_MODULE_ID;
+ },
+ };
+}
diff --git a/packages/eve/src/internal/nitro/host/configure-nitro-routes.ts b/packages/eve/src/internal/nitro/host/configure-nitro-routes.ts
index ac7fbd7f8..831c46f83 100644
--- a/packages/eve/src/internal/nitro/host/configure-nitro-routes.ts
+++ b/packages/eve/src/internal/nitro/host/configure-nitro-routes.ts
@@ -415,7 +415,11 @@ export async function configureProductionNitroRoutes(
await registerWorkflowArtifactBuildHook(nitro, syncWorkflowArtifacts);
const routeRegistry = createApplicationRouteRegistry(preparedHost);
- registerApplicationRoutes(nitro, createProductionNitroArtifactsConfig(), routeRegistry);
+ registerApplicationRoutes(
+ nitro,
+ createProductionNitroArtifactsConfig(preparedHost.appRoot),
+ routeRegistry,
+ );
const workflowBundlePath = join(preparedHost.workflowBuildDir, "workflows.mjs");
const hasConfiguredWorkflowWorld =
diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.test.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.test.ts
index cb33b3687..387fa141a 100644
--- a/packages/eve/src/internal/nitro/host/create-application-nitro.test.ts
+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.test.ts
@@ -1,40 +1,40 @@
import { describe, expect, it } from "vitest";
-import { shouldPruneLocalSandboxBackends } from "#internal/nitro/host/create-application-nitro.js";
+import { shouldPruneLocalSandboxProviders } from "#internal/nitro/host/create-application-nitro.js";
-describe("shouldPruneLocalSandboxBackends", () => {
- it("prunes local backends from hosted Vercel builds when the sandbox uses defaultSandbox", () => {
+describe("shouldPruneLocalSandboxProviders", () => {
+ it("prunes local providers from hosted Vercel builds when the sandbox uses defaultSandbox", () => {
expect(
- shouldPruneLocalSandboxBackends({
+ shouldPruneLocalSandboxProviders({
configuredBackendNames: new Set(),
preset: "vercel",
}),
).toBe(true);
});
- it("keeps local backends when a local backend is configured explicitly", () => {
- for (const backendName of ["docker", "microsandbox", "just-bash"]) {
+ it("keeps local providers when a local backend is configured explicitly", () => {
+ for (const providerName of ["docker", "microsandbox", "just-bash"]) {
expect(
- shouldPruneLocalSandboxBackends({
- configuredBackendNames: new Set([backendName]),
+ shouldPruneLocalSandboxProviders({
+ configuredBackendNames: new Set([providerName]),
preset: "vercel",
}),
).toBe(false);
}
});
- it("still prunes local backends when only Vercel or custom backends are configured", () => {
+ it("still prunes local providers when only Vercel or custom backends are configured", () => {
expect(
- shouldPruneLocalSandboxBackends({
+ shouldPruneLocalSandboxProviders({
configuredBackendNames: new Set(["vercel", "custom"]),
preset: "vercel",
}),
).toBe(true);
});
- it("does not prune local backends for non-Vercel presets", () => {
+ it("does not prune local providers for non-Vercel presets", () => {
expect(
- shouldPruneLocalSandboxBackends({
+ shouldPruneLocalSandboxProviders({
configuredBackendNames: new Set(),
preset: undefined,
}),
diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.ts
index c2e4e666e..224617fd9 100644
--- a/packages/eve/src/internal/nitro/host/create-application-nitro.ts
+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.ts
@@ -17,7 +17,7 @@ import {
writeEveVersionedCacheMetadata,
} from "#internal/application/cache-metadata.js";
import { createProductionNitroArtifactsConfig } from "#internal/nitro/host/artifacts-config.js";
-import { createCompiledSandboxBackendPrunePlugin } from "#internal/nitro/host/compiled-sandbox-backend-prune-plugin.js";
+import { createCompiledSandboxProviderPrunePlugin } from "#internal/nitro/host/compiled-sandbox-provider-prune-plugin.js";
import { createExtensionScopePlugin } from "#internal/bundler/extension-scope-plugin.js";
import {
createExtensionExternalDependencyPlugin,
@@ -137,29 +137,29 @@ function collectExtensionExternalDependencies(manifest: CompiledAgentManifest):
* and subagents) selected, so the host build can make backend-aware
* packaging decisions.
*/
-function collectConfiguredSandboxBackendNames(manifest: CompiledAgentManifest): Set<string> {
+function collectConfiguredSandboxProviderNames(manifest: CompiledAgentManifest): Set<string> {
const nodes = [manifest, ...manifest.subagents.map((subagent) => subagent.agent)];
return new Set(
nodes
- .map((node) => node.sandbox?.backendName)
- .filter((backendName): backendName is string => typeof backendName === "string"),
+ .map((node) => node.sandbox?.providerName)
+ .filter((providerName): providerName is string => typeof providerName === "string"),
);
}
/**
- * Hosted Vercel builds can prune local sandbox backends only when the
+ * Hosted Vercel builds can prune local sandbox providers only when the
* app did not explicitly configure one. Omitted backends resolve through
- * `defaultSandbox()`, which selects Vercel on hosted Vercel and never
+ * `DefaultSandbox.environment()`, which selects Vercel on hosted Vercel and never
* needs local runtime code there.
*/
-export function shouldPruneLocalSandboxBackends(input: {
+export function shouldPruneLocalSandboxProviders(input: {
readonly configuredBackendNames: ReadonlySet<string>;
readonly preset: "vercel" | undefined;
}): boolean {
return (
input.preset === "vercel" &&
- ![...input.configuredBackendNames].some((backendName) =>
- LOCAL_SANDBOX_BACKEND_NAMES.has(backendName),
+ ![...input.configuredBackendNames].some((providerName) =>
+ LOCAL_SANDBOX_BACKEND_NAMES.has(providerName),
)
);
}
@@ -556,21 +556,21 @@ function createApplicationNitroBundlerConfiguration(
preparedHost: PreparedApplicationHost,
preset: "vercel" | undefined,
) {
- const configuredBackendNames = collectConfiguredSandboxBackendNames(
+ const configuredBackendNames = collectConfiguredSandboxProviderNames(
preparedHost.compileResult.manifest,
);
- const compiledSandboxBackendPrunePlugin = shouldPruneLocalSandboxBackends({
+ const compiledSandboxProviderPrunePlugin = shouldPruneLocalSandboxProviders({
configuredBackendNames,
preset,
})
- ? createCompiledSandboxBackendPrunePlugin()
+ ? createCompiledSandboxProviderPrunePlugin()
: null;
const configuredOptionalEnginePackages: string[] = [];
const unconfiguredOptionalEnginePackages: string[] = [];
- for (const [backendName, packageName] of Object.entries(
+ for (const [providerName, packageName] of Object.entries(
OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME,
)) {
- (configuredBackendNames.has(backendName)
+ (configuredBackendNames.has(providerName)
? configuredOptionalEnginePackages
: unconfiguredOptionalEnginePackages
).push(packageName);
@@ -591,7 +591,7 @@ function createApplicationNitroBundlerConfiguration(
...preparedHost.compileResult.manifest.subagents.map((subagent) => subagent.agent),
].flatMap((node) => node.extensionMounts);
const nitroBundlerPlugins = [
- compiledSandboxBackendPrunePlugin,
+ compiledSandboxProviderPrunePlugin,
createOptionalEngineDependencyPlugin(unconfiguredOptionalEnginePackages),
createExtensionExternalDependencyPlugin(extensionMounts),
extensionScopePlugin,
@@ -815,7 +815,7 @@ export async function createProductionApplicationNitro(
if (preparedHost.scheduleRegistrations.length > 0) {
applyEveCronHandlerRoute(nitro);
- const artifactsConfig = createProductionNitroArtifactsConfig();
+ const artifactsConfig = createProductionNitroArtifactsConfig(preparedHost.appRoot);
registerScheduleTaskHandlers(nitro, {
artifactsConfig,
dispatchModulePath: resolvePackageSourceFilePath(
diff --git a/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.test.ts b/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.test.ts
index 7e18d9e05..6a9beb861 100644
--- a/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.test.ts
+++ b/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.test.ts
@@ -51,13 +51,10 @@ vi.mock("#internal/nitro/development-generation.js", () => ({
discardDevelopmentGeneration: mocks.discardDevelopmentGeneration,
}));
vi.mock("#internal/nitro/host/artifacts-config.js", () => ({
- createDevelopmentNitroArtifactsConfig: () => ({}),
-}));
-vi.mock("#internal/nitro/routes/runtime-artifacts.js", () => ({
- resolveNitroCompiledArtifactsSource: () => ({}),
+ createDevelopmentGenerationArtifactsSource: () => ({ kind: "disk" }),
}));
vi.mock("#execution/sandbox/development-prewarm.js", () => ({
- startDevelopmentSandboxPrewarmInBackground: vi.fn(),
+ prewarmDevelopmentSandboxes: vi.fn(async () => {}),
}));
function createHost(
diff --git a/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.ts b/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.ts
index 9bd34e070..e6231cc3d 100644
--- a/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.ts
+++ b/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.ts
@@ -1,8 +1,6 @@
-import { relative, resolve } from "node:path";
-
import { stageDevelopmentEnvironmentFiles } from "#cli/dev/environment.js";
-import { startDevelopmentSandboxPrewarmInBackground } from "#execution/sandbox/development-prewarm.js";
-import { createDevelopmentNitroArtifactsConfig } from "#internal/nitro/host/artifacts-config.js";
+import { prewarmDevelopmentSandboxes } from "#execution/sandbox/development-prewarm.js";
+import { createDevelopmentGenerationArtifactsSource } from "#internal/nitro/host/artifacts-config.js";
import { createDevelopmentApplicationNitro } from "#internal/nitro/host/create-application-nitro.js";
import { buildDevelopmentHostCandidate } from "#internal/nitro/host/dev-host-candidate.js";
import { computeDevelopmentHostFingerprint } from "#internal/nitro/host/dev-host-fingerprint.js";
@@ -15,7 +13,6 @@ import {
activateDevelopmentGeneration,
discardDevelopmentGeneration,
} from "#internal/nitro/development-generation.js";
-import { resolveNitroCompiledArtifactsSource } from "#internal/nitro/routes/runtime-artifacts.js";
export type DevelopmentRebuildKind = "structural" | "unchanged" | "runtime";
@@ -124,6 +121,7 @@ class TransactionalDevelopmentAuthoredRebuildCoordinator implements DevelopmentA
) {
throw new DevelopmentWorkflowWorldChangeRequiresRestartError();
}
+ await prewarmDevelopmentHost(nextHost);
const nextHostFingerprint = await computeDevelopmentHostFingerprint(nextHost);
const nextRuntimeFingerprint = nextHost.generation.fingerprint;
const hasStructuralChange = nextHostFingerprint !== this.#currentHostFingerprint;
@@ -155,7 +153,6 @@ class TransactionalDevelopmentAuthoredRebuildCoordinator implements DevelopmentA
this.#commitState(committedHost, nextHostFingerprint, nextRuntimeFingerprint);
nextHost = undefined;
environmentReload.commit();
- startSandboxPrewarmAfterCommit(committedHost, input.changedPaths);
return { host: committedHost, kind: "runtime" };
}
@@ -167,7 +164,6 @@ class TransactionalDevelopmentAuthoredRebuildCoordinator implements DevelopmentA
});
nextHost = undefined;
environmentReload.commit();
- startSandboxPrewarmAfterCommit(result.host, input.changedPaths);
return result;
} catch (error) {
if (error instanceof PostCommitDevelopmentRebuildError) {
@@ -266,40 +262,18 @@ function retainActiveHostWorkspace(
};
}
-function startSandboxPrewarmAfterCommit(
- host: PreparedDevelopmentApplicationHost,
- changedPaths: readonly string[],
-): void {
- if (!hasSandboxRelatedChange(host.compileResult.project.agentRoot, changedPaths)) {
- return;
- }
- const artifactsConfig = createDevelopmentNitroArtifactsConfig({
- appRoot: host.appRoot,
- configuredWorld: host.compileResult.manifest.config.experimental?.workflow?.world,
- });
- startDevelopmentSandboxPrewarmInBackground({
+async function prewarmDevelopmentHost(host: PreparedDevelopmentApplicationHost): Promise<void> {
+ await prewarmDevelopmentSandboxes({
appRoot: host.appRoot,
- compiledArtifactsSource: resolveNitroCompiledArtifactsSource(artifactsConfig),
+ compiledArtifactsSource: createDevelopmentGenerationArtifactsSource({
+ appRoot: host.appRoot,
+ configuredWorld: host.compileResult.manifest.config.experimental?.workflow?.world,
+ runtimeAppRoot: host.generation.runtimeAppRoot,
+ }),
log: (message) => console.log(message),
});
}
-function hasSandboxRelatedChange(agentRoot: string, changedPaths: readonly string[]): boolean {
- return changedPaths.some((path) => {
- const relativePath = relative(resolve(agentRoot), resolve(path));
- const segments = relativePath.split(/[\\/]/u);
- if (segments[0] === ".." || relativePath === "") {
- return false;
- }
- return (
- segments[0] === "sandbox.ts" ||
- segments[0] === "sandbox" ||
- segments[0] === "workspace" ||
- segments[0] === "skills"
- );
- });
-}
-
async function discardPreparedHost(host: PreparedDevelopmentApplicationHost): Promise<void> {
const cleanup = await Promise.allSettled([
discardDevelopmentGeneration(host.generation),
diff --git a/packages/eve/src/internal/nitro/host/dev-host-fingerprint.ts b/packages/eve/src/internal/nitro/host/dev-host-fingerprint.ts
index 029b27f05..503c9e3aa 100644
--- a/packages/eve/src/internal/nitro/host/dev-host-fingerprint.ts
+++ b/packages/eve/src/internal/nitro/host/dev-host-fingerprint.ts
@@ -30,11 +30,11 @@ export async function computeDevelopmentHostFingerprint(
sourceRoot: mount.sourceRoot,
}))
.sort((left, right) => left.sourceRoot.localeCompare(right.sourceRoot)),
- sandboxBackends: [
+ sandboxProviders: [
...new Set(
agentNodes
- .map((node) => node.sandbox?.backendName)
- .filter((backendName): backendName is string => backendName !== undefined),
+ .map((node) => node.sandbox?.providerName)
+ .filter((providerName): providerName is string => providerName !== undefined),
),
].sort((left, right) => left.localeCompare(right)),
},
diff --git a/packages/eve/src/internal/nitro/host/prepare-application-host.ts b/packages/eve/src/internal/nitro/host/prepare-application-host.ts
index e57e4dea8..78c647dda 100644
--- a/packages/eve/src/internal/nitro/host/prepare-application-host.ts
+++ b/packages/eve/src/internal/nitro/host/prepare-application-host.ts
@@ -132,6 +132,17 @@ export async function prepareProductionApplicationHost(
});
}
+export async function refreshProductionCompiledArtifacts(
+ host: PreparedApplicationHost,
+ outDir: string,
+): Promise<void> {
+ await writeCompiledArtifactsFiles({
+ compileResult: host.compileResult,
+ defaultWorkflowWorld: resolveProductionWorkflowWorldTarget(),
+ outDir,
+ });
+}
+
function createPreparedApplicationHost(input: {
readonly compileResult: CompileAgentResult;
readonly compiledArtifacts: PreparedApplicationHost["compiledArtifacts"];
diff --git a/packages/eve/src/internal/nitro/host/relocated-production.scenario.test.ts b/packages/eve/src/internal/nitro/host/relocated-production.scenario.test.ts
index 82a11d45c..cd848e467 100644
--- a/packages/eve/src/internal/nitro/host/relocated-production.scenario.test.ts
+++ b/packages/eve/src/internal/nitro/host/relocated-production.scenario.test.ts
@@ -3,7 +3,6 @@ import { join } from "node:path";
import { describe, expect, it } from "vitest";
-import { prewarmBuiltAppSandboxes } from "#execution/sandbox/prewarm.js";
import { useScenarioApp } from "#internal/testing/scenario-app.js";
import { buildApplication } from "./build-application.js";
import { startProductionServer } from "./start-production-server.js";
@@ -32,17 +31,16 @@ describe("relocated production applications", () => {
"apps/service/agent/skills/probe.md":
"---\ndescription: Probe the sandbox.\n---\nProbe content.",
"apps/service/agent/sandbox/sandbox.ts": [
- 'import { justbash } from "eve/sandbox/just-bash";',
+ 'import { defineSandbox } from "eve/sandbox";',
+ 'import { JustBashSandbox } from "eve/sandbox/just-bash";',
'import { marker } from "@/marker";',
- "export default {",
- " backend: justbash(),",
- ' revalidationKey: () => "relocated-v1",',
- " async bootstrap({ use }) {",
- " const sandbox = await use();",
+ "export const environment = JustBashSandbox.environment({",
+ " prepare: async (sandbox) => {",
" const result = await sandbox.run({ command: `echo ${marker}` });",
' if (result.stdout.trim() !== "app-bootstrap") throw new Error("Wrong app alias");',
" },",
- "};",
+ "});",
+ "export default defineSandbox(() => environment.open());",
].join("\n"),
"apps/service/agent/extensions/acme.ts":
'import extension from "@acme/relocated"; export default extension();',
@@ -90,19 +88,6 @@ describe("relocated production applications", () => {
await expect(access(buildRoot)).rejects.toMatchObject({ code: "ENOENT" });
const runtimeAppRoot = join(runtimeRoot, "apps", "service");
- const prewarmedRoots: string[] = [];
- const seededPaths: string[] = [];
- await prewarmBuiltAppSandboxes({
- appRoot: runtimeAppRoot,
- dispatch: async ({ backend, input }) => {
- prewarmedRoots.push(input.runtimeContext.appRoot);
- seededPaths.push(...(input.seedFiles ?? []).map((file) => file.path));
- return await backend.prewarm(input);
- },
- });
- expect(prewarmedRoots).toEqual([runtimeAppRoot]);
- expect(seededPaths).toContain("$HOME/.agents/skills/probe/SKILL.md");
-
const server = await startProductionServer(runtimeAppRoot, { host: "127.0.0.1", port: 0 });
try {
expect((await fetch(new URL("/eve/v1/health", server.url))).status).toBe(200);
diff --git a/packages/eve/src/internal/nitro/host/sandbox-shutdown-plugin.test.ts b/packages/eve/src/internal/nitro/host/sandbox-shutdown-plugin.test.ts
index 6ebcd7332..c89b18c49 100644
--- a/packages/eve/src/internal/nitro/host/sandbox-shutdown-plugin.test.ts
+++ b/packages/eve/src/internal/nitro/host/sandbox-shutdown-plugin.test.ts
@@ -63,8 +63,8 @@ describe("installSandboxShutdownHandlers", () => {
});
it("stops tracked sandboxes and exits 143 on SIGTERM", async () => {
- const handle = { shutdown: vi.fn(async () => {}) };
- trackActiveSandboxHandle({ backendName: "docker", handle, sessionKey: "session-1" });
+ const handle = { onRuntimeShutdown: vi.fn(async () => {}) };
+ trackActiveSandboxHandle({ providerName: "docker", handle, sessionId: "session-1" });
const fakeProcess = createFakeProcess();
installSandboxShutdownHandlers({ log: () => {}, process: fakeProcess });
@@ -73,12 +73,12 @@ describe("installSandboxShutdownHandlers", () => {
await vi.waitFor(() => {
expect(fakeProcess.exit).toHaveBeenCalledWith(143);
});
- expect(handle.shutdown).toHaveBeenCalledTimes(1);
+ expect(handle.onRuntimeShutdown).toHaveBeenCalledTimes(1);
});
it("stops tracked sandboxes and exits 130 on SIGINT", async () => {
- const handle = { shutdown: vi.fn(async () => {}) };
- trackActiveSandboxHandle({ backendName: "docker", handle, sessionKey: "session-1" });
+ const handle = { onRuntimeShutdown: vi.fn(async () => {}) };
+ trackActiveSandboxHandle({ providerName: "docker", handle, sessionId: "session-1" });
const fakeProcess = createFakeProcess();
installSandboxShutdownHandlers({ log: () => {}, process: fakeProcess });
@@ -87,12 +87,12 @@ describe("installSandboxShutdownHandlers", () => {
await vi.waitFor(() => {
expect(fakeProcess.exit).toHaveBeenCalledWith(130);
});
- expect(handle.shutdown).toHaveBeenCalledTimes(1);
+ expect(handle.onRuntimeShutdown).toHaveBeenCalledTimes(1);
});
it("stops tracked sandboxes through the nitro close hook", async () => {
- const handle = { shutdown: vi.fn(async () => {}) };
- trackActiveSandboxHandle({ backendName: "docker", handle, sessionKey: "session-1" });
+ const handle = { onRuntimeShutdown: vi.fn(async () => {}) };
+ trackActiveSandboxHandle({ providerName: "docker", handle, sessionId: "session-1" });
let closeHandler: (() => Promise<void>) | undefined;
const nitroApp = {
hooks: {
@@ -112,7 +112,7 @@ describe("installSandboxShutdownHandlers", () => {
});
await closeHandler?.();
- expect(handle.shutdown).toHaveBeenCalledTimes(1);
+ expect(handle.onRuntimeShutdown).toHaveBeenCalledTimes(1);
});
});
@@ -120,8 +120,8 @@ describe("runSandboxShutdown", () => {
it("exits even when a handle shutdown never settles", async () => {
vi.useFakeTimers();
try {
- const handle = { shutdown: vi.fn(() => new Promise<void>(() => {})) };
- trackActiveSandboxHandle({ backendName: "docker", handle, sessionKey: "session-1" });
+ const handle = { onRuntimeShutdown: vi.fn(() => new Promise<void>(() => {})) };
+ trackActiveSandboxHandle({ providerName: "docker", handle, sessionId: "session-1" });
const log = vi.fn();
const shutdown = runSandboxShutdown(log);
diff --git a/packages/eve/src/internal/nitro/host/sandbox-shutdown-plugin.ts b/packages/eve/src/internal/nitro/host/sandbox-shutdown-plugin.ts
index 716a33743..4e762fcfb 100644
--- a/packages/eve/src/internal/nitro/host/sandbox-shutdown-plugin.ts
+++ b/packages/eve/src/internal/nitro/host/sandbox-shutdown-plugin.ts
@@ -1,5 +1,5 @@
import { shutdownActiveSandboxHandles } from "#execution/sandbox/active-handles.js";
-import { isEveDevEnvironment } from "#internal/application/optional-package-install.js";
+import { isEveDevEnvironment } from "#internal/application/dev-environment.js";
const SHUTDOWN_SIGNALS = ["SIGINT", "SIGTERM"] as const;
type ShutdownSignal = (typeof SHUTDOWN_SIGNALS)[number];
diff --git a/packages/eve/src/internal/nitro/host/schedule-task-routes.test.ts b/packages/eve/src/internal/nitro/host/schedule-task-routes.test.ts
index fea1ce78a..d9e6bde79 100644
--- a/packages/eve/src/internal/nitro/host/schedule-task-routes.test.ts
+++ b/packages/eve/src/internal/nitro/host/schedule-task-routes.test.ts
@@ -16,6 +16,7 @@ const DISPATCH_MODULE_PATH = "/framework/schedule-task.ts";
const ARTIFACTS_CONFIG = {
kind: "production",
+ sandboxScope: "test-sandbox-scope",
} as const;
describe("schedule task routes", () => {
diff --git a/packages/eve/src/internal/nitro/host/start-development-server.test.ts b/packages/eve/src/internal/nitro/host/start-development-server.test.ts
index 1a2dc1e12..f85213930 100644
--- a/packages/eve/src/internal/nitro/host/start-development-server.test.ts
+++ b/packages/eve/src/internal/nitro/host/start-development-server.test.ts
@@ -199,12 +199,12 @@ vi.mock("#discover/project.js", () => ({
resolveDiscoveryProject: mocks.resolveDiscoveryProject,
}));
-vi.mock("#internal/nitro/routes/runtime-artifacts.js", () => ({
- resolveNitroCompiledArtifactsSource: mocks.resolveNitroCompiledArtifactsSource,
+vi.mock("#internal/nitro/host/artifacts-config.js", () => ({
+ createDevelopmentGenerationArtifactsSource: () => mocks.resolveNitroCompiledArtifactsSource(),
}));
vi.mock("#execution/sandbox/development-prewarm.js", () => ({
- startDevelopmentSandboxPrewarmInBackground: mocks.startDevelopmentSandboxPrewarmInBackground,
+ prewarmDevelopmentSandboxes: mocks.startDevelopmentSandboxPrewarmInBackground,
}));
vi.mock("#execution/sandbox/bindings/local.js", () => ({
diff --git a/packages/eve/src/internal/nitro/host/start-development-server.ts b/packages/eve/src/internal/nitro/host/start-development-server.ts
index 80bc7fd94..a8e366fc7 100644
--- a/packages/eve/src/internal/nitro/host/start-development-server.ts
+++ b/packages/eve/src/internal/nitro/host/start-development-server.ts
@@ -5,7 +5,7 @@ import type { Nitro } from "nitro/types";
import { createDevelopmentApplicationNitro } from "#internal/nitro/host/create-application-nitro.js";
import { DrainedNitroDevServer } from "#internal/nitro/host/drained-nitro-dev-server.js";
-import { createDevelopmentNitroArtifactsConfig } from "#internal/nitro/host/artifacts-config.js";
+import { createDevelopmentGenerationArtifactsSource } from "#internal/nitro/host/artifacts-config.js";
import type { AuthoredSourceWatcherHandle } from "#internal/nitro/host/dev-authored-source-watcher.js";
import { prepareDevelopmentApplicationHost } from "#internal/nitro/host/prepare-application-host.js";
import { buildDevelopmentHostCandidate } from "#internal/nitro/host/dev-host-candidate.js";
@@ -23,12 +23,11 @@ import { toErrorMessage } from "#shared/errors.js";
import { isLoopbackServerUrl } from "#shared/network-address.js";
import { readDevelopmentRuntimeArtifactsRevision } from "#services/dev-client/runtime-artifacts.js";
import { handleDevRuntimeArtifactsRequest } from "#internal/nitro/routes/dev-runtime-artifacts.js";
-import { resolveNitroCompiledArtifactsSource } from "#internal/nitro/routes/runtime-artifacts.js";
import {
pruneLocalSandboxTemplatesInBackground,
stopDevelopmentSandboxResources,
} from "#execution/sandbox/bindings/local.js";
-import { startDevelopmentSandboxPrewarmInBackground } from "#execution/sandbox/development-prewarm.js";
+import { prewarmDevelopmentSandboxes } from "#execution/sandbox/development-prewarm.js";
import {
createDevelopmentSandboxRunId,
EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV,
@@ -436,11 +435,19 @@ async function startNitroDevelopmentServer(
options.onBootProgress,
);
preparedDevelopmentHost = preparedHost;
- const compiledArtifactsSource = resolveNitroCompiledArtifactsSource(
- createDevelopmentNitroArtifactsConfig({
- appRoot: preparedHost.appRoot,
- configuredWorld: preparedHost.compileResult.manifest.config.experimental?.workflow?.world,
- }),
+ await devBootPhase(
+ "preparing sandbox templates",
+ () =>
+ prewarmDevelopmentSandboxes({
+ appRoot: preparedHost.appRoot,
+ compiledArtifactsSource: createDevelopmentGenerationArtifactsSource({
+ appRoot: preparedHost.appRoot,
+ configuredWorld:
+ preparedHost.compileResult.manifest.config.experimental?.workflow?.world,
+ runtimeAppRoot: preparedHost.generation.runtimeAppRoot,
+ }),
+ }),
+ options.onBootProgress,
);
pruneLocalSandboxTemplatesInBackground(preparedHost.appRoot);
const activeNitro = await devBootPhase(
@@ -523,10 +530,6 @@ async function startNitroDevelopmentServer(
options.onBootProgress,
);
await workflowWorld?.start();
- startDevelopmentSandboxPrewarmInBackground({
- appRoot: preparedHost.appRoot,
- compiledArtifactsSource,
- });
const rebuildCoordinator = await createDevelopmentAuthoredRebuildCoordinator({
devServer: activeDevServer,
diff --git a/packages/eve/src/internal/nitro/host/start-production-server.test.ts b/packages/eve/src/internal/nitro/host/start-production-server.test.ts
index 715657523..ccac624c9 100644
--- a/packages/eve/src/internal/nitro/host/start-production-server.test.ts
+++ b/packages/eve/src/internal/nitro/host/start-production-server.test.ts
@@ -7,7 +7,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
existsSync: vi.fn(() => true),
loadDevelopmentEnvironmentFiles: vi.fn(),
- prewarmBuiltAppSandboxes: vi.fn(async () => undefined),
spawn: vi.fn(),
}));
@@ -25,10 +24,6 @@ vi.mock("#cli/dev/environment.js", () => ({
loadDevelopmentEnvironmentFiles: mocks.loadDevelopmentEnvironmentFiles,
}));
-vi.mock("#execution/sandbox/prewarm.js", () => ({
- prewarmBuiltAppSandboxes: mocks.prewarmBuiltAppSandboxes,
-}));
-
function createChildProcess(): ChildProcess {
const child = new EventEmitter() as ChildProcess;
const stdout = new PassThrough();
@@ -98,10 +93,6 @@ describe("startProductionServer", () => {
expect(server.url).toBe("http://127.0.0.1:4321/");
expect(mocks.loadDevelopmentEnvironmentFiles).toHaveBeenCalledWith("/tmp/app");
- expect(mocks.prewarmBuiltAppSandboxes).toHaveBeenCalledWith({
- appRoot: "/tmp/app",
- log: expect.any(Function),
- });
expect(mocks.spawn).toHaveBeenCalledWith(
process.execPath,
["/tmp/app/.output/server/index.mjs"],
diff --git a/packages/eve/src/internal/nitro/host/start-production-server.ts b/packages/eve/src/internal/nitro/host/start-production-server.ts
index 768bdc479..294fda6c9 100644
--- a/packages/eve/src/internal/nitro/host/start-production-server.ts
+++ b/packages/eve/src/internal/nitro/host/start-production-server.ts
@@ -5,7 +5,6 @@ import { join, resolve } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
import { loadDevelopmentEnvironmentFiles } from "#cli/dev/environment.js";
-import { prewarmBuiltAppSandboxes } from "#execution/sandbox/prewarm.js";
import type { ProductionServerHandle } from "#internal/nitro/host/types.js";
const DEFAULT_PRODUCTION_SERVER_HOST = "0.0.0.0";
@@ -205,10 +204,6 @@ export async function startProductionServer(
}
await loadDevelopmentEnvironmentFiles(appRoot);
- await prewarmBuiltAppSandboxes({
- appRoot,
- log: (message) => console.log(message),
- });
const host = options.host ?? DEFAULT_PRODUCTION_SERVER_HOST;
const port = await resolveListenPort({
diff --git a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.test.ts b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.test.ts
index 74600ef96..fd450425f 100644
--- a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.test.ts
+++ b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.test.ts
@@ -34,7 +34,7 @@ describe("buildAgentInfoResponse", () => {
},
capabilities: { devRoutes: true },
kind: "eve-agent-info",
- version: 4,
+ version: 5,
});
expect(response.tools.static).toContainEqual(
expect.objectContaining({
diff --git a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts
index 532e28124..495b3ce1c 100644
--- a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts
+++ b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts
@@ -142,12 +142,9 @@ export function buildAgentInfoResponse(
},
sandbox: {
...toModuleSource(manifest, manifest.sandbox),
- backendKind: manifest.sandbox.backendName,
- description: manifest.sandbox.description,
- hasBootstrap: false,
- hasOnSession: false,
- revalidationKey: manifest.sandbox.revalidationKey,
- sourceHash: manifest.sandbox.sourceHash,
+ provider: manifest.sandbox.providerName,
+ environmentExportName: manifest.sandbox.environmentExportName,
+ revisionHash: manifest.sandbox.revisionHash,
},
schedules: manifest.schedules.map((schedule) => ({
...toOwnedSource(manifest, schedule),
@@ -205,7 +202,7 @@ export function buildAgentInfoResponse(
requiresApproval: tool.requiresApproval,
})),
},
- version: 4,
+ version: 5,
workspace: {
resourceRoot: manifest.workspaceResourceRoot,
rootEntries: [...manifest.workspaceResourceRoot.rootEntries],
diff --git a/packages/eve/src/internal/nitro/routes/info.test.ts b/packages/eve/src/internal/nitro/routes/info.test.ts
index 5c7709f1b..280d93f10 100644
--- a/packages/eve/src/internal/nitro/routes/info.test.ts
+++ b/packages/eve/src/internal/nitro/routes/info.test.ts
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
- buildAgentInfoResponse: vi.fn(() => ({ kind: "eve-agent-info", version: 4 })),
+ buildAgentInfoResponse: vi.fn(() => ({ kind: "eve-agent-info", version: 6 })),
getVercelOidcToken: vi.fn(),
refreshChatGptState: vi.fn(async () => ({ kind: "ready" as const })),
loadAgentInfoManifestData: vi.fn(async (): Promise<unknown> => ({
diff --git a/packages/eve/src/internal/nitro/routes/runtime-artifacts.test.ts b/packages/eve/src/internal/nitro/routes/runtime-artifacts.test.ts
index 9a30323af..dcd49dc39 100644
--- a/packages/eve/src/internal/nitro/routes/runtime-artifacts.test.ts
+++ b/packages/eve/src/internal/nitro/routes/runtime-artifacts.test.ts
@@ -66,9 +66,11 @@ describe("resolveNitroCompiledArtifactsSource", () => {
expect(
resolveNitroCompiledArtifactsSource({
kind: "production",
+ sandboxScope: "test-sandbox-scope",
}),
).toEqual({
kind: "bundled",
+ sandboxScope: "test-sandbox-scope",
});
});
});
@@ -76,8 +78,8 @@ describe("resolveNitroCompiledArtifactsSource", () => {
it("does not fall back to the authored build path in production", async () => {
await withScopedRuntimeSession(() => {
const productionConfig = {
- appRoot: "/tmp/build-machine-app",
kind: "production" as const,
+ sandboxScope: "test-sandbox-scope",
};
expect(() => resolveNitroCompiledArtifactsSource(productionConfig)).toThrow(
"requires bundled artifacts",
diff --git a/packages/eve/src/internal/nitro/routes/runtime-artifacts.ts b/packages/eve/src/internal/nitro/routes/runtime-artifacts.ts
index 42161bec5..25c3c12e5 100644
--- a/packages/eve/src/internal/nitro/routes/runtime-artifacts.ts
+++ b/packages/eve/src/internal/nitro/routes/runtime-artifacts.ts
@@ -27,6 +27,7 @@ export interface DevelopmentNitroArtifactsConfig {
export interface ProductionNitroArtifactsConfig {
readonly kind: "production";
+ readonly sandboxScope: string;
}
export type NitroArtifactsConfig = DevelopmentNitroArtifactsConfig | ProductionNitroArtifactsConfig;
@@ -51,7 +52,7 @@ export function resolveNitroCompiledArtifactsSource(
}
if (readBundledCompiledArtifacts() !== null) {
- return createBundledRuntimeCompiledArtifactsSource();
+ return createBundledRuntimeCompiledArtifactsSource(config.sandboxScope);
}
throw new Error("eve Nitro production requires bundled artifacts.");
diff --git a/packages/eve/src/internal/runtime-registry.ts b/packages/eve/src/internal/runtime-registry.ts
index ff1f7b351..db0fe1533 100644
--- a/packages/eve/src/internal/runtime-registry.ts
+++ b/packages/eve/src/internal/runtime-registry.ts
@@ -11,8 +11,8 @@ export interface RuntimeRegistryEntryLocation {
/**
* Error raised when a runtime-owned subsystem rejects an entry — for
- * example a duplicate authored sandbox name, a tool name reserved by the
- * framework, or a subagent whose node id is already taken.
+ * example a tool name reserved by the framework or a subagent whose node id
+ * is already taken.
*
* The `registry` field identifies which subsystem produced the error
* (`"sandbox"`, `"tool"`, `"subagent"`, …) so consumers can branch on
diff --git a/packages/eve/src/internal/testing/agent-info-fixture.ts b/packages/eve/src/internal/testing/agent-info-fixture.ts
index 4d657514a..ffc27b183 100644
--- a/packages/eve/src/internal/testing/agent-info-fixture.ts
+++ b/packages/eve/src/internal/testing/agent-info-fixture.ts
@@ -60,10 +60,10 @@ export function createTestAgentInfoResult(
logicalPath: "sandbox.ts",
owner,
},
- hasBootstrap: false,
- hasOnSession: false,
+ environmentExportName: "environment",
logicalPath: "sandbox.ts",
owner,
+ revisionHash: "sandbox-revision",
sourceId: "sandbox.ts",
sourceKind: "module",
},
@@ -71,7 +71,7 @@ export function createTestAgentInfoResult(
skills: { dynamic: [], static: [] },
subagents: { local: [], total: 0 },
tools: { dynamic: [], static: [] },
- version: 4,
+ version: 5,
workspace: { resourceRoot: null, rootEntries: [] },
};
}
diff --git a/packages/eve/src/internal/testing/app-harness.ts b/packages/eve/src/internal/testing/app-harness.ts
index c39a4ea74..6edcb8288 100644
--- a/packages/eve/src/internal/testing/app-harness.ts
+++ b/packages/eve/src/internal/testing/app-harness.ts
@@ -17,7 +17,7 @@ import { resolveRuntimeAgentGraph } from "#runtime/resolve-agent-graph.js";
import { createNodeHarnessTools } from "#execution/node-step.js";
import { serializeInputSchema, serializeOutputSchema } from "#tools/schema.js";
import { defineSandbox } from "#public/definitions/sandbox.js";
-import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
+import { defineSandboxProvider } from "#shared/sandbox-provider.js";
import {
buildActiveSessionContext,
type ActiveSessionInit,
@@ -144,25 +144,32 @@ const DEFAULT_AGENT_NAME = "test-agent";
*/
export const TEST_DEFAULT_MODEL_ID = "openai/gpt-5.4";
-const TEST_SANDBOX_BACKEND: SandboxBackend = {
+const TEST_SANDBOX_PROVIDER = defineSandboxProvider({
name: "eve-test-memory",
- async create(input) {
- const sandbox = mockSandbox({ id: input.sessionKey });
- return {
- session: sandbox.session,
- useSessionFn: async () => sandbox.session,
- captureState: async () => ({
- backendName: TEST_SANDBOX_BACKEND.name,
- metadata: {},
- sessionKey: input.sessionKey,
- }),
- delete: async (options) => await sandbox.access.delete?.(options),
- shutdown: async () => undefined,
- stop: async () => undefined,
- };
- },
- prewarm: async () => ({ reused: true }),
-};
+ environment: () => ({
+ async prepare() {
+ return null;
+ },
+ async resume(context) {
+ return createHandle(context.session.id);
+ },
+ async start(context) {
+ return { handle: createHandle(context.session.id), state: null };
+ },
+ }),
+});
+
+function createHandle(sessionId: string) {
+ const sandbox = mockSandbox({ id: sessionId });
+ return {
+ sandbox: sandbox.session,
+ async onSessionDelete(options?: import("#shared/sandbox-provider.js").SandboxDeleteOptions) {
+ await sandbox.access.delete?.(options);
+ },
+ async onSessionStop() {},
+ async onRuntimeShutdown() {},
+ };
+}
export async function createTestRuntime(descriptor: TestAppDescriptor = {}): Promise<TestRuntime> {
const compileInput: CompileFromMemoryInput = {
@@ -171,9 +178,10 @@ export async function createTestRuntime(descriptor: TestAppDescriptor = {}): Pro
limits: descriptor.agent?.limits,
modules: [
{
- loadNamespace: async () => ({
- default: defineSandbox({ backend: TEST_SANDBOX_BACKEND }),
- }),
+ loadNamespace: async () => {
+ const environment = TEST_SANDBOX_PROVIDER.environment();
+ return { environment, default: defineSandbox(() => environment.open()) };
+ },
logicalPath: "sandbox.ts",
},
...(descriptor.modules ?? []),
diff --git a/packages/eve/src/internal/testing/mocks/mock-sandbox.ts b/packages/eve/src/internal/testing/mocks/mock-sandbox.ts
index 28628d336..22f78a087 100644
--- a/packages/eve/src/internal/testing/mocks/mock-sandbox.ts
+++ b/packages/eve/src/internal/testing/mocks/mock-sandbox.ts
@@ -116,7 +116,6 @@ export interface MockSandbox {
* Builds an in-memory {@link MockSandbox} from a declarative descriptor.
*/
export function mockSandbox(input: MockSandboxInput = {}): MockSandbox {
- const sandboxId = input.id ?? "sbx_mock";
const files = new Map<string, string>();
const fileBytes = new Map<string, Buffer>();
const writes: MockSandboxWrite[] = [];
@@ -179,7 +178,6 @@ export function mockSandbox(input: MockSandboxInput = {}): MockSandbox {
}
const baseSession: SandboxSession = {
- id: sandboxId,
resolvePath(path: string): string {
return resolveWorkspacePath(path);
},
@@ -249,10 +247,7 @@ export function mockSandbox(input: MockSandboxInput = {}): MockSandbox {
const access: SandboxAccess = {
async captureState(): Promise<SandboxState> {
- return {
- initialized: false,
- session: null,
- };
+ return { session: null };
},
async delete(): Promise<void> {
await input.delete?.();
diff --git a/packages/eve/src/internal/testing/sandbox-provider-harness.ts b/packages/eve/src/internal/testing/sandbox-provider-harness.ts
new file mode 100644
index 000000000..511b98b02
--- /dev/null
+++ b/packages/eve/src/internal/testing/sandbox-provider-harness.ts
@@ -0,0 +1,109 @@
+import { createSandboxProviderFiles } from "#execution/sandbox/provider-files.js";
+import { createSandboxProviderHost } from "#execution/sandbox/provider-host.js";
+import {
+ createSandboxProviderResources,
+ type SandboxPreparedArtifact,
+ type SandboxProviderHandle,
+ type SandboxProviderImplementation,
+} from "#shared/sandbox-provider.js";
+import type { SandboxSession } from "#shared/sandbox-session.js";
+
+export function createSandboxProviderHarness<
+ Options extends object | undefined,
+ PreparedArtifact extends SandboxPreparedArtifact,
+ SessionState,
+ Session extends SandboxSession,
+>(
+ implementation: SandboxProviderImplementation<Options, PreparedArtifact, SessionState, Session>,
+ options: Options,
+ harnessOptions: {
+ readonly preparedArtifact?: () => PreparedArtifact;
+ } = {},
+) {
+ let preparedArtifact: PreparedArtifact | undefined;
+ async function resolveArtifact(input: {
+ readonly appRoot: string;
+ readonly prepared?: PreparedArtifact;
+ }): Promise<PreparedArtifact> {
+ return (
+ input.prepared ??
+ preparedArtifact ??
+ harnessOptions.preparedArtifact?.() ??
+ (await harness.prepare({ appRoot: input.appRoot }))
+ );
+ }
+
+ const harness = {
+ async prepare(input: {
+ readonly appRoot: string;
+ readonly log?: (message: string) => void;
+ readonly resourcesKey?: string;
+ readonly resourcesPath?: string;
+ readonly seedFiles?: readonly {
+ readonly content: string | Uint8Array;
+ readonly path: string;
+ }[];
+ readonly sourceRevision?: string;
+ }) {
+ const artifact = await implementation.prepare({
+ files: createSandboxProviderFiles(`${input.appRoot}/sandbox`),
+ host: createSandboxProviderHost(input.appRoot),
+ log: input.log,
+ resources: createSandboxProviderResources({
+ ...input,
+ resourcesKey:
+ input.resourcesKey ??
+ (input.seedFiles === undefined || input.seedFiles.length === 0
+ ? undefined
+ : "test-resources"),
+ }),
+ sourceRevision: input.sourceRevision ?? "test-source-revision",
+ storagePath: input.appRoot,
+ });
+ preparedArtifact = artifact;
+ return artifact;
+ },
+ async openSession(input: {
+ readonly appRoot: string;
+ readonly existing?: SessionState;
+ readonly prepared?: PreparedArtifact;
+ readonly sandboxName: string;
+ }): Promise<SandboxProviderHandle<Session>> {
+ const artifact = await resolveArtifact(input);
+ const context = {
+ host: createSandboxProviderHost(input.appRoot),
+ session: {
+ auth: { current: null, initiator: null },
+ id: input.sandboxName,
+ turn: { id: "test-turn", sequence: 0 },
+ },
+ storagePath: input.appRoot,
+ } as const;
+ if (input.existing === undefined) {
+ return (await implementation.start(context, options, artifact)).handle;
+ }
+ return await implementation.resume(context, artifact, input.existing);
+ },
+ async start(input: {
+ readonly appRoot: string;
+ readonly prepared?: PreparedArtifact;
+ readonly sandboxName: string;
+ }) {
+ const artifact = await resolveArtifact(input);
+ return await implementation.start(
+ {
+ host: createSandboxProviderHost(input.appRoot),
+ session: {
+ auth: { current: null, initiator: null },
+ id: input.sandboxName,
+ turn: { id: "test-turn", sequence: 0 },
+ },
+ storagePath: input.appRoot,
+ },
+ options,
+ artifact,
+ );
+ },
+ };
+ return harness;
+}
diff --git a/packages/eve/src/internal/testing/scenario-apps/extension-agent.ts b/packages/eve/src/internal/testing/scenario-apps/extension-agent.ts
index b7f7a6407..e16b367ee 100644
--- a/packages/eve/src/internal/testing/scenario-apps/extension-agent.ts
+++ b/packages/eve/src/internal/testing/scenario-apps/extension-agent.ts
@@ -21,12 +21,15 @@ export const EXTENSION_AGENT_DESCRIPTOR: ScenarioAppDescriptor = {
`,
"agent/lib/weather/tail.mjs": `export const TOOL_TAIL = "across cjs/js/mts/mjs modules.";
`,
- "agent/sandbox/sandbox.cjs": `module.exports = {
- async onSession({ use }) {
- const sandbox = await use();
- await sandbox.run({ command: "mkdir -p .extension-fixture" });
- },
-};
+ "agent/sandbox/sandbox.cjs": `const { DefaultSandbox, defineSandbox } = require("eve/sandbox");
+Object.defineProperty(exports, "__esModule", { value: true });
+const environment = DefaultSandbox.environment();
+exports.environment = environment;
+exports.default = defineSandbox(async () => {
+ const sandbox = await environment.open();
+ await sandbox.run({ command: "mkdir -p .extension-fixture" });
+ return sandbox;
+});
`,
"agent/schedules/nightly.cts": `export default {
cron: "0 0 * * *",
diff --git a/packages/eve/src/internal/testing/scenario-apps/sandbox-workspaces.ts b/packages/eve/src/internal/testing/scenario-apps/sandbox-workspaces.ts
index 04e5eb2ee..f674ff1b1 100644
--- a/packages/eve/src/internal/testing/scenario-apps/sandbox-workspaces.ts
+++ b/packages/eve/src/internal/testing/scenario-apps/sandbox-workspaces.ts
@@ -7,9 +7,10 @@ import type { ScenarioAppDescriptor } from "#internal/testing/scenario-app.js";
*/
export const SANDBOX_WORKSPACES_DESCRIPTOR: ScenarioAppDescriptor = {
files: {
- "agent/sandbox/sandbox.ts": `import { defineSandbox } from "eve/sandbox";
+ "agent/sandbox/sandbox.ts": `import { DefaultSandbox, defineSandbox } from "eve/sandbox";
-export default defineSandbox({});
+export const environment = DefaultSandbox.environment();
+export default defineSandbox(() => environment.open());
`,
"agent/sandbox/workspace/notes.md": `# repo-shell notes
diff --git a/packages/eve/src/internal/testing/stub-sandbox-registry.ts b/packages/eve/src/internal/testing/stub-sandbox-registry.ts
index 751fa542c..adc5acff9 100644
--- a/packages/eve/src/internal/testing/stub-sandbox-registry.ts
+++ b/packages/eve/src/internal/testing/stub-sandbox-registry.ts
@@ -1,21 +1,17 @@
-import { type RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";
-import { defaultSandbox } from "#public/sandbox/backends/default.js";
+import { defineSandbox } from "#public/definitions/sandbox.js";
+import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";
+import { DefaultSandbox } from "#sandbox/providers.js";
-/**
- * Stub registry for tests that exercise harness/execution paths that do
- * not touch the sandbox itself.
- *
- * Production code constructs registries via
- * `createRuntimeSandboxRegistry` from the resolved authored graph;
- * `RuntimeSandboxRegistry.sandbox` is non-null there. Tests that need a
- * registry but never call into the sandbox use this helper.
- */
export function createStubSandboxRegistry(): RuntimeSandboxRegistry {
+ const environment = DefaultSandbox.environment();
return {
sandbox: {
definition: {
- backend: defaultSandbox(),
+ environment,
+ kind: "independent",
logicalPath: "sandbox.ts",
+ revisionHash: "stub-sandbox-revision",
+ selector: defineSandbox(() => environment.open()),
sourceId: "test:stub-sandbox",
sourceKind: "module",
},
diff --git a/packages/eve/src/internal/vercel/build-agent-workspace.ts b/packages/eve/src/internal/vercel/build-agent-workspace.ts
index 499a415e3..617911270 100644
--- a/packages/eve/src/internal/vercel/build-agent-workspace.ts
+++ b/packages/eve/src/internal/vercel/build-agent-workspace.ts
@@ -34,7 +34,10 @@ function createMultiAgentSummary(workspace: AgentWorkspace): VercelEveMultiAgent
}
/** Emit the inferred Vercel Services project for a strict hostless workspace. */
-export async function buildAgentWorkspace(workspace: AgentWorkspace): Promise<string> {
+export async function buildAgentWorkspace(
+ workspace: AgentWorkspace,
+ options: { readonly skipSandboxPrewarm?: boolean } = {},
+): Promise<string> {
const config = await readVercelJsonFile(join(workspace.root, "vercel.json"));
if (
config.services !== undefined ||
@@ -51,7 +54,7 @@ export async function buildAgentWorkspace(workspace: AgentWorkspace): Promise<st
appRoot: member.appRoot,
buildCommand: `node ${quoteVercelShellArgument(
toVercelRelativePath(member.appRoot, resolveEveBinaryPath(member.appRoot)),
- )} build`,
+ )} build${options.skipSandboxPrewarm === true ? " --skip-sandbox-prewarm" : ""}`,
devCommand: `node ${quoteVercelShellArgument(
toVercelRelativePath(member.appRoot, resolveEveBinaryPath(member.appRoot)),
)} dev --no-ui`,
diff --git a/packages/eve/src/public/channels/github/checkout.ts b/packages/eve/src/public/channels/github/checkout.ts
index 6d26ba081..57badb51a 100644
--- a/packages/eve/src/public/channels/github/checkout.ts
+++ b/packages/eve/src/public/channels/github/checkout.ts
@@ -99,6 +99,9 @@ export async function checkoutGitHubRepository(
// (token-free) URL and the platform injects `Authorization` on egress to
// GitHub, so the token never enters the sandbox process. The `"*"` rule keeps
// the agent's other egress open.
+ if (sandbox.setNetworkPolicy === undefined) {
+ throw new Error("GitHub checkout requires a sandbox provider with mutable network policy.");
+ }
await sandbox.setNetworkPolicy(gitHubGitBrokerNetworkPolicy(token));
await runCheckoutCommand({
diff --git a/packages/eve/src/public/definitions/exact.test.ts b/packages/eve/src/public/definitions/exact.test.ts
index 02cdcd497..8cb7b17a6 100644
--- a/packages/eve/src/public/definitions/exact.test.ts
+++ b/packages/eve/src/public/definitions/exact.test.ts
@@ -23,6 +23,7 @@ import {
type ProviderDefinition,
} from "#public/definitions/instrumentation.js";
import { defineSandbox } from "#public/definitions/sandbox.js";
+import { DockerSandbox, VercelSandbox } from "#sandbox/providers.js";
import { defineSchedule } from "#public/definitions/schedule.js";
import { defineSkill } from "#public/definitions/skill.js";
import { defineTool, type TaskReceipt, type ToolDefinition } from "#public/tools/index.js";
@@ -444,40 +445,20 @@ function typeOnlyFixtures(): void {
},
});
- defineSandbox({
- async onSession({ ctx, use }) {
- const sessionId: string = ctx.session.id;
- // @ts-expect-error Sandbox lifecycle access is unavailable during session initialization.
- void ctx.getSandbox;
- // @ts-expect-error Skill access is unavailable during session initialization.
- void ctx.getSkill;
- const sandbox = await use();
- // @ts-expect-error Runtime lifecycle access is unavailable during session initialization.
- void sandbox.delete;
- void sandbox;
- void sessionId;
- },
- });
-
- defineSandbox({
- async bootstrap({ use }) {
- const sandbox = await use();
- void sandbox;
- },
- });
-
- defineSandbox({
- revalidationKey: () => "bootstrap-v1",
- async bootstrap({ use }) {
- const sandbox = await use();
- void sandbox;
- },
- });
-
- // @ts-expect-error Sandbox revalidation keys are only valid with bootstrap.
- defineSandbox({
- revalidationKey: () => "unused",
+ const environment = VercelSandbox.environment();
+ defineSandbox(async ({ session }) => {
+ const sandbox = await environment.open({
+ mounts: {},
+ networkPolicy: "deny-all",
+ resources: { vcpus: 4 },
+ });
+ const sessionId: string = session.id;
+ await sandbox.setNetworkPolicy?.("allow-all");
+ void sessionId;
+ return sandbox;
});
+ const dockerEnvironment = DockerSandbox.environment();
+ defineSandbox(() => dockerEnvironment.open({ networkPolicy: "deny-all" }));
defineTool({
description: "Fetch current weather for a city.",
diff --git a/packages/eve/src/public/definitions/sandbox-backend.ts b/packages/eve/src/public/definitions/sandbox-backend.ts
deleted file mode 100644
index 418131433..000000000
--- a/packages/eve/src/public/definitions/sandbox-backend.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-export type {
- SandboxBackendHandle,
- SandboxBackendSessionState,
- SandboxDeleteOptions,
- SandboxSeedFile,
- SandboxBackendTags,
- SandboxBackendRuntimeContext,
- SandboxBackendCreateInput,
- SandboxBackendPrewarmInput,
- SandboxBackendPrewarmResult,
- SandboxBackend,
-} from "#shared/sandbox-backend.js";
-
-/**
- * Thrown by a backend's `create` when the requested template was never
- * provisioned. Run `eve build` or call `prewarmAppSandboxes()` before
- * serving traffic. `backendName` and `templateKey` identify the missing
- * template. Use {@link SandboxTemplateNotProvisionedError.is} to narrow.
- */
-export class SandboxTemplateNotProvisionedError extends Error {
- readonly backendName: string;
- readonly templateKey: string;
-
- constructor(input: { readonly backendName: string; readonly templateKey: string }) {
- super(
- `Sandbox template "${input.templateKey}" is not provisioned for backend "${input.backendName}". Run \`eve build\` or invoke \`prewarmAppSandboxes()\` before serving traffic.`,
- );
- this.name = "SandboxTemplateNotProvisionedError";
- this.backendName = input.backendName;
- this.templateKey = input.templateKey;
- }
-
- /** Type guard for {@link SandboxTemplateNotProvisionedError}. */
- static is(error: unknown): error is SandboxTemplateNotProvisionedError {
- return (
- error instanceof SandboxTemplateNotProvisionedError ||
- (typeof error === "object" &&
- error !== null &&
- (error as { readonly name?: unknown }).name === "SandboxTemplateNotProvisionedError" &&
- typeof (error as { readonly backendName?: unknown }).backendName === "string" &&
- typeof (error as { readonly templateKey?: unknown }).templateKey === "string")
- );
- }
-}
diff --git a/packages/eve/src/public/definitions/sandbox.ts b/packages/eve/src/public/definitions/sandbox.ts
index 17eb33fd0..12ee76482 100644
--- a/packages/eve/src/public/definitions/sandbox.ts
+++ b/packages/eve/src/public/definitions/sandbox.ts
@@ -1,8 +1,4 @@
-import type { Optional } from "#shared/optional.js";
-import type {
- SandboxDefinitionWithBootstrap as SharedSandboxDefinitionWithBootstrap,
- SandboxDefinitionWithoutBootstrap as SharedSandboxDefinitionWithoutBootstrap,
-} from "#shared/sandbox-definition.js";
+import type { SandboxSelector } from "#shared/sandbox-environment.js";
export type {
SandboxCommandResult,
@@ -11,79 +7,36 @@ export type {
SandboxReadFileOptions,
SandboxRemovePathOptions,
SandboxReadTextFileOptions,
+ FixedNetworkSandboxSession,
+ MutableNetworkSandboxSession,
SandboxRunOptions,
SandboxSession,
RuntimeSandboxSession,
+ RuntimeSandboxSessionFor,
SandboxSpawnOptions,
SandboxWriteBinaryFileOptions,
SandboxWriteFileOptions,
SandboxWriteTextFileOptions,
} from "#shared/sandbox-session.js";
export type {
- SandboxBootstrapUseFn,
- SandboxRevalidationKeyFn,
- SandboxSessionUseFn,
- SandboxBootstrapContext,
- SandboxSessionContext,
-} from "#shared/sandbox-definition.js";
+ SandboxOpenArguments,
+ SandboxEnvironment,
+ SandboxSelector,
+ SandboxSelectorContext,
+} from "#shared/sandbox-environment.js";
-/** Opaque reference to an ancestor's durable sandbox. */
-export interface SandboxAncestorReference {
- readonly sandbox: SandboxParentValue;
-}
-
-/**
- * Opaque value returned from a sandbox definition to select its parent's
- * durable sandbox. It intentionally exposes no provider operations: authored
- * code can only return it to eve.
- */
-export interface SandboxParentValue {
- readonly __eveSandboxParentValue: unique symbol;
-}
+const SELECTOR = Symbol.for("eve.sandbox-selector");
+const PARENT = Symbol.for("eve.sandbox-parent-definition");
-/** Runtime ancestry passed to a parent-selecting sandbox definition. */
-export interface SandboxParentDefinitionContext {
- readonly parent: SandboxAncestorReference | null;
+export function defineSandbox(definition: SandboxSelector): SandboxSelector {
+ Object.defineProperty(definition, SELECTOR, { value: true });
+ return definition;
}
-/** A definition that selects the dispatching parent's exact sandbox. */
-export type SandboxParentDefinition = (
- context: SandboxParentDefinitionContext,
-) => SandboxParentValue | Promise<SandboxParentValue>;
-
-const SANDBOX_PARENT_DEFINITION_MARKER = Symbol.for("eve.sandbox-parent-definition");
-
-/**
- * The shape passed to {@link defineSandbox}: a discriminated union over
- * whether a `bootstrap` hook is present. `backend` is optional here (it is
- * required on the shared base): when omitted, eve substitutes
- * `defaultBackend()` at runtime. `BO`/`SO` type the options for the
- * bootstrap-use and session-use functions respectively.
- */
-export type SandboxDefinition<BO = Record<string, never>, SO = Record<string, never>> =
- | Optional<SharedSandboxDefinitionWithBootstrap<BO, SO>, "backend">
- | Optional<SharedSandboxDefinitionWithoutBootstrap<BO, SO>, "backend">;
-
-/**
- * Defines the sandbox an agent (or subagent) runs in. Authored at the
- * path-derived location `agent/sandbox.ts` (or `agent/sandbox/sandbox.ts`
- * when paired with a `workspace/` folder); subagents use
- * `subagents/<name>/sandbox.ts`.
- *
- * Pass an object to define an independent sandbox. Passing a callback to
- * `defineSandbox` opts into sharing: return `parent.sandbox` to select the
- * dispatching parent's exact durable sandbox. It is intended for child-only
- * definitions; throw when `parent` is `null`.
- */
-export function defineSandbox(definition: SandboxParentDefinition): SandboxParentDefinition;
-export function defineSandbox<BO = Record<string, never>, SO = Record<string, never>>(
- definition: SandboxDefinition<BO, SO>,
-): SandboxDefinition<BO, SO>;
-export function defineSandbox<BO = Record<string, never>, SO = Record<string, never>>(
- definition: SandboxDefinition<BO, SO> | SandboxParentDefinition,
-): SandboxDefinition<BO, SO> | SandboxParentDefinition {
- if (typeof definition === "function") {
- Object.defineProperty(definition, SANDBOX_PARENT_DEFINITION_MARKER, { value: true });
- }
- return definition;
+export function defineParentSandbox(): SandboxSelector {
+ const selector = defineSandbox(async () => {
+ throw new Error("Parent sandbox selection is resolved by eve.");
+ });
+ Object.defineProperty(selector, PARENT, { value: true });
+ return selector;
}
diff --git a/packages/eve/src/public/sandbox/backends/default.ts b/packages/eve/src/public/sandbox/backends/default.ts
deleted file mode 100644
index 1ee3b252d..000000000
--- a/packages/eve/src/public/sandbox/backends/default.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "#sandbox/backends/default.js";
diff --git a/packages/eve/src/public/sandbox/backends/docker.ts b/packages/eve/src/public/sandbox/backends/docker.ts
deleted file mode 100644
index 42e38faeb..000000000
--- a/packages/eve/src/public/sandbox/backends/docker.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "#sandbox/backends/docker.js";
diff --git a/packages/eve/src/public/sandbox/backends/just-bash.ts b/packages/eve/src/public/sandbox/backends/just-bash.ts
deleted file mode 100644
index b49338eba..000000000
--- a/packages/eve/src/public/sandbox/backends/just-bash.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "#sandbox/backends/just-bash.js";
diff --git a/packages/eve/src/public/sandbox/backends/microsandbox.ts b/packages/eve/src/public/sandbox/backends/microsandbox.ts
deleted file mode 100644
index 24940ec8f..000000000
--- a/packages/eve/src/public/sandbox/backends/microsandbox.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "#sandbox/backends/microsandbox.js";
diff --git a/packages/eve/src/public/sandbox/backends/vercel.ts b/packages/eve/src/public/sandbox/backends/vercel.ts
deleted file mode 100644
index 63a1b231a..000000000
--- a/packages/eve/src/public/sandbox/backends/vercel.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "#sandbox/backends/vercel.js";
diff --git a/packages/eve/src/public/sandbox/docker-sandbox.ts b/packages/eve/src/public/sandbox/docker-sandbox.ts
index cbe0abd47..fe3a494a3 100644
--- a/packages/eve/src/public/sandbox/docker-sandbox.ts
+++ b/packages/eve/src/public/sandbox/docker-sandbox.ts
@@ -1,48 +1,29 @@
-/**
- * Image pull behavior for the Docker sandbox backend.
- *
- * - `"if-not-present"` (default): pull the base image only when it is
- * missing from the local image store.
- * - `"always"`: pull before every template build so the image floats to
- * the registry's latest digest.
- * - `"never"`: never pull; fail when the image is missing locally.
- */
+import type { SandboxSession } from "#shared/sandbox-session.js";
+import type {
+ SandboxNetworkOptions,
+ SandboxNetworkPolicy,
+} from "#shared/sandbox-network-policy.js";
+
+/** Image pull behavior for Docker sandbox environments. */
export type DockerSandboxPullPolicy = "if-not-present" | "always" | "never";
-/**
- * Initial network policy for sandboxes created by the Docker backend.
- * Docker supports coarse-grained egress control only: `"allow-all"`
- * attaches the container to the default bridge network, `"deny-all"`
- * runs it with networking disabled. Domain-level policies and
- * credential brokering require `vercel()`.
- */
-export type DockerSandboxNetworkPolicy = "allow-all" | "deny-all";
+/** Coarse-grained egress policy for one live Docker sandbox. */
+export type DockerSandboxNetworkPolicy = Extract<SandboxNetworkPolicy, "allow-all" | "deny-all">;
-/**
- * Options accepted by `docker(opts)`.
- */
-export interface DockerSandboxCreateOptions {
- /**
- * Base container image for templates and sessions. Defaults to eve's
- * published `ghcr.io/vercel/eve` image, tagged with the installed eve
- * version without build metadata or `EVE_SANDBOX_IMAGE_TAG` when set. Framework setup creates
- * `/workspace` and verifies Bash. Install
- * any authored runtime tools in sandbox bootstrap or provide them through a
- * custom image.
- */
+/** Options shared by every sandbox created from one Docker environment. */
+export interface DockerSandboxEnvironmentOptions {
+ /** Base container image. Defaults to eve's published sandbox image. */
readonly image?: string;
- /**
- * Environment variables baked into every container the backend
- * creates (template builds and sessions).
- */
+ /** Environment variables baked into template builds and live containers. */
readonly env?: Readonly<Record<string, string>>;
- /**
- * Base image pull behavior. Defaults to `"if-not-present"`.
- */
+ /** Base image pull behavior. @default "if-not-present" */
readonly pullPolicy?: DockerSandboxPullPolicy;
- /**
- * Initial network policy for created containers. Defaults to
- * `"allow-all"`.
- */
+ /** Idempotent setup captured in the prepared image. */
+ readonly prepare?: (sandbox: SandboxSession) => Promise<void> | void;
+}
+
+/** Options applied when eve creates one live Docker sandbox. */
+export interface DockerSandboxRuntimeOptions extends SandboxNetworkOptions {
+ /** Initial network policy for this container. @default "allow-all" */
readonly networkPolicy?: DockerSandboxNetworkPolicy;
}
diff --git a/packages/eve/src/public/sandbox/docker.ts b/packages/eve/src/public/sandbox/docker.ts
index a41bc6a1c..47332f47d 100644
--- a/packages/eve/src/public/sandbox/docker.ts
+++ b/packages/eve/src/public/sandbox/docker.ts
@@ -1,6 +1,9 @@
-export { docker } from "#public/sandbox/backends/docker.js";
+export {
+ DockerSandbox,
+ type DockerSandboxEnvironmentOptions,
+ type DockerSandboxRuntimeOptions,
+} from "#sandbox/providers/docker.js";
export type {
- DockerSandboxCreateOptions,
DockerSandboxNetworkPolicy,
DockerSandboxPullPolicy,
} from "#public/sandbox/docker-sandbox.js";
diff --git a/packages/eve/src/public/sandbox/index.ts b/packages/eve/src/public/sandbox/index.ts
index 5b7e67de6..1dc64b86e 100644
--- a/packages/eve/src/public/sandbox/index.ts
+++ b/packages/eve/src/public/sandbox/index.ts
@@ -1,45 +1,29 @@
-/**
- * Sandbox authoring helpers for `agent/sandbox.ts` (or
- * `agent/sandbox/sandbox.ts` when paired with a `workspace/` folder).
- */
export {
+ defineParentSandbox,
defineSandbox,
- type SandboxAncestorReference,
- type SandboxBootstrapContext,
- type SandboxBootstrapUseFn,
+ type SandboxOpenArguments,
+ type SandboxEnvironment,
+ type SandboxSelector,
+ type SandboxSelectorContext,
type SandboxCommandResult,
- type SandboxDefinition,
- type SandboxParentDefinition,
- type SandboxParentDefinitionContext,
- type SandboxParentValue,
+ type FixedNetworkSandboxSession,
+ type MutableNetworkSandboxSession,
type SandboxProcess,
type SandboxReadBinaryFileOptions,
type SandboxReadFileOptions,
type SandboxReadTextFileOptions,
- type SandboxRevalidationKeyFn,
type SandboxRunOptions,
type SandboxSession,
type RuntimeSandboxSession,
+ type RuntimeSandboxSessionFor,
type SandboxSpawnOptions,
- type SandboxSessionContext,
- type SandboxSessionUseFn,
type SandboxWriteBinaryFileOptions,
type SandboxWriteFileOptions,
type SandboxWriteTextFileOptions,
} from "#public/definitions/sandbox.js";
+export { DefaultSandbox } from "#sandbox/providers/default.js";
+export type { DefaultSandboxEnvironmentOptions } from "#sandbox/providers/default.js";
export type {
- SandboxBackend,
- SandboxBackendCreateInput,
- SandboxBackendHandle,
- SandboxBackendPrewarmInput,
- SandboxBackendRuntimeContext,
- SandboxBackendSessionState,
- SandboxDeleteOptions,
- SandboxSeedFile,
-} from "#public/definitions/sandbox-backend.js";
-export type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";
-export { SandboxTemplateNotProvisionedError } from "#public/definitions/sandbox-backend.js";
-export {
- defaultSandbox as defaultBackend,
- type DefaultSandboxOptions as DefaultBackendOptions,
-} from "#public/sandbox/backends/default.js";
+ SandboxNetworkOptions,
+ SandboxNetworkPolicy,
+} from "#shared/sandbox-network-policy.js";
diff --git a/packages/eve/src/public/sandbox/just-bash-sandbox.ts b/packages/eve/src/public/sandbox/just-bash-sandbox.ts
index 09326d08b..c1c0eb45c 100644
--- a/packages/eve/src/public/sandbox/just-bash-sandbox.ts
+++ b/packages/eve/src/public/sandbox/just-bash-sandbox.ts
@@ -1,11 +1,14 @@
import type { CustomCommand, IFileSystem } from "just-bash";
+import type { SandboxSession } from "#shared/sandbox-session.js";
/**
* Context passed to a custom just-bash filesystem factory for each live handle.
*/
export interface JustBashFilesystemContext {
- /** Stable application root for this backend create call. */
- readonly appRoot: string;
+ /** Resolves an application-relative path without exposing project layout. */
+ resolveProjectPath(path: string): string;
+ /** Stable provider-private storage directory for this sandbox. */
+ readonly storagePath: string;
/** eve's durable, session-owned filesystem, including `/workspace`. */
readonly defaultFilesystem: IFileSystem;
/** The just-bash engine resolved by eve after its optional installation check. */
@@ -13,9 +16,9 @@ export interface JustBashFilesystemContext {
}
/**
- * Options accepted by `justbash(opts)`.
+ * Options accepted by just-bash environment constructors.
*
- * The just-bash backend runs the workspace under the pure-JS `just-bash`
+ * The just-bash provider runs the workspace under the pure-JS `just-bash`
* interpreter with a virtual filesystem — no daemon or VM required, but
* no real binaries either. The `just-bash` package is not bundled with
* eve; it is loaded lazily from the application install.
@@ -33,7 +36,7 @@ export interface JustBashSandboxCreateOptions {
* just-bash interpreter. Custom commands can participate in normal shell
* composition, including pipelines and redirections.
*
- * Custom commands are not available during template prewarming. They run in
+ * Custom commands are not available during environment preparation. They run in
* eve's host process, outside the virtual filesystem security boundary, and
* are responsible for validating their own inputs and cleaning up host
* resources.
@@ -47,7 +50,9 @@ export interface JustBashSandboxCreateOptions {
*
* This just-bash-specific escape hatch requires the application to install
* a compatible `just-bash` version. It is not invoked during template
- * prewarming.
+ * preparation.
*/
readonly filesystem?: (context: JustBashFilesystemContext) => IFileSystem | Promise<IFileSystem>;
+ /** Idempotent setup captured in the prepared virtual filesystem. */
+ readonly prepare?: (sandbox: SandboxSession) => Promise<void> | void;
}
diff --git a/packages/eve/src/public/sandbox/just-bash.ts b/packages/eve/src/public/sandbox/just-bash.ts
index bfe333a5e..68f10c4af 100644
--- a/packages/eve/src/public/sandbox/just-bash.ts
+++ b/packages/eve/src/public/sandbox/just-bash.ts
@@ -1,5 +1,2 @@
-export { justbash } from "#public/sandbox/backends/just-bash.js";
-export type {
- JustBashFilesystemContext,
- JustBashSandboxCreateOptions,
-} from "#public/sandbox/just-bash-sandbox.js";
+export { JustBashSandbox, type JustBashEnvironmentOptions } from "#sandbox/providers/just-bash.js";
+export type { JustBashFilesystemContext } from "#public/sandbox/just-bash-sandbox.js";
diff --git a/packages/eve/src/public/sandbox/microsandbox-sandbox.ts b/packages/eve/src/public/sandbox/microsandbox-sandbox.ts
index daae6dea3..014b6077b 100644
--- a/packages/eve/src/public/sandbox/microsandbox-sandbox.ts
+++ b/packages/eve/src/public/sandbox/microsandbox-sandbox.ts
@@ -1,9 +1,13 @@
-import type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";
+import type { SandboxSession } from "#shared/sandbox-session.js";
+import type {
+ SandboxNetworkOptions,
+ SandboxNetworkPolicy,
+} from "#shared/sandbox-network-policy.js";
/**
- * Options accepted by `microsandbox(opts)`.
+ * Options accepted by microsandbox environment constructors.
*
- * The microsandbox backend runs sandboxes in lightweight local VMs via
+ * The microsandbox provider runs sandboxes in lightweight local VMs via
* [microsandbox](https://www.npmjs.com/package/microsandbox). Options
* are eve-owned rather than a raw passthrough so the public surface can
* stay stable while the underlying runtime evolves. Supported hosts:
@@ -13,8 +17,8 @@ export interface MicrosandboxSandboxCreateOptions {
/**
* OCI image used as the base runtime. eve prepares this image with
* Bash, the framework workspace, and the sandbox user before authored
- * bootstrap code runs. Install authored runtime tools such as Node,
- * Python, or ripgrep in sandbox bootstrap or provide them through a
+ * environment preparation runs. Install authored runtime tools such as Node,
+ * Python, or ripgrep during preparation or provide them through a
* custom image.
*
* @default The `ghcr.io/vercel/eve` tag matching the installed eve version without build metadata, or `EVE_SANDBOX_IMAGE_TAG` when set.
@@ -28,6 +32,8 @@ export interface MicrosandboxSandboxCreateOptions {
readonly env?: Readonly<Record<string, string>>;
/** OCI image pull policy. @default "if-missing" */
readonly pullPolicy?: "always" | "if-missing" | "never";
+ /** Idempotent setup captured in the prepared VM snapshot. */
+ readonly prepare?: (sandbox: SandboxSession) => Promise<void> | void;
/**
* Installation behavior for the microsandbox npm package and its VM
* runtime. By default eve installs both automatically when missing —
@@ -38,20 +44,10 @@ export interface MicrosandboxSandboxCreateOptions {
readonly autoInstall?: boolean;
readonly skipVerify?: boolean;
};
- /** Initial network policy applied to sandboxes after framework setup. */
- readonly networkPolicy?: SandboxNetworkPolicy;
-}
-
-/**
- * Options accepted by the microsandbox backend's `bootstrap({ use })` hook.
- */
-export interface MicrosandboxBootstrapUseOptions {
- readonly networkPolicy?: SandboxNetworkPolicy;
}
-/**
- * Options accepted by the microsandbox backend's `onSession({ use })` hook.
- */
-export interface MicrosandboxSessionUseOptions {
+/** Options applied when eve creates one live microsandbox VM. */
+export interface MicrosandboxSandboxRuntimeOptions extends SandboxNetworkOptions {
+ /** Initial network policy for this VM. @default "allow-all" */
readonly networkPolicy?: SandboxNetworkPolicy;
}
diff --git a/packages/eve/src/public/sandbox/microsandbox.ts b/packages/eve/src/public/sandbox/microsandbox.ts
index a92efa86c..5c6aefa1e 100644
--- a/packages/eve/src/public/sandbox/microsandbox.ts
+++ b/packages/eve/src/public/sandbox/microsandbox.ts
@@ -1,6 +1,5 @@
-export { microsandbox } from "#public/sandbox/backends/microsandbox.js";
-export type {
- MicrosandboxBootstrapUseOptions,
- MicrosandboxSandboxCreateOptions,
- MicrosandboxSessionUseOptions,
-} from "#public/sandbox/microsandbox-sandbox.js";
+export {
+ MicrosandboxSandbox,
+ type MicrosandboxEnvironmentOptions,
+} from "#sandbox/providers/microsandbox.js";
+export type { MicrosandboxSandboxRuntimeOptions } from "#public/sandbox/microsandbox-sandbox.js";
diff --git a/packages/eve/src/public/sandbox/provider.ts b/packages/eve/src/public/sandbox/provider.ts
new file mode 100644
index 000000000..158846f7e
--- /dev/null
+++ b/packages/eve/src/public/sandbox/provider.ts
@@ -0,0 +1,17 @@
+export {
+ defineSandboxProvider,
+ type SandboxDeleteOptions,
+ type SandboxPreparedArtifact,
+ type SandboxProvider,
+ type SandboxProviderDefinition,
+ type SandboxProviderFiles,
+ type SandboxProviderHandle,
+ type SandboxProviderImplementation,
+ type SandboxProviderPrepareContext,
+ type SandboxProviderResourceFile,
+ type SandboxProviderResources,
+ type SandboxProviderResourceSource,
+ type SandboxProviderResourceTree,
+ type SandboxProviderSessionContext,
+ type SandboxProviderTargetFile,
+} from "#shared/sandbox-provider.js";
diff --git a/packages/eve/src/public/sandbox/vercel-sandbox.ts b/packages/eve/src/public/sandbox/vercel-sandbox.ts
index 0a8ee2398..d9a83246b 100644
--- a/packages/eve/src/public/sandbox/vercel-sandbox.ts
+++ b/packages/eve/src/public/sandbox/vercel-sandbox.ts
@@ -1,9 +1,8 @@
import type * as Vercel from "#compiled/@vercel/sandbox/index.js";
+import type { SandboxNetworkOptions } from "#shared/sandbox-network-policy.js";
type VercelCreateOptions = NonNullable<Parameters<typeof Vercel.Sandbox.create>[0]>;
-type VercelUpdateOptions = Parameters<Vercel.Sandbox["update"]>[0];
-
type VercelSandboxInternalCreateOptions = {
readonly [key: `__${string}`]: unknown;
};
@@ -14,14 +13,14 @@ type VercelSandboxAuthorCreateOptions<T> = T extends unknown
: never;
/**
- * Options accepted by `vercel(opts)`. Forwarded to Vercel
+ * Options accepted by Vercel sandbox environment constructors. Forwarded to Vercel
* Sandbox creation for every fresh sandbox the framework creates
- * (template at prewarm time, session at first-time session-create).
+ * (template during preparation, session at first creation).
* Skipped on resume (`Sandbox.get`) since no create happens there.
*
* `networkPolicy` is deferred until after framework-owned base setup
* for fresh templates and template-less sessions, so eve can install
- * required packages before authored bootstrap code runs. Template-backed
+ * required packages before authored environment preparation runs. Template-backed
* session creates receive it at creation time because the template
* already contains the prepared base runtime.
*
@@ -30,7 +29,7 @@ type VercelSandboxAuthorCreateOptions<T> = T extends unknown
* author-supplied values.
*
* `runtime` is excluded: eve defaults to its published
- * `vcr.vercel.com/vercel/eve/base` image tagged with the installed eve version without build metadata
+ * `vcr.vercel.com/vercel/eve/base` image tagged with the installed eve version
* or `EVE_SANDBOX_IMAGE_TAG` when `image` is not supplied. Both are mutually
* exclusive with a stock runtime.
*
@@ -38,9 +37,9 @@ type VercelSandboxAuthorCreateOptions<T> = T extends unknown
* snapshot `source` takes precedence because the Vercel SDK makes it mutually
* exclusive with `image`.
*
- * `source` is honored only on the template create at prewarm time, so
+ * `source` is honored only on the template creation during preparation, so
* an author-supplied snapshot, git revision, or tarball becomes the
- * base layer for the template. Framework setup, bootstrap, and seed
+ * base layer for the template. Framework setup, preparation, and seed
* files all run on top, and the resulting
* framework-owned snapshot is what every later session derives from,
* so `source` is stripped from the session-create path. eve does not
@@ -60,43 +59,14 @@ export type VercelSandboxMount = Vercel.SandboxMounts[string];
export type VercelSandboxMounts = Vercel.SandboxMounts;
/** Options resolved when eve creates a fresh live session sandbox. */
-export interface VercelSandboxSessionCreateOptions {
+export interface VercelSandboxMountOptions {
readonly mounts?: VercelSandboxMounts;
}
-/** Context available while resolving fresh live-session creation options. */
-export interface VercelSandboxSessionCreateContext {
- readonly session: { readonly id: string };
-}
-
-/** Options accepted by `vercel(opts)`. */
-export type VercelSandboxOptions = VercelSandboxCreateOptions & {
- /**
- * Resolves options that apply only to fresh live sessions. It is not called
- * while prewarming templates or resuming an existing sandbox.
- */
- readonly sessionCreateOptions?: (
- context: VercelSandboxSessionCreateContext,
- ) => Promise<VercelSandboxSessionCreateOptions> | VercelSandboxSessionCreateOptions;
-};
-
-/**
- * Options accepted by the Vercel backend's `bootstrap({ use })` hook.
- * Tracks the Vercel SDK's `Sandbox.update(...)` parameter because bootstrap
- * applies its options to the template via `sandbox.update(...)` after
- * `Sandbox.create()` and before the snapshot is captured. The Vercel
- * SDK persists `update`-d settings on the sandbox so they survive into
- * the snapshot, which becomes the seed for every later session.
- *
- * Today this is the same shape as
- * {@link VercelSandboxSessionUseOptions}; both are exposed as separate
- * named aliases so future divergence is non-breaking.
- */
-export type VercelSandboxBootstrapUseOptions = VercelUpdateOptions;
-
-/**
- * Options accepted by the Vercel backend's `onSession({ use })` hook.
- * Tracks the Vercel SDK's `Sandbox.update(...)` parameter; passed values are
- * applied to the live session via the SDK's `update`.
- */
-export type VercelSandboxSessionUseOptions = VercelUpdateOptions;
+/** Options accepted when creating one live Vercel sandbox from an environment. */
+export type VercelSandboxRuntimeOptions = Omit<
+ VercelSandboxCreateOptions,
+ "fetch" | "image" | "projectId" | "source" | "tags" | "teamId" | "token"
+> &
+ SandboxNetworkOptions &
+ VercelSandboxMountOptions;
diff --git a/packages/eve/src/public/sandbox/vercel.test.ts b/packages/eve/src/public/sandbox/vercel.test.ts
index 91b53bde0..02a378b5d 100644
--- a/packages/eve/src/public/sandbox/vercel.test.ts
+++ b/packages/eve/src/public/sandbox/vercel.test.ts
@@ -1,27 +1,10 @@
import { describe, expect, expectTypeOf, it } from "vitest";
-
-import {
- Drive,
- vercel,
- type VercelSandboxOptions,
- type VercelSandboxSessionCreateOptions,
-} from "#public/sandbox/vercel.js";
-
-describe("vercel", () => {
- it("exposes Drive and accepts session-scoped mounts", () => {
- const options = {
- sessionCreateOptions: ({ session }) => ({
- mounts: {
- "/workspace": { drive: `repo-${session.id}`, mode: "read-write" },
- },
- }),
- } satisfies VercelSandboxOptions;
-
- expect(vercel(options).name).toBe("vercel");
+import { Drive, VercelSandbox } from "#public/sandbox/vercel.js";
+describe("VercelSandbox", () => {
+ it("creates environments", () => {
+ const environment = VercelSandbox.environment({ resources: { vcpus: 4 } });
+ expect(environment.provider).toBe("vercel");
+ expectTypeOf(environment.open).toBeFunction();
expectTypeOf(Drive.getOrCreate).toBeFunction();
- expectTypeOf(
- options.sessionCreateOptions({ session: { id: "acme" } }),
- ).toMatchTypeOf<VercelSandboxSessionCreateOptions>();
- expectTypeOf<VercelSandboxOptions>().not.toHaveProperty("mounts");
});
});
diff --git a/packages/eve/src/public/sandbox/vercel.ts b/packages/eve/src/public/sandbox/vercel.ts
index 47e36252d..ab9a4afb1 100644
--- a/packages/eve/src/public/sandbox/vercel.ts
+++ b/packages/eve/src/public/sandbox/vercel.ts
@@ -1,13 +1,11 @@
-export { vercel } from "#public/sandbox/backends/vercel.js";
+export {
+ VercelSandbox,
+ type VercelSandboxEnvironmentOptions,
+ type VercelSandboxRuntimeOptions,
+} from "#sandbox/providers/vercel.js";
export { Drive } from "#compiled/@vercel/sandbox/index.js";
export type {
- VercelSandboxBootstrapUseOptions,
- VercelSandboxCreateOptions,
VercelSandboxMount,
VercelSandboxMountMode,
VercelSandboxMounts,
- VercelSandboxOptions,
- VercelSandboxSessionCreateContext,
- VercelSandboxSessionCreateOptions,
- VercelSandboxSessionUseOptions,
} from "#public/sandbox/vercel-sandbox.js";
diff --git a/packages/eve/src/runtime/compiled-artifacts-source.ts b/packages/eve/src/runtime/compiled-artifacts-source.ts
index 9baf711a3..afbff38a4 100644
--- a/packages/eve/src/runtime/compiled-artifacts-source.ts
+++ b/packages/eve/src/runtime/compiled-artifacts-source.ts
@@ -11,6 +11,8 @@ export type RuntimeCompiledArtifactsSource =
*/
export interface RuntimeBundledCompiledArtifactsSource {
readonly kind: "bundled";
+ /** Stable app partition embedded by a production build for local providers. */
+ readonly sandboxScope?: string;
}
/**
@@ -27,6 +29,8 @@ export interface RuntimeDiskCompiledArtifactsSource {
* emitted by the build.
*/
readonly moduleMapLoaderPath?: string;
+ /** Stable app partition shared by production build preparation and runtime. */
+ readonly sandboxScope?: string;
/**
* Stable application root used for local sandbox template/session caches.
* In development, `appRoot` can point at an immutable runtime snapshot
@@ -46,10 +50,10 @@ export interface RuntimeDiskCompiledArtifactsSource {
/**
* Creates the bundled compiled-artifact source.
*/
-export function createBundledRuntimeCompiledArtifactsSource(): RuntimeBundledCompiledArtifactsSource {
- return {
- kind: "bundled",
- };
+export function createBundledRuntimeCompiledArtifactsSource(
+ sandboxScope?: string,
+): RuntimeBundledCompiledArtifactsSource {
+ return sandboxScope === undefined ? { kind: "bundled" } : { kind: "bundled", sandboxScope };
}
/**
@@ -61,11 +65,13 @@ export function createDiskRuntimeCompiledArtifactsSource(
readonly durableReference?: "development-generation";
readonly moduleMapLoaderPath?: string;
readonly sandboxAppRoot?: string;
+ readonly sandboxScope?: string;
} = {},
): RuntimeDiskCompiledArtifactsSource {
if (
options.moduleMapLoaderPath !== undefined ||
options.sandboxAppRoot !== undefined ||
+ options.sandboxScope !== undefined ||
options.durableReference !== undefined
) {
return {
@@ -74,6 +80,7 @@ export function createDiskRuntimeCompiledArtifactsSource(
kind: "disk",
moduleMapLoaderPath: options.moduleMapLoaderPath,
sandboxAppRoot: options.sandboxAppRoot,
+ sandboxScope: options.sandboxScope,
};
}
diff --git a/packages/eve/src/runtime/loaders/artifact-paths.ts b/packages/eve/src/runtime/loaders/artifact-paths.ts
index 93a6f92b3..09dd4b2c4 100644
--- a/packages/eve/src/runtime/loaders/artifact-paths.ts
+++ b/packages/eve/src/runtime/loaders/artifact-paths.ts
@@ -10,6 +10,7 @@ export interface RuntimeCompilerArtifactPaths {
readonly discoveryManifestPath: string;
readonly discoveryDirectoryPath: string;
readonly moduleMapPath: string;
+ readonly sandboxPreparedArtifactsPath: string;
}
/**
@@ -30,6 +31,7 @@ export function resolveRuntimeCompilerArtifactPaths(appRoot: string): RuntimeCom
discoveryDirectoryPath,
discoveryManifestPath: `${discoveryDirectoryPath}/agent-discovery-manifest.json`,
moduleMapPath: `${compileDirectoryPath}/module-map.mjs`,
+ sandboxPreparedArtifactsPath: `${compileDirectoryPath}/sandbox-prepared-artifacts.json`,
};
}
diff --git a/packages/eve/src/runtime/loaders/bundled-artifacts.ts b/packages/eve/src/runtime/loaders/bundled-artifacts.ts
index 1d45e0f70..e325e9f16 100644
--- a/packages/eve/src/runtime/loaders/bundled-artifacts.ts
+++ b/packages/eve/src/runtime/loaders/bundled-artifacts.ts
@@ -1,6 +1,7 @@
import type { CompileMetadata } from "#compiler/artifacts.js";
import type { CompiledAgentManifest } from "#compiler/manifest.js";
import type { CompiledModuleMap } from "#compiler/module-map.js";
+import type { SandboxPreparedArtifactsManifest } from "#shared/sandbox-prepared-artifacts.js";
import {
createRuntimeSession,
getActiveRuntimeSession,
@@ -16,6 +17,7 @@ export interface BundledCompiledArtifacts {
manifest: CompiledAgentManifest;
metadata?: CompileMetadata;
moduleMap: CompiledModuleMap;
+ sandboxPreparedArtifacts?: SandboxPreparedArtifactsManifest;
}
/**
@@ -37,6 +39,7 @@ export function installBundledCompiledArtifacts(input: BundledCompiledArtifacts)
manifest: input.manifest,
metadata: input.metadata,
moduleMap: input.moduleMap,
+ sandboxPreparedArtifacts: input.sandboxPreparedArtifacts,
});
}
@@ -60,6 +63,16 @@ export async function withBundledCompiledArtifacts<T>(
* Reads the bundled compiled-artifact snapshot for the active runtime
* session, or `null` if none has been installed.
*/
+export function updateBundledSandboxPreparedArtifacts(
+ sandboxPreparedArtifacts: SandboxPreparedArtifactsManifest,
+): boolean {
+ const session = getActiveRuntimeSession();
+ const installed = session.compiledArtifacts;
+ if (installed === null) return false;
+ setRuntimeSessionCompiledArtifacts(session, { ...installed, sandboxPreparedArtifacts });
+ return true;
+}
+
export function readBundledCompiledArtifacts(): BundledCompiledArtifacts | null {
return getActiveRuntimeSession().compiledArtifacts;
}
diff --git a/packages/eve/src/runtime/resolve-agent-graph.ts b/packages/eve/src/runtime/resolve-agent-graph.ts
index 2ad15864d..77cf37fd9 100644
--- a/packages/eve/src/runtime/resolve-agent-graph.ts
+++ b/packages/eve/src/runtime/resolve-agent-graph.ts
@@ -401,7 +401,7 @@ function attachInheritedSandboxWorkspaceResources(input: {
);
for (const [nodeId, node] of input.nodesByNodeId) {
- if (node.sandboxRegistry.sandbox.definition.inheritsParent !== true) continue;
+ if (node.sandboxRegistry.sandbox.definition.kind !== "parent") continue;
if (node.agent.dynamicSkillResolvers.length > 0) {
throw new ResolveRuntimeAgentGraphError(
`Sandbox "${node.sandboxRegistry.sandbox.definition.logicalPath}" selects parent.sandbox but agent node "${nodeId}" defines dynamic skills. Remove the child dynamic skills or give the child its own sandbox.`,
@@ -447,7 +447,7 @@ function resolveSandboxOwnerNode(input: {
nodeId: input.nodeId,
});
}
- if (node.sandboxRegistry.sandbox.definition.inheritsParent !== true) return node;
+ if (node.sandboxRegistry.sandbox.definition.kind !== "parent") return node;
const parentNodeId = input.parentNodeIdByChildNodeId.get(input.nodeId);
if (parentNodeId === undefined) {
diff --git a/packages/eve/src/runtime/resolve-sandbox.test.ts b/packages/eve/src/runtime/resolve-sandbox.test.ts
new file mode 100644
index 000000000..b655b243a
--- /dev/null
+++ b/packages/eve/src/runtime/resolve-sandbox.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from "vitest";
+
+import type { CompiledSandboxDefinition } from "#compiler/manifest.js";
+import { resolveSandboxDefinition } from "#runtime/resolve-sandbox.js";
+
+const inheritedSandbox: CompiledSandboxDefinition = {
+ inheritsParent: true,
+ logicalPath: "sandbox.ts",
+ revisionHash: "parent-source-hash",
+ sourceId: "parent-sandbox-source",
+ sourceKind: "module",
+};
+
+describe("resolveSandboxDefinition", () => {
+ it("resolves parent inheritance without loading the parent module from the child scope", async () => {
+ await expect(
+ resolveSandboxDefinition(inheritedSandbox, { nodes: { child: { modules: {} } } }, "child"),
+ ).resolves.toMatchObject({
+ kind: "parent",
+ logicalPath: "sandbox.ts",
+ sourceId: "parent-sandbox-source",
+ });
+ });
+});
diff --git a/packages/eve/src/runtime/resolve-sandbox.ts b/packages/eve/src/runtime/resolve-sandbox.ts
index 9ab72e1d1..6a3f0031a 100644
--- a/packages/eve/src/runtime/resolve-sandbox.ts
+++ b/packages/eve/src/runtime/resolve-sandbox.ts
@@ -1,107 +1,49 @@
-import type { CompiledSandboxDefinition } from "#compiler/manifest.js";
+import { ROOT_COMPILED_AGENT_NODE_ID, type CompiledSandboxDefinition } from "#compiler/manifest.js";
import type { CompiledModuleMap } from "#compiler/module-map.js";
-import { lazyBackend } from "#execution/sandbox/lazy-backend.js";
-import { expectObjectRecord } from "#internal/authored-module.js";
-import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
-import { defaultSandbox } from "#public/sandbox/backends/default.js";
-import { toErrorMessage } from "#shared/errors.js";
-import { loadResolvedModuleExport, ResolveAgentError } from "#runtime/resolve-helpers.js";
+import { expectObjectRecord, getAuthoredModuleExport } from "#internal/authored-module.js";
+import { defineParentSandbox } from "#public/definitions/sandbox.js";
+import { ResolveAgentError } from "#runtime/resolve-helpers.js";
import type { ResolvedSandboxDefinition } from "#runtime/types.js";
+import { getBoundSandboxEnvironment, isSandboxEnvironment } from "#shared/sandbox-environment.js";
-/**
- * Resolves one compiled sandbox entry into a runtime-owned definition
- * with live `backend`, `bootstrap`, and `onSession` lifecycle handlers
- * (when present) attached from the authored module.
- *
- * If the authored module omits `backend`, the resolver substitutes
- * {@link defaultSandbox} so the rest of the runtime can rely on a
- * non-null backend value.
- */
export async function resolveSandboxDefinition(
definition: CompiledSandboxDefinition,
moduleMap: CompiledModuleMap,
nodeId: string | undefined,
): Promise<ResolvedSandboxDefinition> {
- try {
- const resolvedExportValue = definition.inheritsParent
- ? undefined
- : await loadResolvedModuleExport({
- definition,
- kindLabel: "sandbox",
- moduleMap,
- nodeId,
- });
- const sandboxDefinition: {
- readonly backend?: unknown;
- readonly bootstrap?: (input: unknown) => Promise<void> | void;
- readonly onSession?: (input: unknown) => Promise<void> | void;
- } = definition.inheritsParent
- ? {}
- : expectObjectRecord(
- resolvedExportValue,
- `Expected the sandbox export "${definition.exportName ?? "default"}" from "${definition.logicalPath}" to return an object.`,
- );
-
- const backend = resolveBackend(sandboxDefinition.backend, definition.logicalPath);
-
+ if (definition.inheritsParent === true) {
return {
- backend,
- bootstrap: sandboxDefinition.bootstrap as ResolvedSandboxDefinition["bootstrap"],
- description: definition.description,
- inheritsParent: definition.inheritsParent,
exportName: definition.exportName,
+ kind: "parent",
logicalPath: definition.logicalPath,
- onSession: sandboxDefinition.onSession as ResolvedSandboxDefinition["onSession"],
- revalidationKey: definition.revalidationKey,
- sourceHash: definition.sourceHash,
+ revisionHash: definition.revisionHash,
+ selector: defineParentSandbox(),
sourceId: definition.sourceId,
sourceKind: "module",
};
- } catch (error) {
- if (error instanceof ResolveAgentError) {
- throw error;
- }
- throw new ResolveAgentError(
- `Failed to attach the sandbox lifecycle handlers from "${definition.logicalPath}": ${toErrorMessage(error)}`,
- {
- logicalPath: definition.logicalPath,
- sourceId: definition.sourceId,
- },
- );
- }
-}
-
-function resolveBackend(value: unknown, logicalPath: string): SandboxBackend {
- if (value === undefined) {
- return defaultSandbox();
- }
-
- if (typeof value === "function") {
- return lazyBackend(value as () => SandboxBackend);
- }
-
- if (typeof value !== "object" || value === null) {
- throw new ResolveAgentError(
- `Sandbox "${logicalPath}" exposed a non-object "backend" field. Use docker(), vercel(), another factory that returns a SandboxBackend value, or a zero-arg callback returning one.`,
- { logicalPath },
- );
- }
-
- const record = value as Record<string, unknown>;
-
- if (typeof record.name !== "string" || record.name.length === 0) {
- throw new ResolveAgentError(
- `Sandbox "${logicalPath}" backend is missing a non-empty string "name" identifier.`,
- { logicalPath },
- );
- }
-
- if (typeof record.create !== "function") {
- throw new ResolveAgentError(
- `Sandbox "${logicalPath}" backend is missing a "create" function.`,
- { logicalPath },
- );
}
- return record as unknown as SandboxBackend;
+ const namespace =
+ moduleMap.nodes[nodeId ?? ROOT_COMPILED_AGENT_NODE_ID]?.modules[definition.sourceId];
+ const record = expectObjectRecord(
+ namespace,
+ `Missing sandbox module "${definition.logicalPath}".`,
+ );
+ const selector = getAuthoredModuleExport(record, definition);
+ if (typeof selector !== "function")
+ throw new ResolveAgentError(`Sandbox "${definition.logicalPath}" does not export a selector.`);
+ const environment = definition.environmentExportName
+ ? record[definition.environmentExportName]
+ : getBoundSandboxEnvironment(selector);
+ const base = {
+ exportName: definition.exportName,
+ logicalPath: definition.logicalPath,
+ revisionHash: definition.revisionHash,
+ selector: selector as ResolvedSandboxDefinition["selector"],
+ sourceId: definition.sourceId,
+ sourceKind: "module" as const,
+ };
+ if (!isSandboxEnvironment(environment))
+ throw new ResolveAgentError(`Sandbox "${definition.logicalPath}" has no environment.`);
+ return { ...base, environment, kind: "independent" };
}
diff --git a/packages/eve/src/runtime/sandbox/keys.test.ts b/packages/eve/src/runtime/sandbox/keys.test.ts
deleted file mode 100644
index b030a8bbd..000000000
--- a/packages/eve/src/runtime/sandbox/keys.test.ts
+++ /dev/null
@@ -1,281 +0,0 @@
-import { createHash } from "node:crypto";
-import { afterEach, describe, expect, it, vi } from "vitest";
-
-import {
- COMPILE_METADATA_KIND,
- COMPILE_METADATA_VERSION,
- type CompileMetadata,
-} from "#compiler/artifacts.js";
-import { compileFromMemory } from "#compiler/compile-from-memory.js";
-import { resolveInstalledPackageInfo } from "#internal/application/package.js";
-import { createFakeVercelOidcToken } from "#internal/testing/vercel-oidc-token.js";
-import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
-import { withBundledCompiledArtifacts } from "#runtime/loaders/bundled-artifacts.js";
-import {
- createRuntimeSandboxKeys,
- createRuntimeSandboxTemplateKey,
-} from "#runtime/sandbox/keys.js";
-import type { RuntimeSandboxTemplatePlan } from "#runtime/sandbox/template-plan.js";
-
-const RUNTIME_SANDBOX_CONTRACT_VERSION = 7;
-
-const CONTENT_HASH = "a".repeat(64);
-
-function createMetadataFixture(generatorVersion: string): CompileMetadata {
- return {
- compile: {
- manifest: { path: ".eve/compile/agent-manifest.json", sha256: "a".repeat(64) },
- moduleMap: { path: ".eve/compile/module-map.mjs", sha256: "b".repeat(64) },
- },
- discovery: {
- diagnostics: { path: ".eve/discovery/diagnostics.json", sha256: "c".repeat(64) },
- manifest: { path: ".eve/discovery/agent-discovery-manifest.json", sha256: "d".repeat(64) },
- sourceGraphHash: "e".repeat(64),
- summary: { errors: 0, warnings: 0 },
- },
- generator: { name: "eve", version: generatorVersion },
- kind: COMPILE_METADATA_KIND,
- status: "ready",
- version: COMPILE_METADATA_VERSION,
- };
-}
-
-function sha256(value: string): string {
- return createHash("sha256").update(value).digest("hex");
-}
-
-function expectedTemplateKey(input: { scopeSource: string; version: string }): string {
- const scope = sha256(input.scopeSource).slice(0, 16);
- const versionHash = sha256(`workspace-content:${CONTENT_HASH}:__root__:eve:default-sandbox`);
- const templateHash = sha256(
- `${input.version}:${RUNTIME_SANDBOX_CONTRACT_VERSION}:${versionHash}`,
- ).slice(0, 20);
- return `eve-sbx-tpl-local-${scope}-${templateHash}`;
-}
-
-async function deriveTemplateKey(): Promise<string | null> {
- return await createRuntimeSandboxTemplateKey({
- backendName: "local",
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- nodeId: "__root__",
- sourceId: "eve:default-sandbox",
- templatePlan: { contentHash: CONTENT_HASH, kind: "workspace-content" },
- });
-}
-
-async function withBundledMetadata<T>(
- metadata: CompileMetadata | undefined,
- fn: () => Promise<T>,
-): Promise<T> {
- const { manifest, moduleMap } = await compileFromMemory({
- agentRoot: "/virtual/app/agent",
- appRoot: "/virtual/app",
- model: "openai/gpt-5.4",
- name: "keys-test-agent",
- });
-
- return await withBundledCompiledArtifacts({ manifest, metadata, moduleMap }, fn);
-}
-
-async function deriveSessionKey(input?: {
- readonly backendName?: string;
- readonly contentHash?: string;
-}): Promise<string> {
- const keys = await createRuntimeSandboxKeys({
- backendName: input?.backendName ?? "local",
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- nodeId: "__root__",
- sessionId: "session_1",
- sourceId: "eve:default-sandbox",
- templatePlan: {
- contentHash: input?.contentHash ?? CONTENT_HASH,
- kind: "workspace-content",
- },
- });
- return keys.sessionKey;
-}
-
-async function deriveBootstrapKeys(
- templatePlan: Extract<RuntimeSandboxTemplatePlan, { kind: "bootstrap" }> = {
- kind: "bootstrap",
- sourceHash: "sandbox-source-v1",
- },
-) {
- return await createRuntimeSandboxKeys({
- backendName: "vercel",
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- nodeId: "__root__",
- sessionId: "session_1",
- sourceId: "sandbox.ts",
- templatePlan,
- });
-}
-
-/**
- * Derives one vercel-backed session key under exactly the given env.
- * Unlisted project and deployment variables are stubbed empty so ambient
- * CI values cannot leak into the derivation.
- */
-async function deriveVercelSessionKey(env: Record<string, string>): Promise<string> {
- const stubbed = {
- VERCEL_DEPLOYMENT_ID: "",
- VERCEL_OIDC_TOKEN: "",
- VERCEL_PROJECT_ID: "",
- ...env,
- };
- for (const [key, value] of Object.entries(stubbed)) {
- vi.stubEnv(key, value);
- }
-
- return await withBundledMetadata(createMetadataFixture("1.0.0"), () =>
- deriveSessionKey({ backendName: "vercel" }),
- );
-}
-
-describe("createRuntimeSandboxKeys", () => {
- afterEach(() => {
- vi.unstubAllEnvs();
- });
-
- it("pins the vercel session key across deployments when only the OIDC token names the project", async () => {
- const token = createFakeVercelOidcToken({ project_id: "prj_123" });
-
- const first = await deriveVercelSessionKey({
- VERCEL_DEPLOYMENT_ID: "dpl_first",
- VERCEL_OIDC_TOKEN: token,
- });
- const second = await deriveVercelSessionKey({
- VERCEL_DEPLOYMENT_ID: "dpl_second",
- VERCEL_OIDC_TOKEN: token,
- });
-
- expect(first).toBe(second);
- });
-
- it("derives the same session key from the project id env var and the OIDC token claim", async () => {
- const fromEnv = await deriveVercelSessionKey({ VERCEL_PROJECT_ID: "prj_123" });
- const fromToken = await deriveVercelSessionKey({
- VERCEL_OIDC_TOKEN: createFakeVercelOidcToken({ project_id: "prj_123" }),
- });
-
- expect(fromEnv).toBe(fromToken);
- });
-
- it("never scopes the session key by deployment id, even without a resolvable project id", async () => {
- const first = await deriveVercelSessionKey({ VERCEL_DEPLOYMENT_ID: "dpl_first" });
- const second = await deriveVercelSessionKey({ VERCEL_DEPLOYMENT_ID: "dpl_second" });
-
- expect(first).toBe(second);
- });
-
- it("keeps the session key stable across unrelated source and eve version changes", async () => {
- const changedMetadata = createMetadataFixture("2.0.0");
-
- const first = await withBundledMetadata(createMetadataFixture("1.0.0"), () =>
- deriveSessionKey(),
- );
- const second = await withBundledMetadata(
- {
- ...changedMetadata,
- discovery: { ...changedMetadata.discovery, sourceGraphHash: "f".repeat(64) },
- },
- () => deriveSessionKey(),
- );
-
- expect(first).toBe(second);
- });
-
- it("rotates the session key when the sandbox content changes", async () => {
- const first = await withBundledMetadata(createMetadataFixture("1.0.0"), () =>
- deriveSessionKey(),
- );
- const second = await withBundledMetadata(createMetadataFixture("1.0.0"), () =>
- deriveSessionKey({ contentHash: "b".repeat(64) }),
- );
-
- expect(first).not.toBe(second);
- });
-
- it("keeps unseeded bootstrap template and session keys stable across unrelated source changes", async () => {
- vi.stubEnv("VERCEL_PROJECT_ID", "prj_123");
- const metadata = createMetadataFixture("1.0.0");
- const first = await withBundledMetadata(metadata, () => deriveBootstrapKeys());
- const second = await withBundledMetadata(
- {
- ...metadata,
- discovery: { ...metadata.discovery, sourceGraphHash: "f".repeat(64) },
- },
- () => deriveBootstrapKeys(),
- );
-
- expect(first.templateKey).not.toBeNull();
- expect(second).toEqual(first);
- });
-
- it("does not use missing compile metadata as unseeded bootstrap content", async () => {
- vi.stubEnv("VERCEL_PROJECT_ID", "prj_123");
- const metadata = createMetadataFixture(resolveInstalledPackageInfo().version);
- const withMetadata = await withBundledMetadata(metadata, () => deriveBootstrapKeys());
- const withoutMetadata = await withBundledMetadata(undefined, () => deriveBootstrapKeys());
-
- expect(withoutMetadata).toEqual(withMetadata);
- });
-
- it.each([
- { sourceHash: "sandbox-source-v2" },
- { revalidationKey: "bootstrap-v2" },
- { contentHash: CONTENT_HASH },
- ])("rotates both bootstrap keys when sandbox inputs change: %j", async (change) => {
- vi.stubEnv("VERCEL_PROJECT_ID", "prj_123");
- await withBundledMetadata(createMetadataFixture("1.0.0"), async () => {
- const first = await deriveBootstrapKeys();
- const second = await deriveBootstrapKeys({
- kind: "bootstrap",
- sourceHash: "sandbox-source-v1",
- ...change,
- });
-
- expect(second.templateKey).not.toBe(first.templateKey);
- expect(second.sessionKey).not.toBe(first.sessionKey);
- });
- });
-});
-
-describe("createRuntimeSandboxTemplateKey", () => {
- it("derives the version segment from compile metadata so build and runtime agree", async () => {
- const templateKey = await withBundledMetadata(
- createMetadataFixture("9.9.9-test"),
- deriveTemplateKey,
- );
-
- expect(templateKey).toBe(
- expectedTemplateKey({ scopeSource: "bundled", version: "9.9.9-test" }),
- );
- // The installed package version must not leak into the key: a deployed
- // bundle cannot resolve it and would otherwise diverge from the prewarm.
- expect(templateKey).not.toBe(
- expectedTemplateKey({
- scopeSource: "bundled",
- version: resolveInstalledPackageInfo().version,
- }),
- );
- });
-
- it("changes the template key when the compiled generator version changes", async () => {
- const first = await withBundledMetadata(createMetadataFixture("1.0.0"), deriveTemplateKey);
- const second = await withBundledMetadata(createMetadataFixture("2.0.0"), deriveTemplateKey);
-
- expect(first).not.toBe(second);
- });
-
- it("falls back to the installed package version without compile metadata", async () => {
- const templateKey = await withBundledMetadata(undefined, deriveTemplateKey);
-
- expect(templateKey).toBe(
- expectedTemplateKey({
- scopeSource: "bundled",
- version: resolveInstalledPackageInfo().version,
- }),
- );
- });
-});
diff --git a/packages/eve/src/runtime/sandbox/keys.ts b/packages/eve/src/runtime/sandbox/keys.ts
deleted file mode 100644
index 1333cee13..000000000
--- a/packages/eve/src/runtime/sandbox/keys.ts
+++ /dev/null
@@ -1,230 +0,0 @@
-import { createHash } from "node:crypto";
-import { realpath } from "node:fs/promises";
-import type { CompileMetadata } from "#compiler/artifacts.js";
-import { resolveInstalledPackageInfo } from "#internal/application/package.js";
-import {
- getRuntimeCompiledArtifactsSandboxAppRoot,
- getRuntimeCompiledArtifactsCacheKey,
- type RuntimeCompiledArtifactsSource,
-} from "#runtime/compiled-artifacts-source.js";
-import { loadCompileMetadata } from "#runtime/loaders/compile-metadata.js";
-import { resolveVercelProjectIdFromEnvironment } from "#shared/vercel-project.js";
-import type { RuntimeSandboxTemplatePlan } from "#runtime/sandbox/template-plan.js";
-
-/*
- * Template keys include this version for sandbox runtime contract changes
- * that are not captured by source or resource hashes. Version 7 writes static
- * skill seed files to the sandbox user's $HOME/.agents/skills directory.
- */
-const RUNTIME_SANDBOX_CONTRACT_VERSION = 7;
-
-/**
- * Input for deriving the stable runtime keys used for one sandbox definition.
- */
-interface CreateRuntimeSandboxKeysInput {
- readonly backendName: string;
- readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
- readonly nodeId: string;
- readonly sessionId: string;
- readonly sourceId: string;
- readonly templatePlan: RuntimeSandboxTemplatePlan;
-}
-
-/**
- * Creates the stable runtime template and session keys for one sandbox
- * definition under the current artifact source and backend.
- *
- * Both keys derive from one {@link RuntimeSandboxKeyParts} value, so the
- * coupling holds by construction: the session key rotates exactly when
- * the template content rotates.
- */
-export async function createRuntimeSandboxKeys(input: CreateRuntimeSandboxKeysInput): Promise<{
- readonly sessionKey: string;
- readonly templateKey: string | null;
-}> {
- const parts = await deriveRuntimeSandboxKeyParts(input);
- return {
- sessionKey: buildRuntimeSandboxSessionKey(input, parts),
- templateKey: buildRuntimeSandboxTemplateKey(input, parts),
- };
-}
-
-/**
- * Creates the stable reusable template key for one sandbox definition,
- * or `null` when the sandbox should start from a fresh backend runtime.
- *
- * The template key factors in the graph `nodeId` so that two
- * runtime agents (root and subagents) do not collide on the same
- * template when they each own a sandbox authored at the same logical
- * path.
- */
-export async function createRuntimeSandboxTemplateKey(input: {
- readonly backendName: string;
- readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
- readonly nodeId: string;
- readonly sourceId: string;
- readonly templatePlan: RuntimeSandboxTemplatePlan;
-}): Promise<string | null> {
- return buildRuntimeSandboxTemplateKey(input, await deriveRuntimeSandboxKeyParts(input));
-}
-
-/**
- * The facts both keys derive from, computed once per derivation:
- * compile metadata, the partition scope, and the sandbox definition's
- * version hash (`null` when the sandbox needs no template).
- */
-interface RuntimeSandboxKeyParts {
- readonly metadata: CompileMetadata | null;
- readonly scope: string;
- readonly versionHash: string | null;
-}
-
-async function deriveRuntimeSandboxKeyParts(input: {
- readonly backendName: string;
- readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
- readonly nodeId: string;
- readonly sourceId: string;
- readonly templatePlan: RuntimeSandboxTemplatePlan;
-}): Promise<RuntimeSandboxKeyParts> {
- const metadata = await loadCompileMetadataForKeys(input.compiledArtifactsSource);
- const scope = await resolveRuntimeSandboxScope(input);
- const versionHash =
- input.templatePlan.kind === "none"
- ? null
- : resolveRuntimeSandboxVersionHash({
- nodeId: input.nodeId,
- sourceId: input.sourceId,
- templatePlan: input.templatePlan,
- });
- return { metadata, scope, versionHash };
-}
-
-function buildRuntimeSandboxTemplateKey(
- input: { readonly backendName: string },
- parts: RuntimeSandboxKeyParts,
-): string | null {
- if (parts.versionHash === null) {
- return null;
- }
-
- const templateHash = createStableHash(
- `${resolvePackageVersionForTemplateKey(parts.metadata)}:${RUNTIME_SANDBOX_CONTRACT_VERSION}:${parts.versionHash}`,
- ).slice(0, 20);
-
- return sanitizeRuntimeSandboxKey(
- `eve-sbx-tpl-${input.backendName}-${parts.scope}-${templateHash}`,
- );
-}
-
-/**
- * Builds the session sandbox key for one sandbox definition.
- *
- * Session keys are pinned per durable session: the scope is stable across
- * deployments so a session reattaches to the same sandbox after a redeploy
- * and keeps its `/workspace` state. The key also folds in the sandbox
- * definition's version hash, so changing the sandbox itself (bootstrap
- * source, `revalidationKey`, or workspace seed content) rotates the
- * session sandbox onto the new template — unrelated source changes do not.
- * The eve package version deliberately does not participate: upgrading
- * eve must not discard session sandbox state.
- */
-function buildRuntimeSandboxSessionKey(
- input: { readonly backendName: string; readonly nodeId: string; readonly sessionId: string },
- parts: RuntimeSandboxKeyParts,
-): string {
- const version = createStableHash(
- `${RUNTIME_SANDBOX_CONTRACT_VERSION}:${parts.versionHash ?? "none"}`,
- ).slice(0, 12);
- const nodeScope = sanitizeRuntimeSandboxKey(input.nodeId);
-
- return sanitizeRuntimeSandboxKey(
- `eve-sbx-ses-${input.backendName}-${parts.scope}-${version}-${input.sessionId}-${nodeScope}`,
- );
-}
-
-/**
- * Resolves the eve package version that participates in template keys.
- *
- * Build-time prewarm and deployed runtime must derive the same key, but a
- * bundled runtime cannot resolve the installed package.json and may fall back
- * to a version string the prewarm CLI never saw. The compile metadata's
- * generator version ships inside the artifacts both phases read, so both
- * derive the same key from it.
- */
-function resolvePackageVersionForTemplateKey(metadata: CompileMetadata | null): string {
- return metadata?.generator.version ?? resolveInstalledPackageInfo().version;
-}
-
-async function loadCompileMetadataForKeys(
- compiledArtifactsSource: RuntimeCompiledArtifactsSource,
-): Promise<CompileMetadata | null> {
- try {
- return await loadCompileMetadata({ compiledArtifactsSource });
- } catch {
- // Key derivation must work from whatever artifacts exist; unreadable
- // metadata degrades to the same fallbacks as absent metadata.
- return null;
- }
-}
-
-/**
- * Resolves the partition scope shared by template and session keys.
- *
- * On Vercel the scope is the project id (env var or OIDC token claim),
- * never a deployment-scoped identifier: a key that varies per deployment
- * would discard prewarmed templates and, worse, silently discard session
- * sandbox state on every redeploy. The project id is also the only
- * identifier Vercel exposes at both build-time prewarm and deployed
- * runtime; a build-only identifier (e.g. team id) would leave the
- * prewarmed template "not provisioned" at runtime.
- *
- * Everywhere else the scope falls back to realpath(appRoot), then the
- * compiled-artifacts cache key.
- */
-async function resolveRuntimeSandboxScope(input: {
- readonly backendName: string;
- readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
-}): Promise<string> {
- if (input.backendName === "vercel") {
- const projectId = resolveVercelProjectIdFromEnvironment();
- if (projectId !== undefined) {
- return createStableHash(`vercel-project:${projectId}`).slice(0, 16);
- }
- }
-
- const appRoot = getRuntimeCompiledArtifactsSandboxAppRoot(input.compiledArtifactsSource);
- if (appRoot !== undefined) {
- return createStableHash(await realpath(appRoot)).slice(0, 16);
- }
-
- return createStableHash(getRuntimeCompiledArtifactsCacheKey(input.compiledArtifactsSource)).slice(
- 0,
- 16,
- );
-}
-
-function resolveRuntimeSandboxVersionHash(input: {
- readonly nodeId: string;
- readonly sourceId: string;
- readonly templatePlan: Exclude<RuntimeSandboxTemplatePlan, { readonly kind: "none" }>;
-}): string {
- // No seed files means empty content, independent of unrelated application source.
- const contentHash = input.templatePlan.contentHash ?? "";
-
- if (input.templatePlan.kind === "bootstrap") {
- const revalidationKey = input.templatePlan.revalidationKey ?? "";
- return createStableHash(
- `bootstrap:${revalidationKey}:${input.templatePlan.sourceHash}:${contentHash}:${input.nodeId}:${input.sourceId}`,
- );
- }
-
- return createStableHash(`workspace-content:${contentHash}:${input.nodeId}:${input.sourceId}`);
-}
-
-function createStableHash(value: string): string {
- return createHash("sha256").update(value).digest("hex");
-}
-
-function sanitizeRuntimeSandboxKey(value: string): string {
- return value.replaceAll(/[^a-zA-Z0-9._-]+/g, "-").slice(0, 120);
-}
diff --git a/packages/eve/src/runtime/sandbox/prepared-artifacts.integration.test.ts b/packages/eve/src/runtime/sandbox/prepared-artifacts.integration.test.ts
new file mode 100644
index 000000000..ed37a42d7
--- /dev/null
+++ b/packages/eve/src/runtime/sandbox/prepared-artifacts.integration.test.ts
@@ -0,0 +1,69 @@
+import { mkdir } from "node:fs/promises";
+import { join } from "node:path";
+
+import { describe, expect, it } from "vitest";
+
+import { createDiskRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
+import { withBundledCompiledArtifacts } from "#runtime/loaders/bundled-artifacts.js";
+import {
+ loadSandboxPreparedArtifact,
+ writeSandboxPreparedArtifactsManifest,
+} from "#runtime/sandbox/prepared-artifacts.js";
+import { createSandboxPreparedArtifactsManifest } from "#shared/sandbox-prepared-artifacts.js";
+import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";
+
+const createScratchDirectory = useTemporaryDirectories();
+
+describe("sandbox prepared artifacts", () => {
+ it("writes and loads provider artifacts from disk", async () => {
+ const appRoot = await createScratchDirectory("eve-sandbox-prepared-artifacts-");
+ const compileDirectoryPath = join(appRoot, ".eve", "compile");
+ await mkdir(compileDirectoryPath, { recursive: true });
+
+ await writeSandboxPreparedArtifactsManifest({
+ compileDirectoryPath,
+ entries: [
+ {
+ artifact: { imageReference: "eve-template:v1" },
+ nodeId: "__root__",
+ providerName: "docker",
+ },
+ ],
+ });
+
+ await expect(
+ loadSandboxPreparedArtifact({
+ compiledArtifactsSource: createDiskRuntimeCompiledArtifactsSource(appRoot),
+ nodeId: "__root__",
+ providerName: "docker",
+ }),
+ ).resolves.toEqual({ imageReference: "eve-template:v1" });
+ });
+
+ it("loads the same artifact from bundled runtime state", async () => {
+ const sandboxPreparedArtifacts = createSandboxPreparedArtifactsManifest([
+ {
+ artifact: { snapshotId: "snap_123" },
+ nodeId: "__root__",
+ providerName: "vercel",
+ },
+ ]);
+
+ await withBundledCompiledArtifacts(
+ {
+ manifest: {} as never,
+ moduleMap: {} as never,
+ sandboxPreparedArtifacts,
+ },
+ async () => {
+ await expect(
+ loadSandboxPreparedArtifact({
+ compiledArtifactsSource: { kind: "bundled" },
+ nodeId: "__root__",
+ providerName: "vercel",
+ }),
+ ).resolves.toEqual({ snapshotId: "snap_123" });
+ },
+ );
+ });
+});
diff --git a/packages/eve/src/runtime/sandbox/prepared-artifacts.ts b/packages/eve/src/runtime/sandbox/prepared-artifacts.ts
new file mode 100644
index 000000000..2676eec89
--- /dev/null
+++ b/packages/eve/src/runtime/sandbox/prepared-artifacts.ts
@@ -0,0 +1,64 @@
+import { readFile, writeFile } from "node:fs/promises";
+
+import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
+import { readBundledCompiledArtifacts } from "#runtime/loaders/bundled-artifacts.js";
+import { resolveRuntimeCompilerArtifactPaths } from "#runtime/loaders/artifact-paths.js";
+import {
+ createSandboxPreparedArtifactsManifest,
+ sandboxPreparedArtifactsManifestSchema,
+ type SandboxPreparedArtifactEntry,
+ type SandboxPreparedArtifactsManifest,
+} from "#shared/sandbox-prepared-artifacts.js";
+import type { SandboxPreparedArtifact } from "#shared/sandbox-provider.js";
+
+export async function writeSandboxPreparedArtifactsManifest(input: {
+ readonly compileDirectoryPath: string;
+ readonly entries: readonly SandboxPreparedArtifactEntry[];
+}): Promise<void> {
+ if (input.entries.length === 0) return;
+ const path = `${input.compileDirectoryPath}/sandbox-prepared-artifacts.json`;
+ let existing: SandboxPreparedArtifactsManifest | null = null;
+ try {
+ existing = sandboxPreparedArtifactsManifestSchema.parse(
+ JSON.parse(await readFile(path, "utf8")),
+ );
+ } catch (error) {
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
+ }
+ const entries = new Map(existing?.entries.map((entry) => [entry.nodeId, entry]));
+ for (const entry of input.entries) entries.set(entry.nodeId, entry);
+ await writeFile(
+ path,
+ `${JSON.stringify(createSandboxPreparedArtifactsManifest([...entries.values()]), null, 2)}\n`,
+ );
+}
+
+export async function loadSandboxPreparedArtifact(input: {
+ readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
+ readonly nodeId: string;
+ readonly providerName: string;
+}): Promise<SandboxPreparedArtifact | undefined> {
+ const manifest = await loadSandboxPreparedArtifactsManifest(input.compiledArtifactsSource);
+ const entry = manifest?.entries.find((candidate) => candidate.nodeId === input.nodeId);
+ if (entry !== undefined && entry.providerName !== input.providerName) {
+ throw new Error(
+ `Prepared sandbox artifact for node "${input.nodeId}" belongs to provider "${entry.providerName}", not "${input.providerName}".`,
+ );
+ }
+ return entry?.artifact;
+}
+
+export async function loadSandboxPreparedArtifactsManifest(
+ source: RuntimeCompiledArtifactsSource,
+): Promise<SandboxPreparedArtifactsManifest | null> {
+ if (source.kind === "bundled") {
+ return readBundledCompiledArtifacts()?.sandboxPreparedArtifacts ?? null;
+ }
+ const path = resolveRuntimeCompilerArtifactPaths(source.appRoot).sandboxPreparedArtifactsPath;
+ try {
+ return sandboxPreparedArtifactsManifestSchema.parse(JSON.parse(await readFile(path, "utf8")));
+ } catch (error) {
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return null;
+ throw error;
+ }
+}
diff --git a/packages/eve/src/runtime/sandbox/registry.test.ts b/packages/eve/src/runtime/sandbox/registry.test.ts
index c5b2e6ec8..cf5553099 100644
--- a/packages/eve/src/runtime/sandbox/registry.test.ts
+++ b/packages/eve/src/runtime/sandbox/registry.test.ts
@@ -1,40 +1,30 @@
import { describe, expect, it } from "vitest";
-
-import type { ResolvedSandboxDefinition } from "#runtime/types.js";
+import { defineParentSandbox } from "#public/definitions/sandbox.js";
import { createRuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";
-
-const inheritedDefinition = {
- backend: { name: "test" },
- inheritsParent: true,
- logicalPath: "agent/subagents/foo/sandbox.ts",
- sourceId: "agent/subagents/foo/sandbox",
+import type { ResolvedSandboxDefinition } from "#runtime/types.js";
+const parent: ResolvedSandboxDefinition = {
+ kind: "parent",
+ logicalPath: "sandbox.ts",
+ revisionHash: "parent-sandbox-revision",
+ selector: defineParentSandbox(),
+ sourceId: "sandbox",
sourceKind: "module",
-} as ResolvedSandboxDefinition;
-
+};
describe("createRuntimeSandboxRegistry", () => {
- it("allows an empty child to inherit its parent sandbox", () => {
+ it("allows parent inheritance without resources", () => {
expect(
createRuntimeSandboxRegistry({
- sandbox: inheritedDefinition,
+ sandbox: parent,
workspaceResourceRoot: { logicalPath: "", rootEntries: [] },
- }),
- ).toMatchObject({
- sandbox: { definition: inheritedDefinition },
- });
+ }).sandbox.definition.kind,
+ ).toBe("parent");
});
-
- it("rejects child workspace resources when inheriting the parent sandbox", () => {
+ it("rejects parent inheritance with resources", () => {
expect(() =>
createRuntimeSandboxRegistry({
- sandbox: inheritedDefinition,
- workspaceResourceRoot: {
- contentHash: "child-content",
- logicalPath: "workspace-resources/foo",
- rootEntries: ["bar.txt"],
- },
+ sandbox: parent,
+ workspaceResourceRoot: { contentHash: "hash", logicalPath: "resources", rootEntries: [] },
}),
- ).toThrow(
- 'Sandbox "agent/subagents/foo/sandbox.ts" selects parent.sandbox but has managed workspace resources. Remove the child workspace or give the child its own sandbox.',
- );
+ ).toThrow("managed workspace resources");
});
});
diff --git a/packages/eve/src/runtime/sandbox/registry.ts b/packages/eve/src/runtime/sandbox/registry.ts
index b5ee3b5fa..04be9f552 100644
--- a/packages/eve/src/runtime/sandbox/registry.ts
+++ b/packages/eve/src/runtime/sandbox/registry.ts
@@ -1,13 +1,6 @@
import type { CompiledWorkspaceResourceRoot } from "#compiler/manifest.js";
import type { ResolvedSandboxDefinition } from "#runtime/types.js";
-/**
- * Stable internal source id for the framework-owned default sandbox.
- *
- * Used by the runtime template/session key derivation and by prewarm
- * to distinguish the shared framework sandbox from per-node authored
- * overrides.
- */
/**
* Resolved sandbox tracked by the runtime-owned registry.
*
@@ -18,8 +11,8 @@ import type { ResolvedSandboxDefinition } from "#runtime/types.js";
* compiled workspace resource tree owned by this graph node. The
* prewarm orchestrator resolves the descriptor's logical path against
* the active compiled artifacts source and writes the contents into
- * the sandbox template snapshot. Runtime `backend.create(...)` never
- * reads these files.
+ * the sandbox template artifact. Runtime provider `open(...)` never reads these
+ * files.
*/
export interface RuntimeRegisteredSandbox {
readonly definition: ResolvedSandboxDefinition;
@@ -54,7 +47,7 @@ export function createRuntimeSandboxRegistry(input: {
}): RuntimeSandboxRegistry {
const definition = input.sandbox;
if (
- definition.inheritsParent === true &&
+ definition.kind === "parent" &&
(input.workspaceResourceRoot.contentHash !== undefined ||
input.workspaceResourceRoot.rootEntries.length > 0)
) {
diff --git a/packages/eve/src/runtime/sandbox/template-plan.ts b/packages/eve/src/runtime/sandbox/template-plan.ts
deleted file mode 100644
index 24989b03c..000000000
--- a/packages/eve/src/runtime/sandbox/template-plan.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import type { CompiledWorkspaceResourceRoot } from "#compiler/manifest.js";
-import type { ResolvedSandboxDefinition } from "#runtime/types.js";
-
-/**
- * Describes whether one sandbox needs a prewarmed template and, if so,
- * which inputs must participate in the template key.
- */
-export type RuntimeSandboxTemplatePlan =
- | {
- readonly kind: "none";
- }
- | {
- readonly contentHash?: string;
- readonly kind: "workspace-content";
- }
- | {
- readonly contentHash?: string;
- readonly kind: "bootstrap";
- readonly revalidationKey?: string;
- readonly sourceHash: string;
- };
-
-/**
- * Chooses the template strategy for one resolved sandbox definition.
- */
-export function createRuntimeSandboxTemplatePlan(input: {
- readonly definition: ResolvedSandboxDefinition;
- readonly workspaceResourceRoot: CompiledWorkspaceResourceRoot;
-}): RuntimeSandboxTemplatePlan {
- if (input.definition.bootstrap !== undefined) {
- if (input.definition.sourceHash === undefined) {
- throw new Error(
- `Sandbox "${input.definition.logicalPath}" defines bootstrap() but has no compiled sourceHash.`,
- );
- }
-
- return {
- contentHash: input.workspaceResourceRoot.contentHash,
- kind: "bootstrap",
- revalidationKey: input.definition.revalidationKey,
- sourceHash: input.definition.sourceHash,
- };
- }
-
- if (
- input.workspaceResourceRoot.contentHash === undefined &&
- input.workspaceResourceRoot.rootEntries.length === 0
- ) {
- return { kind: "none" };
- }
-
- return {
- contentHash: input.workspaceResourceRoot.contentHash,
- kind: "workspace-content",
- };
-}
diff --git a/packages/eve/src/runtime/sessions/runtime-session.ts b/packages/eve/src/runtime/sessions/runtime-session.ts
index abdfc960c..df99be5a7 100644
--- a/packages/eve/src/runtime/sessions/runtime-session.ts
+++ b/packages/eve/src/runtime/sessions/runtime-session.ts
@@ -74,7 +74,11 @@ function isSameCompiledArtifactSnapshot(
// Equivalent bootstrap modules do not share object identity, but the
// compiler fingerprint is stable across their copies.
if (installedSourceGraphHash && inputSourceGraphHash) {
- return installedSourceGraphHash === inputSourceGraphHash;
+ return (
+ installedSourceGraphHash === inputSourceGraphHash &&
+ JSON.stringify(installed.sandboxPreparedArtifacts) ===
+ JSON.stringify(input.sandboxPreparedArtifacts)
+ );
}
return (
diff --git a/packages/eve/src/runtime/types.ts b/packages/eve/src/runtime/types.ts
index f2f00713d..f1f7e4f59 100644
--- a/packages/eve/src/runtime/types.ts
+++ b/packages/eve/src/runtime/types.ts
@@ -35,8 +35,7 @@ import type { InternalAgentDefinition } from "#shared/agent-definition.js";
import type { RuntimeDynamicModelReference } from "#runtime/agent/bootstrap.js";
import type { InternalToolDefinitionWithExecuteFn } from "#tools/definition.js";
import type { CompiledToolBehavior } from "#tools/behavior.js";
-import type { SandboxBackend } from "#shared/sandbox-backend.js";
-import type { SandboxBootstrapContext, SandboxSessionContext } from "#shared/sandbox-definition.js";
+import type { SandboxEnvironmentIdentity, SandboxSelector } from "#shared/sandbox-environment.js";
import type { ToolSchema } from "#tools/schema.js";
import type { AgentSourceOwner } from "#compiler/source-graph.js";
import type { MemoryDefinition } from "#public/memory/index.js";
@@ -128,33 +127,21 @@ export interface ResolvedConnectionDefinition extends ResolvedModuleSourceRef {
}
/**
- * Runtime-owned authored sandbox definition resolved from a compiled module
- * map.
- *
- * The resolved `backend` is non-optional: every sandbox in the runtime
- * graph carries a concrete SandboxBackend value, even when the
- * authored definition omits `backend`. The omitted field is filled
- * in by `defaultSandbox()` (which itself selects between
- * `vercel()`, `docker()`, `microsandbox()`, and `justbash()` based on the current
- * environment).
+ * Runtime-owned sandbox definition resolved from a compiled module map.
+ * Independent definitions carry their exported environment; parent definitions
+ * explicitly inherit the dispatching agent's sandbox.
*/
-export type ResolvedSandboxDefinition = ResolvedModuleSourceRef & {
- readonly bootstrap?: (input: SandboxBootstrapContext) => Promise<void> | void;
- readonly revalidationKey?: string;
- readonly sourceHash?: string;
- /**
- * Resolved backend value. The authored `SandboxDefinition.backend`
- * accepts either a `SandboxBackend` or a `() => SandboxBackend`; by
- * the time it reaches the runtime the function form has been
- * unwrapped via `lazyBackend(...)` so consumers always see a plain
- * value.
- */
- readonly backend: SandboxBackend;
- readonly description?: string;
- readonly inheritsParent?: boolean;
- readonly onSession?: (input: SandboxSessionContext) => Promise<void> | void;
+type ResolvedSandboxDefinitionBase = ResolvedModuleSourceRef & {
+ readonly revisionHash: string;
+ readonly selector: SandboxSelector;
};
+export type ResolvedSandboxDefinition = ResolvedSandboxDefinitionBase &
+ (
+ | { readonly environment: SandboxEnvironmentIdentity; readonly kind: "independent" }
+ | { readonly kind: "parent" }
+ );
+
/**
* Runtime-owned tool definition resolved from the selected compiled source graph.
* A tool without `execute` is surfaced to the client and never executed by eve.
diff --git a/packages/eve/src/runtime/workspace/types.ts b/packages/eve/src/runtime/workspace/types.ts
index 32f612919..b1c2b79cd 100644
--- a/packages/eve/src/runtime/workspace/types.ts
+++ b/packages/eve/src/runtime/workspace/types.ts
@@ -1,6 +1,6 @@
/**
* Stable root directory for every workspace eve exposes to agents and
- * sandbox backends.
+ * sandbox providers.
*
* This is both the model-facing logical path and the live `bash` cwd
* for every backend. Backends must initialize their filesystems so
diff --git a/packages/eve/src/sandbox/backends/default.ts b/packages/eve/src/sandbox/backends/default.ts
deleted file mode 100644
index 5b23e0865..000000000
--- a/packages/eve/src/sandbox/backends/default.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import { SANDBOX_BACKEND_PROBES, type DefaultSandboxProbes } from "./probes.js";
-import { lazyBackend } from "#execution/sandbox/lazy-backend.js";
-import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
-import { docker } from "#sandbox/backends/docker.js";
-import type { DockerSandboxCreateOptions } from "#public/sandbox/docker-sandbox.js";
-import { justbash } from "#sandbox/backends/just-bash.js";
-import type { JustBashSandboxCreateOptions } from "#public/sandbox/just-bash-sandbox.js";
-import { microsandbox } from "#sandbox/backends/microsandbox.js";
-import type { MicrosandboxSandboxCreateOptions } from "#public/sandbox/microsandbox-sandbox.js";
-import { vercel } from "#sandbox/backends/vercel.js";
-import type { VercelSandboxCreateOptions } from "#public/sandbox/vercel-sandbox.js";
-
-export { SANDBOX_BACKEND_PROBES, type DefaultSandboxProbes } from "./probes.js";
-
-/**
- * Input to {@link defaultSandbox}: a separate options bag per inner
- * backend. The framework picks one backend at runtime based on
- * availability and passes it the matching bag; the others are ignored.
- */
-export interface DefaultSandboxOptions {
- readonly docker?: DockerSandboxCreateOptions;
- readonly justBash?: JustBashSandboxCreateOptions;
- readonly microsandbox?: MicrosandboxSandboxCreateOptions;
- readonly vercel?: VercelSandboxCreateOptions;
-}
-
-/**
- * Constructs an availability-aware sandbox backend. On first use it
- * picks the best backend the host supports, in priority order:
- *
- * 1. **Vercel Sandbox** when deploying on Vercel (`process.env.VERCEL`
- * is set) — local container/VM runtimes cannot run there.
- * 2. **Docker** when a Linux-container Docker daemon is reachable.
- * 3. **microsandbox** when the host supports it (macOS on Apple
- * Silicon, or glibc Linux with KVM); `eve dev` auto-installs the
- * package into the project.
- * 4. **just-bash** as the dependency-free fallback; `eve dev`
- * auto-installs the package into the project.
- *
- * The selection is cached for the process lifetime. To pin a backend
- * unconditionally, configure its factory directly (`docker()`,
- * `microsandbox()`, `justbash()`,
- * `vercel()`).
- */
-export function defaultSandbox(opts?: DefaultSandboxOptions): SandboxBackend {
- return lazyBackend(() => selectDefaultSandbox(opts, SANDBOX_BACKEND_PROBES));
-}
-
-/**
- * The selection chain behind {@link defaultSandbox}. Internal —
- * exported for tests, which inject probes.
- */
-export function selectDefaultSandbox(
- opts: DefaultSandboxOptions | undefined,
- probes: DefaultSandboxProbes,
-): SandboxBackend {
- if (probes.isDeployedOnVercel()) {
- return vercel(opts?.vercel);
- }
- if (probes.isDockerAvailable()) {
- return docker(opts?.docker);
- }
- if (probes.isMicrosandboxSupported()) {
- return microsandbox(opts?.microsandbox);
- }
- return justbash(opts?.justBash);
-}
diff --git a/packages/eve/src/sandbox/backends/docker.ts b/packages/eve/src/sandbox/backends/docker.ts
deleted file mode 100644
index 6fbbcbb3e..000000000
--- a/packages/eve/src/sandbox/backends/docker.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { createDockerSandboxBackend } from "#execution/sandbox/bindings/local.js";
-
-import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
-import type { DockerSandboxCreateOptions } from "#public/sandbox/docker-sandbox.js";
-
-/**
- * Constructs the Docker sandbox backend: the workspace runs inside a
- * real Linux container driven through the Docker CLI, using the
- * official Ubuntu 26.04 image by default.
- *
- * Requires a running Docker-compatible daemon reachable through a
- * `docker` CLI (Docker Desktop, OrbStack, Colima, Podman via its
- * docker-compatible CLI, …; override the binary with `EVE_DOCKER_PATH`).
- * Configuring this backend pins it unconditionally — when you want
- * fallback behavior, use `defaultBackend()` instead.
- */
-export function docker(opts?: DockerSandboxCreateOptions): SandboxBackend {
- return createDockerSandboxBackend({ createOptions: opts });
-}
diff --git a/packages/eve/src/sandbox/backends/just-bash.ts b/packages/eve/src/sandbox/backends/just-bash.ts
deleted file mode 100644
index 8f773f329..000000000
--- a/packages/eve/src/sandbox/backends/just-bash.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { createJustBashSandboxBackend } from "#execution/sandbox/bindings/local.js";
-
-import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
-import type { JustBashSandboxCreateOptions } from "#public/sandbox/just-bash-sandbox.js";
-
-/**
- * Constructs the just-bash sandbox backend: a pure-JS bash interpreter
- * over a virtual filesystem stored under `.eve/sandbox-cache/`. It
- * needs no daemon or VM, but commands run in a simulated shell — no
- * real binaries (`git`, `node`, package managers) and no network
- * isolation.
- *
- * The `just-bash` package is not bundled with eve. When it is missing,
- * `eve dev` installs it into the application automatically (disable
- * with `autoInstall: false`); production processes fail with an
- * actionable install error instead. Configuring this backend pins it
- * unconditionally — when you want fallback behavior, use
- * `defaultBackend()` instead.
- */
-export function justbash(opts?: JustBashSandboxCreateOptions): SandboxBackend {
- return createJustBashSandboxBackend({ createOptions: opts });
-}
diff --git a/packages/eve/src/sandbox/backends/microsandbox.ts b/packages/eve/src/sandbox/backends/microsandbox.ts
deleted file mode 100644
index 019a979f6..000000000
--- a/packages/eve/src/sandbox/backends/microsandbox.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { createMicrosandboxSandboxBackend } from "#execution/sandbox/bindings/local.js";
-
-import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
-import type {
- MicrosandboxBootstrapUseOptions,
- MicrosandboxSandboxCreateOptions,
- MicrosandboxSessionUseOptions,
-} from "#public/sandbox/microsandbox-sandbox.js";
-
-/**
- * Constructs the microsandbox sandbox backend: lightweight local VMs
- * via [microsandbox](https://www.npmjs.com/package/microsandbox) with
- * snapshot-backed templates and a firewall capable of domain-level
- * network policies and credential brokering.
- *
- * Supported hosts: macOS on Apple Silicon, or Linux (glibc) with KVM
- * enabled. The `microsandbox` package is not bundled with eve. When it
- * (or its VM runtime) is missing, `eve dev` installs both
- * automatically (disable with `setup: { autoInstall: false }`);
- * production processes fail with actionable errors instead.
- * Configuring this backend pins it unconditionally — when you want
- * fallback behavior, use `defaultBackend()` instead.
- */
-export function microsandbox(
- opts?: MicrosandboxSandboxCreateOptions,
-): SandboxBackend<MicrosandboxBootstrapUseOptions, MicrosandboxSessionUseOptions> {
- return createMicrosandboxSandboxBackend({ createOptions: opts });
-}
diff --git a/packages/eve/src/sandbox/backends/vercel.ts b/packages/eve/src/sandbox/backends/vercel.ts
deleted file mode 100644
index b659a6091..000000000
--- a/packages/eve/src/sandbox/backends/vercel.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { createVercelSandbox } from "#execution/sandbox/bindings/vercel.js";
-
-import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
-import type {
- VercelSandboxBootstrapUseOptions,
- VercelSandboxOptions,
- VercelSandboxSessionUseOptions,
-} from "#public/sandbox/vercel-sandbox.js";
-
-/**
- * Constructs the [Vercel Sandbox](https://vercel.com/docs/sandbox)
- * backend. Configuring this backend pins it unconditionally —
- * including for local development, where it creates real hosted
- * sandboxes (requires Vercel credentials).
- *
- * The optional provider creation fields are forwarded to Vercel Sandbox creation
- * for every fresh sandbox the framework creates (template at prewarm,
- * session at first-time create). On resume (`Sandbox.get`), no create
- * happens, so opts are not re-applied. `networkPolicy` is applied after
- * framework-owned base setup for fresh templates and template-less
- * sessions, before authored bootstrap code runs.
- *
- * `opts.source`, if supplied, is used only on the template create:
- * the author's snapshot, git revision, or tarball becomes the base
- * layer of the template. Bootstrap, seed files, and framework setup
- * still run on top, and every session derives from the resulting
- * eve-owned snapshot. `source` is stripped from session creates so the
- * framework's snapshot always wins.
- *
- * `bootstrap({ use })` applies its options to the template via
- * `sandbox.update(...)`; those settings persist into the snapshot.
- * `onSession({ use })` applies its options to the live session via the
- * SDK's `update` under the hood, overriding any overlapping field
- * from `opts`. `sessionCreateOptions`, when provided, is resolved only
- * when creating a fresh live session and can attach session-specific Drives.
- */
-export function vercel(
- opts?: VercelSandboxOptions,
-): SandboxBackend<VercelSandboxBootstrapUseOptions, VercelSandboxSessionUseOptions> {
- const { sessionCreateOptions, ...createOptions } = opts ?? {};
- return createVercelSandbox({
- createOptions,
- resolveSessionCreateOptions: sessionCreateOptions,
- });
-}
diff --git a/packages/eve/src/sandbox/providers.test.ts b/packages/eve/src/sandbox/providers.test.ts
new file mode 100644
index 000000000..bb3ce6da7
--- /dev/null
+++ b/packages/eve/src/sandbox/providers.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, expectTypeOf, it } from "vitest";
+
+import { defineDefaultSandboxProvider } from "#sandbox/providers/default.js";
+import { DockerSandbox, MicrosandboxSandbox, VercelSandbox } from "#sandbox/providers.js";
+import type {
+ MutableNetworkSandboxSession,
+ RuntimeSandboxSessionFor,
+} from "#shared/sandbox-session.js";
+
+describe("sandbox providers", () => {
+ it("implements default selection through the provider contract", () => {
+ const environment = defineDefaultSandboxProvider({
+ isDeployedOnVercel: () => true,
+ isDockerAvailable: () => false,
+ isMicrosandboxSupported: () => false,
+ }).environment();
+ expect(environment.provider).toBe("vercel");
+ });
+ it("exposes image and Dockerfile constructors only for local image providers", () => {
+ expect(DockerSandbox.image("example.test/agent@sha256:abc").provider).toBe("docker");
+ expect(DockerSandbox.dockerfile().provider).toBe("docker");
+ expect(MicrosandboxSandbox.image("example.test/agent@sha256:abc").provider).toBe(
+ "microsandbox",
+ );
+ expect(MicrosandboxSandbox.dockerfile().provider).toBe("microsandbox");
+ expect("image" in VercelSandbox).toBe(false);
+ expect("dockerfile" in VercelSandbox).toBe(false);
+ });
+
+ it("returns runtime sandboxes from open", () => {
+ const environment = DockerSandbox.environment();
+ expectTypeOf(environment.open).returns.toEqualTypeOf<
+ Promise<RuntimeSandboxSessionFor<MutableNetworkSandboxSession>>
+ >();
+ });
+});
diff --git a/packages/eve/src/sandbox/providers.ts b/packages/eve/src/sandbox/providers.ts
new file mode 100644
index 000000000..feee69b8a
--- /dev/null
+++ b/packages/eve/src/sandbox/providers.ts
@@ -0,0 +1,5 @@
+export { DefaultSandbox } from "#sandbox/providers/default.js";
+export { DockerSandbox } from "#sandbox/providers/docker.js";
+export { JustBashSandbox } from "#sandbox/providers/just-bash.js";
+export { MicrosandboxSandbox } from "#sandbox/providers/microsandbox.js";
+export { VercelSandbox } from "#sandbox/providers/vercel.js";
diff --git a/packages/eve/src/sandbox/providers/default.ts b/packages/eve/src/sandbox/providers/default.ts
new file mode 100644
index 000000000..15f30fc3c
--- /dev/null
+++ b/packages/eve/src/sandbox/providers/default.ts
@@ -0,0 +1,73 @@
+import {
+ isLinuxDockerDaemonAvailableSync,
+ isMicrosandboxPlatformSupported,
+} from "#execution/sandbox/bindings/local.js";
+import type { DockerSandboxEnvironmentOptions } from "#public/sandbox/docker-sandbox.js";
+import type { JustBashSandboxCreateOptions } from "#public/sandbox/just-bash-sandbox.js";
+import type { MicrosandboxSandboxCreateOptions } from "#public/sandbox/microsandbox-sandbox.js";
+import type { VercelSandboxCreateOptions } from "#public/sandbox/vercel-sandbox.js";
+import { DockerSandbox } from "#sandbox/providers/docker.js";
+import { JustBashSandbox } from "#sandbox/providers/just-bash.js";
+import { MicrosandboxSandbox } from "#sandbox/providers/microsandbox.js";
+import { createDefaultVercelEnvironment } from "#sandbox/providers/vercel.js";
+import type { SandboxEnvironment } from "#shared/sandbox-environment.js";
+import type { SandboxSession } from "#shared/sandbox-session.js";
+
+export interface DefaultSandboxEnvironmentOptions {
+ readonly docker?: DockerSandboxEnvironmentOptions;
+ readonly justBash?: JustBashSandboxCreateOptions;
+ readonly microsandbox?: MicrosandboxSandboxCreateOptions;
+ readonly prepare?: (sandbox: SandboxSession) => Promise<void> | void;
+ readonly vercel?: VercelSandboxCreateOptions;
+}
+
+export interface DefaultSandboxProbes {
+ readonly isDeployedOnVercel: () => boolean;
+ readonly isDockerAvailable: () => boolean;
+ readonly isMicrosandboxSupported: () => boolean;
+}
+
+export const SANDBOX_PROVIDER_PROBES: DefaultSandboxProbes = {
+ isDeployedOnVercel: () => Boolean(process.env.VERCEL),
+ isDockerAvailable: () => isLinuxDockerDaemonAvailableSync(),
+ isMicrosandboxSupported: () => isMicrosandboxPlatformSupported(),
+};
+
+export const DefaultSandbox = defineDefaultSandboxProvider(SANDBOX_PROVIDER_PROBES);
+
+export function defineDefaultSandboxProvider(probes: DefaultSandboxProbes) {
+ return {
+ name: "default",
+ environment(options: DefaultSandboxEnvironmentOptions = {}): SandboxEnvironment<undefined> {
+ if (probes.isDeployedOnVercel()) {
+ return withoutOpenOptions(
+ createDefaultVercelEnvironment(withPreparation(options.vercel, options.prepare)),
+ );
+ }
+ if (probes.isDockerAvailable()) {
+ return withoutOpenOptions(
+ DockerSandbox.environment(withPreparation(options.docker, options.prepare)),
+ );
+ }
+ if (probes.isMicrosandboxSupported()) {
+ return withoutOpenOptions(
+ MicrosandboxSandbox.environment(withPreparation(options.microsandbox, options.prepare)),
+ );
+ }
+ return JustBashSandbox.environment(withPreparation(options.justBash, options.prepare));
+ },
+ };
+}
+
+function withPreparation<Options extends object>(
+ options: Options | undefined,
+ prepare: ((sandbox: SandboxSession) => Promise<void> | void) | undefined,
+) {
+ return Object.assign({}, options, prepare === undefined ? {} : { prepare });
+}
+
+function withoutOpenOptions<Options extends object | undefined>(
+ environment: SandboxEnvironment<Options>,
+): SandboxEnvironment<undefined> {
+ return environment as SandboxEnvironment<undefined>;
+}
diff --git a/packages/eve/src/sandbox/providers/docker.ts b/packages/eve/src/sandbox/providers/docker.ts
new file mode 100644
index 000000000..889331260
--- /dev/null
+++ b/packages/eve/src/sandbox/providers/docker.ts
@@ -0,0 +1,43 @@
+import { createDockerSandboxProvider } from "#execution/sandbox/bindings/local.js";
+import type {
+ DockerSandboxEnvironmentOptions,
+ DockerSandboxRuntimeOptions,
+} from "#public/sandbox/docker-sandbox.js";
+import type { SandboxEnvironment } from "#shared/sandbox-environment.js";
+import { defineSandboxProvider } from "#shared/sandbox-provider.js";
+import type { MutableNetworkSandboxSession } from "#shared/sandbox-session.js";
+
+export type {
+ DockerSandboxEnvironmentOptions,
+ DockerSandboxRuntimeOptions,
+} from "#public/sandbox/docker-sandbox.js";
+
+type DockerfileEnvironmentInput = Omit<DockerSandboxEnvironmentOptions, "image">;
+
+const provider = defineSandboxProvider<
+ DockerSandboxEnvironmentOptions,
+ DockerSandboxRuntimeOptions,
+ { readonly imageReference: string },
+ { readonly containerName: string; readonly generation: string; readonly version: 2 },
+ MutableNetworkSandboxSession
+>({
+ name: "docker",
+ environment(options) {
+ return createDockerSandboxProvider(options);
+ },
+});
+
+export const DockerSandbox = {
+ ...provider,
+ dockerfile(
+ options: DockerfileEnvironmentInput = {},
+ ): SandboxEnvironment<DockerSandboxRuntimeOptions, MutableNetworkSandboxSession> {
+ return provider.environment(options);
+ },
+ image(
+ reference: string,
+ options: DockerfileEnvironmentInput = {},
+ ): SandboxEnvironment<DockerSandboxRuntimeOptions, MutableNetworkSandboxSession> {
+ return provider.environment({ ...options, image: reference });
+ },
+};
diff --git a/packages/eve/src/sandbox/providers/just-bash.ts b/packages/eve/src/sandbox/providers/just-bash.ts
new file mode 100644
index 000000000..8ce20bf72
--- /dev/null
+++ b/packages/eve/src/sandbox/providers/just-bash.ts
@@ -0,0 +1,17 @@
+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 type { FixedNetworkSandboxSession } from "#shared/sandbox-session.js";
+
+export type JustBashEnvironmentOptions = JustBashSandboxCreateOptions;
+
+export const JustBashSandbox = defineSandboxProvider<
+ JustBashEnvironmentOptions,
+ undefined,
+ { readonly templateRootPath: string },
+ { readonly generation: string; readonly rootPath: string; readonly version: 2 },
+ FixedNetworkSandboxSession
+>({
+ name: "just-bash",
+ environment: (options) => createJustBashSandboxProvider(options),
+});
diff --git a/packages/eve/src/sandbox/providers/microsandbox.ts b/packages/eve/src/sandbox/providers/microsandbox.ts
new file mode 100644
index 000000000..68f175e68
--- /dev/null
+++ b/packages/eve/src/sandbox/providers/microsandbox.ts
@@ -0,0 +1,43 @@
+import {
+ createMicrosandboxSandboxProvider,
+ type MicrosandboxProviderSessionState,
+} from "#execution/sandbox/bindings/microsandbox.js";
+import type { MicrosandboxPreparedArtifact } from "#execution/sandbox/bindings/microsandbox-lifecycle.js";
+import type {
+ MicrosandboxSandboxCreateOptions,
+ MicrosandboxSandboxRuntimeOptions,
+} from "#public/sandbox/microsandbox-sandbox.js";
+import type { SandboxEnvironment } from "#shared/sandbox-environment.js";
+import { defineSandboxProvider } from "#shared/sandbox-provider.js";
+import type { MutableNetworkSandboxSession } from "#shared/sandbox-session.js";
+
+export type MicrosandboxEnvironmentOptions = MicrosandboxSandboxCreateOptions;
+
+type DockerfileEnvironmentInput = Omit<MicrosandboxEnvironmentOptions, "image">;
+
+const provider = defineSandboxProvider<
+ MicrosandboxEnvironmentOptions,
+ MicrosandboxSandboxRuntimeOptions,
+ MicrosandboxPreparedArtifact,
+ MicrosandboxProviderSessionState,
+ MutableNetworkSandboxSession
+>({
+ name: "microsandbox",
+ stateProtocolVersion: 3,
+ environment: (options) => createMicrosandboxSandboxProvider(options),
+});
+
+export const MicrosandboxSandbox = {
+ ...provider,
+ dockerfile(
+ options: DockerfileEnvironmentInput = {},
+ ): SandboxEnvironment<MicrosandboxSandboxRuntimeOptions, MutableNetworkSandboxSession> {
+ return provider.environment(options);
+ },
+ image(
+ reference: string,
+ options: DockerfileEnvironmentInput = {},
+ ): SandboxEnvironment<MicrosandboxSandboxRuntimeOptions, MutableNetworkSandboxSession> {
+ return provider.environment({ ...options, image: reference });
+ },
+};
diff --git a/packages/eve/src/sandbox/providers/vercel.ts b/packages/eve/src/sandbox/providers/vercel.ts
new file mode 100644
index 000000000..149a0816d
--- /dev/null
+++ b/packages/eve/src/sandbox/providers/vercel.ts
@@ -0,0 +1,58 @@
+import {
+ createVercelSandbox,
+ createVercelSandboxProvider,
+ type VercelSandboxPreparedArtifact,
+ type VercelSandboxSessionState,
+} from "#execution/sandbox/bindings/vercel.js";
+import type {
+ VercelSandboxCreateOptions,
+ VercelSandboxRuntimeOptions,
+} from "#public/sandbox/vercel-sandbox.js";
+import type { SandboxEnvironment } from "#shared/sandbox-environment.js";
+import { defineSandboxProvider } from "#shared/sandbox-provider.js";
+import type { MutableNetworkSandboxSession, SandboxSession } from "#shared/sandbox-session.js";
+
+export type VercelSandboxEnvironmentOptions = VercelSandboxCreateOptions & {
+ readonly prepare?: (sandbox: SandboxSession) => Promise<void> | void;
+};
+export type { VercelSandboxRuntimeOptions } from "#public/sandbox/vercel-sandbox.js";
+
+const defaultProvider = defineSandboxProvider<
+ VercelSandboxEnvironmentOptions | undefined,
+ VercelSandboxRuntimeOptions,
+ VercelSandboxPreparedArtifact,
+ VercelSandboxSessionState,
+ MutableNetworkSandboxSession
+>({
+ name: "vercel",
+ environment: (options) => {
+ const { prepare, ...createOptions } = options ?? {};
+ return createVercelSandbox({ createOptions, prepare, skipEmptyPreparation: true });
+ },
+});
+
+const provider = defineSandboxProvider<
+ VercelSandboxEnvironmentOptions | undefined,
+ VercelSandboxRuntimeOptions,
+ VercelSandboxPreparedArtifact,
+ VercelSandboxSessionState,
+ MutableNetworkSandboxSession
+>({
+ name: "vercel",
+ environment: (options) => createVercelSandboxProvider(options),
+});
+
+export function createDefaultVercelEnvironment(
+ options?: VercelSandboxEnvironmentOptions,
+): SandboxEnvironment<VercelSandboxRuntimeOptions, MutableNetworkSandboxSession> {
+ return defaultProvider.environment(options);
+}
+
+export const VercelSandbox = {
+ name: "vercel",
+ environment(
+ options?: VercelSandboxEnvironmentOptions,
+ ): SandboxEnvironment<VercelSandboxRuntimeOptions, MutableNetworkSandboxSession> {
+ return provider.environment(options);
+ },
+};
diff --git a/packages/eve/src/sandbox/state.ts b/packages/eve/src/sandbox/state.ts
index 5d3cb7e16..8dfb90f12 100644
--- a/packages/eve/src/sandbox/state.ts
+++ b/packages/eve/src/sandbox/state.ts
@@ -1,35 +1,16 @@
import type { SandboxSession } from "#public/definitions/sandbox.js";
-import type { SandboxBackendSessionState } from "#public/definitions/sandbox-backend.js";
-import type { SandboxDeleteOptions } from "#public/definitions/sandbox-backend.js";
+import type { SandboxDeleteOptions, SandboxPreparedArtifact } from "#shared/sandbox-provider.js";
-/**
- * Serializable sandbox reconnect record stored on the harness session.
- * Alias for {@link SandboxBackendSessionState} kept at this layer so
- * `SandboxState.session` can describe itself without importing the
- * backend's public-API spelling into harness code.
- */
-export type SandboxSessionState = SandboxBackendSessionState;
+export interface SandboxSessionState {
+ readonly providerName: string;
+ readonly state: SandboxPreparedArtifact;
+ readonly stateProtocolVersion: number;
+}
-/**
- * Serializable sandbox state carried on the harness session across
- * step boundaries.
- *
- * Contains only stable identifiers — live handles stay in a
- * process-level cache and are rehydrated per step via the backend.
- * Every agent owns exactly one sandbox, so the state is just a single
- * `initialized` flag and an optional persisted session record.
- */
export interface SandboxState {
- readonly initialized: boolean;
readonly session: SandboxSessionState | null;
}
-/**
- * Lazy sandbox accessor bound to one step execution.
- *
- * Returned by `ensureSandboxAccess` and placed on the `AlsContext` (via
- * `SandboxKey`) so tools can call `ctx.getSandbox()`.
- */
export interface SandboxAccess {
captureState(): Promise<SandboxState>;
delete?(options?: SandboxDeleteOptions): Promise<void>;
diff --git a/packages/eve/src/self-modification/authored-runtime-boundary.scenario.test.ts b/packages/eve/src/self-modification/authored-runtime-boundary.scenario.test.ts
index 66071d576..9b779784b 100644
--- a/packages/eve/src/self-modification/authored-runtime-boundary.scenario.test.ts
+++ b/packages/eve/src/self-modification/authored-runtime-boundary.scenario.test.ts
@@ -17,14 +17,7 @@ describe("self-modification authored runtime boundary", () => {
expect(code).not.toContain("createJustBashSandboxBackend");
expect(code).not.toContain("loadJustBashModule");
if (entry === "sandbox") {
- for (const specifier of [
- "eve/sandbox",
- "eve/sandbox/just-bash",
- "eve/sandbox/microsandbox",
- "eve/sandbox/vercel",
- ]) {
- expect(code).toContain(`from "${specifier}"`);
- }
+ expect(code).toContain('from "eve/self-modification/sandbox"');
} else {
expect(code).toContain('from "eve"');
}
diff --git a/packages/eve/src/self-modification/extension/subagents/agent/sandbox.ts b/packages/eve/src/self-modification/extension/subagents/agent/sandbox.ts
index 6b2be2cbe..9d60f8ebc 100644
--- a/packages/eve/src/self-modification/extension/subagents/agent/sandbox.ts
+++ b/packages/eve/src/self-modification/extension/subagents/agent/sandbox.ts
@@ -1,119 +1,6 @@
-import { shellQuote } from "#shared/shell-quote.js";
-import { SANDBOX_BACKEND_PROBES, type DefaultSandboxProbes } from "#sandbox/backends/probes.js";
-import {
- defaultBackend,
- defineSandbox,
- type SandboxBackend,
- type SandboxDefinition,
-} from "eve/sandbox";
-import { justbash } from "eve/sandbox/just-bash";
-import { microsandbox } from "eve/sandbox/microsandbox";
-import { vercel } from "eve/sandbox/vercel";
-
-import { resolveSelfModificationConfig, type SelfModificationConfig } from "../../../config.js";
-import { createGitHubCredentialProvider } from "../../../credentials.js";
-import { createLocalSelfModificationFilesystem } from "../../../filesystem.js";
-import { prepareSelfModificationWorkspace, REPOSITORY_PATH } from "../../../git-workspace.js";
-import { resolveSelfModificationMode } from "../../../mode.js";
-import { SELF_MODIFICATION_BASELINE_NETWORK_POLICY } from "../../../network-policy.js";
+import { defineSelfModificationSandbox } from "eve/self-modification/sandbox";
import selfModification from "../../extension.js";
-export interface SelfModificationSandboxOptions {
- /**
- * Production backend. Deployed self-modification owns an allow-all network
- * policy and temporarily adds a credential transform while checking out its
- * source. When omitted, eve selects Vercel Sandbox on Vercel or microsandbox
- * on a supported self-hosted system.
- */
- readonly backend?: SandboxBackend;
- /** Policy shared with the agent and extension mount. */
- readonly config?: SelfModificationConfig;
-}
-
-type SelfModificationSandboxProbes = Pick<
- DefaultSandboxProbes,
- "isDeployedOnVercel" | "isMicrosandboxSupported"
->;
-
-/** Defines the local source mount or isolated production proposal workspace. */
-export function defineSelfModificationSandbox(
- options: SelfModificationSandboxOptions = {},
-): SandboxDefinition {
- const config = resolveSelfModificationConfig(options.config ?? selfModification.config);
-
- return defineSandbox({
- backend: () => {
- const mode = resolveSelfModificationMode(config);
- if (mode === "local") return justbash({ filesystem: createLocalSelfModificationFilesystem });
- if (mode === "disabled") return options.backend ?? defaultBackend();
- return selectDeployedSelfModificationBackend(options.backend, SANDBOX_BACKEND_PROBES);
- },
- async onSession({ ctx, use }) {
- if (resolveSelfModificationMode(config) !== "deployed" || config.deployed === undefined)
- return;
- if (ctx.session.parent === undefined) {
- throw new Error(
- "Production self-modification workspaces require a delegated child session.",
- );
- }
-
- const deployed = config.deployed;
- const sandbox = await use();
- await sandbox.setNetworkPolicy(SELF_MODIFICATION_BASELINE_NETWORK_POLICY);
- const token = await createGitHubCredentialProvider(deployed.credentials).resolve({
- capability: "checkout",
- repository: deployed.repository,
- });
- await prepareSelfModificationWorkspace({
- directory: deployed.directory,
- repository: deployed.repository,
- sandbox,
- targetBranch: deployed.targetBranch,
- token,
- });
- const applicationRoot =
- deployed.directory === "." ? REPOSITORY_PATH : `${REPOSITORY_PATH}/${deployed.directory}`;
- const mounted = await sandbox.run({
- command: `rm -rf /source && ln -s ${shellQuote(`${applicationRoot}/agent`)} /source`,
- });
- if (mounted.exitCode !== 0) {
- throw new Error("Self-modification could not mount the production agent source.");
- }
- },
- });
-}
-
-/**
- * Deployed self-modification deliberately selects a backend that can inject
- * GitHub auth at the network boundary, keeping the credential outside the
- * sandbox and agent. Docker and just-bash do not provide that separation.
- * Internal—exported for tests, which inject availability probes.
- */
-export function selectDeployedSelfModificationBackend(
- configured: SandboxBackend | undefined,
- probes: SelfModificationSandboxProbes,
-): SandboxBackend {
- if (configured !== undefined) {
- if (configured.name === "vercel" || configured.name === "microsandbox") return configured;
- throw unsupportedBackend(configured.name);
- }
- if (probes.isDeployedOnVercel()) {
- return vercel({ networkPolicy: SELF_MODIFICATION_BASELINE_NETWORK_POLICY });
- }
- if (probes.isMicrosandboxSupported()) {
- return microsandbox({ networkPolicy: SELF_MODIFICATION_BASELINE_NETWORK_POLICY });
- }
- throw unsupportedBackend();
-}
-
-function unsupportedBackend(name?: string): Error {
- const reason =
- name === undefined
- ? "No supported backend is available."
- : `The configured ${name} backend does not support them.`;
- return new Error(
- `Deployed self-modification requires runtime credential transforms. ${reason} Use vercel() on Vercel or microsandbox() on a supported self-hosted system.`,
- );
-}
+export { defineSelfModificationSandbox } from "eve/self-modification/sandbox";
-export default defineSelfModificationSandbox();
+export default defineSelfModificationSandbox({ config: selfModification.config });
diff --git a/packages/eve/src/self-modification/extension/subagents/agent/tools/publish.ts b/packages/eve/src/self-modification/extension/subagents/agent/tools/publish.ts
index 58e59e464..a405d92a2 100644
--- a/packages/eve/src/self-modification/extension/subagents/agent/tools/publish.ts
+++ b/packages/eve/src/self-modification/extension/subagents/agent/tools/publish.ts
@@ -90,7 +90,7 @@ async function publish(input: unknown, toolContext: ToolContext) {
const title = input.title;
const operationId = publicationOperationId(toolContext);
const sandbox = await toolContext.getSandbox();
- return await withSelfModificationWorkspaceLock(`sandbox:${sandbox.id}`, async () => {
+ return await withSelfModificationWorkspaceLock(`sandbox:${toolContext.session.id}`, async () => {
const workspace = await readPreparedSelfModificationWorkspace({
...deployed,
sandbox,
diff --git a/packages/eve/src/self-modification/extension/subagents/agent/tools/registry_add.ts b/packages/eve/src/self-modification/extension/subagents/agent/tools/registry_add.ts
index 8d27132b6..27a018ce9 100644
--- a/packages/eve/src/self-modification/extension/subagents/agent/tools/registry_add.ts
+++ b/packages/eve/src/self-modification/extension/subagents/agent/tools/registry_add.ts
@@ -342,17 +342,20 @@ async function addProductionRegistryItem(
throw new Error(`No official eve registry item is published at "${address}".`);
}
const sandbox = await context.getSandbox();
- const result = await withSelfModificationWorkspaceLock(`sandbox:${sandbox.id}`, async () => {
- const workspace = await readPreparedSelfModificationWorkspace({ ...deployed, sandbox });
- return await installProductionRegistryItem({
- address,
- answers: continuation.answers,
- installed: continuation.installed,
- sandbox,
- signal: context.abortSignal,
- workspace,
- });
- });
+ const result = await withSelfModificationWorkspaceLock(
+ `sandbox:${context.session.id}`,
+ async () => {
+ const workspace = await readPreparedSelfModificationWorkspace({ ...deployed, sandbox });
+ return await installProductionRegistryItem({
+ address,
+ answers: continuation.answers,
+ installed: continuation.installed,
+ sandbox,
+ signal: context.abortSignal,
+ workspace,
+ });
+ },
+ );
if (result.kind === "completed") return { address, ...result, status: "completed" };
if (result.kind === "input-required") return { address, ...result, status: "input-required" };
if (result.kind === "external-action-required")
diff --git a/packages/eve/src/self-modification/filesystem.ts b/packages/eve/src/self-modification/filesystem.ts
index dd8a3f5a9..98add1e03 100644
--- a/packages/eve/src/self-modification/filesystem.ts
+++ b/packages/eve/src/self-modification/filesystem.ts
@@ -1,13 +1,13 @@
import { mkdir } from "node:fs/promises";
import { resolve } from "node:path";
-
import type { IFileSystem } from "just-bash";
import { getLocalDevCapability } from "eve/local-dev";
-export async function createLocalSelfModificationFilesystem(input: {
- readonly appRoot: string;
+export async function createSelfModificationFilesystem(input: {
+ readonly appRoot?: string;
readonly defaultFilesystem: IFileSystem;
+ resolveProjectPath?(path: string): string;
readonly justBash: typeof import("just-bash");
}): Promise<IFileSystem> {
const capability = getLocalDevCapability();
@@ -64,3 +64,5 @@ export async function createLocalSelfModificationFilesystem(input: {
],
});
}
+
+export const createLocalSelfModificationFilesystem = createSelfModificationFilesystem;
diff --git a/packages/eve/src/self-modification/git-workspace.ts b/packages/eve/src/self-modification/git-workspace.ts
index bbcd68803..2ee94062b 100644
--- a/packages/eve/src/self-modification/git-workspace.ts
+++ b/packages/eve/src/self-modification/git-workspace.ts
@@ -22,7 +22,8 @@ export interface PreparedSelfModificationWorkspace {
readonly targetBranch: string;
}
-type CheckoutSandbox = Pick<SandboxSession, "run" | "setNetworkPolicy">;
+type CheckoutSandbox = Pick<SandboxSession, "run"> &
+ Required<Pick<SandboxSession, "setNetworkPolicy">>;
/** Prepares a token-free remote and immutable target-branch checkout for one child session. */
export async function prepareSelfModificationWorkspace(input: {
diff --git a/packages/eve/src/self-modification/git.ts b/packages/eve/src/self-modification/git.ts
index bc408e47c..96147e282 100644
--- a/packages/eve/src/self-modification/git.ts
+++ b/packages/eve/src/self-modification/git.ts
@@ -8,7 +8,7 @@ const MAX_ERROR_OUTPUT = 2_000;
type CommandSandbox = Pick<SandboxSession, "run">;
export async function withBrokeredGitHubCredential<T>(
- sandbox: Pick<SandboxSession, "setNetworkPolicy">,
+ sandbox: Required<Pick<SandboxSession, "setNetworkPolicy">>,
token: string,
operation: () => Promise<T>,
): Promise<T> {
diff --git a/packages/eve/src/self-modification/sandbox.test.ts b/packages/eve/src/self-modification/sandbox.test.ts
index fe0364468..ebf9f8aa7 100644
--- a/packages/eve/src/self-modification/sandbox.test.ts
+++ b/packages/eve/src/self-modification/sandbox.test.ts
@@ -1,28 +1,52 @@
-import { describe, expect, it, vi } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
-import { defineSelfModificationSandbox, selectDeployedSelfModificationBackend } from "./sandbox.js";
+import type { SelfModificationConfig } from "./config.js";
+import {
+ defineSelfModificationSandbox,
+ selectDeployedSelfModificationEnvironment,
+} from "./sandbox.js";
-describe("retired self-modification sandbox scaffold", () => {
- it("returns an inert sandbox definition", () => {
- const definition = defineSelfModificationSandbox({
- config: { deployed: { authorize: vi.fn() } },
- });
- expect(definition.backend).toBeUndefined();
- expect(definition.onSession).toBeUndefined();
+const connectConfig: SelfModificationConfig = {
+ deployed: {
+ authorize: () => true,
+ credentials: { pat: true },
+ source: { git: { directory: ".", repository: "github.com/acme/agent" } },
+ target: { branch: "main" },
+ },
+};
+
+afterEach(() => vi.unstubAllEnvs());
+
+describe("self-modification sandbox", () => {
+ it("selects Vercel Sandbox on Vercel", () => {
+ expect(
+ selectDeployedSelfModificationEnvironment({
+ isDeployedOnVercel: () => true,
+ isMicrosandboxSupported: () => true,
+ }).provider,
+ ).toBe("vercel");
});
- it("does not select or provision a backend", () => {
- expect(() => selectDeployedSelfModificationBackend(undefined, {})).toThrow(
- "Deployed self-modification is disabled in the retired scaffold.",
- );
+ it("selects microsandbox on a supported self-hosted system", () => {
+ expect(
+ selectDeployedSelfModificationEnvironment({
+ isDeployedOnVercel: () => false,
+ isMicrosandboxSupported: () => true,
+ }).provider,
+ ).toBe("microsandbox");
});
- it("preserves explicitly typed options for compatibility", () => {
+ it("fails when no deployed provider is available", () => {
expect(() =>
- defineSelfModificationSandbox({
- backend: { name: "just-bash" } as never,
- config: {},
+ selectDeployedSelfModificationEnvironment({
+ isDeployedOnVercel: () => false,
+ isMicrosandboxSupported: () => false,
}),
- ).not.toThrow();
+ ).toThrow("No supported provider is available");
+ });
+
+ it("returns a callback definition", () => {
+ vi.stubEnv("VERCEL", "1");
+ expect(defineSelfModificationSandbox({ config: connectConfig })).toBeTypeOf("function");
});
});
diff --git a/packages/eve/src/self-modification/sandbox.ts b/packages/eve/src/self-modification/sandbox.ts
index 0f257c3c7..00f13d133 100644
--- a/packages/eve/src/self-modification/sandbox.ts
+++ b/packages/eve/src/self-modification/sandbox.ts
@@ -1,30 +1,100 @@
import {
defineSandbox,
- type SandboxBackend,
- type SandboxDefinition,
-} from "#public/sandbox/index.js";
-
-/** Options retained for source compatibility with the retired scaffold. */
+ type RuntimeSandboxSession,
+ type SandboxSelectorContext,
+} from "#public/definitions/sandbox.js";
+import { JustBashSandbox } from "#sandbox/providers/just-bash.js";
+import { MicrosandboxSandbox } from "#sandbox/providers/microsandbox.js";
+import { SANDBOX_PROVIDER_PROBES, type DefaultSandboxProbes } from "#sandbox/providers/default.js";
+import { VercelSandbox } from "#sandbox/providers/vercel.js";
+import { bindSandboxEnvironment } from "#shared/sandbox-environment.js";
+import { shellQuote } from "#shared/shell-quote.js";
+import { resolveSelfModificationConfig, type SelfModificationConfig } from "./config.js";
+import { createGitHubCredentialProvider } from "./credentials.js";
+import { createSelfModificationFilesystem } from "./filesystem.js";
+import { prepareSelfModificationWorkspace, REPOSITORY_PATH } from "./git-workspace.js";
+import { resolveSelfModificationMode } from "./mode.js";
+import { SELF_MODIFICATION_BASELINE_NETWORK_POLICY } from "./network-policy.js";
export interface SelfModificationSandboxOptions {
- readonly backend?: SandboxBackend;
- readonly config?: unknown;
+ readonly config?: SelfModificationConfig;
}
-/** @deprecated The scaffolded sandbox is inert; use the packaged extension. */
-export function selectDeployedSelfModificationBackend(
- configured: SandboxBackend | undefined,
- _probes: unknown,
-): SandboxBackend {
- if (configured !== undefined) return configured;
- throw new Error("Deployed self-modification is disabled in the retired scaffold.");
+export interface SelfModificationSandbox {
+ (context: SandboxSelectorContext): Promise<RuntimeSandboxSession> | RuntimeSandboxSession;
}
+type Probes = Pick<DefaultSandboxProbes, "isDeployedOnVercel" | "isMicrosandboxSupported">;
+type DeployedSelfModificationEnvironment =
+ | ReturnType<typeof MicrosandboxSandbox.environment>
+ | ReturnType<typeof VercelSandbox.environment>;
+
export function defineSelfModificationSandbox(
- _options: SelfModificationSandboxOptions = {},
-): SandboxDefinition {
- return defineSandbox({});
+ options: SelfModificationSandboxOptions = {},
+): SelfModificationSandbox {
+ const config = resolveSelfModificationConfig(options.config);
+ const mode = resolveSelfModificationMode(config);
+ if (mode !== "deployed") {
+ const environment =
+ mode === "local"
+ ? JustBashSandbox.environment({ filesystem: createSelfModificationFilesystem })
+ : JustBashSandbox.environment();
+ return bindSandboxEnvironment(
+ defineSandbox(() => environment.open()),
+ environment,
+ );
+ }
+
+ const environment = selectDeployedSelfModificationEnvironment(SANDBOX_PROVIDER_PROBES);
+ return bindSandboxEnvironment(
+ defineSandbox(async ({ session }) => {
+ const sandbox = await environment.open({
+ networkPolicy: SELF_MODIFICATION_BASELINE_NETWORK_POLICY,
+ });
+ if (config.deployed === undefined) return sandbox;
+ if (session.parent === undefined)
+ throw new Error("Production self-modification requires a child session.");
+ if (sandbox.setNetworkPolicy === undefined) {
+ throw new Error("Production self-modification requires mutable sandbox network policy.");
+ }
+ const capableSandbox = { ...sandbox, setNetworkPolicy: sandbox.setNetworkPolicy };
+ const deployed = config.deployed;
+ const token = await createGitHubCredentialProvider(deployed.credentials).resolve({
+ capability: "checkout",
+ repository: deployed.repository,
+ });
+ await prepareSelfModificationWorkspace({
+ directory: deployed.directory,
+ repository: deployed.repository,
+ sandbox: capableSandbox,
+ targetBranch: deployed.targetBranch,
+ token,
+ });
+ const root =
+ deployed.directory === "." ? REPOSITORY_PATH : `${REPOSITORY_PATH}/${deployed.directory}`;
+ const result = await sandbox.run({
+ command: `rm -rf /source && ln -s ${shellQuote(`${root}/agent`)} /source`,
+ });
+ if (result.exitCode !== 0)
+ throw new Error("Self-modification could not mount the agent source.");
+ return sandbox;
+ }),
+ environment,
+ );
+}
+
+export function selectDeployedSelfModificationEnvironment(
+ probes: Probes,
+): DeployedSelfModificationEnvironment {
+ if (probes.isDeployedOnVercel()) {
+ return VercelSandbox.environment();
+ }
+ if (probes.isMicrosandboxSupported()) {
+ return MicrosandboxSandbox.environment();
+ }
+ throw new Error(
+ "Deployed self-modification requires runtime credential transforms. No supported provider is available. Use Vercel Sandbox or microsandbox on a supported self-hosted system.",
+ );
}
-/** @deprecated The scaffolded sandbox is inert; use the packaged extension. */
export default defineSelfModificationSandbox();
diff --git a/packages/eve/src/shared/sandbox-backend.ts b/packages/eve/src/shared/sandbox-backend.ts
deleted file mode 100644
index 4c9110eb4..000000000
--- a/packages/eve/src/shared/sandbox-backend.ts
+++ /dev/null
@@ -1,186 +0,0 @@
-import type { SandboxBootstrapContext, SandboxSessionUseFn } from "#shared/sandbox-definition.js";
-import type { SandboxSession } from "#shared/sandbox-session.js";
-
-/**
- * Live sandbox handle returned by a {@link SandboxBackend}.
- *
- * Wraps the public {@link SandboxSession} with lifecycle methods so the
- * runtime orchestrator can persist reconnect metadata and release
- * resources.
- */
-export interface SandboxBackendHandle<SO = Record<string, never>> {
- readonly session: SandboxSession;
- readonly useSessionFn: SandboxSessionUseFn<SO>;
- captureState(): Promise<SandboxBackendSessionState>;
- /**
- * Permanently deletes this sandbox and its disposable backend state.
- * Reusable or shared template state must not be deleted.
- */
- delete(options?: SandboxDeleteOptions): Promise<void>;
- /**
- * Stops the underlying compute at an authored runtime boundary while
- * preserving any backend state needed to reopen the durable session.
- * Provider errors must reject this call.
- */
- stop(): Promise<void>;
- /**
- * Stops the underlying compute because the eve server is shutting
- * down; nothing may be left running afterwards. The session must
- * remain reattachable from persisted state on the next server start
- * when the backend supports durable sessions.
- */
- shutdown(): Promise<void>;
-}
-
-/** Options for permanently deleting one sandbox. */
-export interface SandboxDeleteOptions {
- readonly abortSignal?: AbortSignal;
-}
-
-/**
- * Serializable per-sandbox reconnect record stored on the harness session.
- *
- * `backendName` matches the {@link SandboxBackend.name} of the backend
- * that produced this state. The runtime reads it to decide whether a
- * previously persisted handle is still compatible with the current
- * backend.
- */
-export interface SandboxBackendSessionState {
- readonly backendName: string;
- readonly metadata: Record<string, unknown>;
- readonly sessionKey: string;
-}
-
-/**
- * One file written into a sandbox template before template state capture.
- */
-export interface SandboxSeedFile {
- readonly path: string;
- readonly content: string | Buffer;
-}
-
-/**
- * Diagnostic tags attached to provider-owned sandbox resources.
- *
- * Built-in backends may forward these into their hosting platform's
- * native tagging system. eve supplies stable tags such as the active
- * agent, channel, and session id so sandboxes can be found and
- * attributed in provider dashboards.
- */
-export type SandboxBackendTags = Readonly<Record<string, string>>;
-
-/**
- * Framework-owned runtime context handed to a backend on every
- * {@link SandboxBackend.create} call.
- *
- * Backends use this to derive any per-call state that depends on the
- * surrounding application. For example, the local backend computes its
- * cache directory from `appRoot`. Backends that don't need anything
- * here may ignore the field entirely.
- */
-export interface SandboxBackendRuntimeContext {
- readonly appRoot: string;
-}
-
-/**
- * Input passed to {@link SandboxBackend.create} when the runtime needs a
- * live sandbox session.
- */
-export interface SandboxBackendCreateInput {
- /**
- * Reusable template key to open this session from. `null` means eve
- * intentionally skipped template prewarm because the sandbox has no
- * `bootstrap()` and no seed files, so the backend should create a
- * fresh session from its default base runtime.
- */
- readonly templateKey: string | null;
- readonly sessionKey: string;
- readonly existingMetadata?: Record<string, unknown>;
- /**
- * Runtime tags the backend should attach to sandbox resources when
- * the underlying provider supports tags.
- */
- readonly tags?: SandboxBackendTags;
- readonly runtimeContext: SandboxBackendRuntimeContext;
-}
-
-/**
- * Input passed to {@link SandboxBackend.prewarm} when the build pipeline
- * is preparing reusable templates.
- *
- * Every authored sandbox in the compiled graph receives exactly one
- * `prewarm(...)` call before runtime opens its first session. The
- * backend captures reusable template state from the supplied
- * `bootstrap` hook and `seedFiles`, then `backend.create(...)` opens
- * durable sessions from that state.
- */
-export interface SandboxBackendPrewarmInput<BO = Record<string, never>> {
- readonly templateKey: string;
- readonly bootstrap?: (input: SandboxBootstrapContext<BO>) => void | Promise<void>;
- /**
- * Optional progress logger for backend-specific prewarm phases.
- */
- readonly log?: (message: string) => void;
- readonly runtimeContext: SandboxBackendRuntimeContext;
- readonly seedFiles: ReadonlyArray<SandboxSeedFile>;
-}
-
-/**
- * Outcome of one {@link SandboxBackend.prewarm} call.
- *
- * The build pipeline uses this to report in the build logs whether a
- * template state was reused from a prior deploy or captured fresh, so
- * a cache hit is distinguishable from an expensive rebuild.
- */
-export interface SandboxBackendPrewarmResult {
- /**
- * `true` when existing template state was reused without rebuilding it;
- * `false` when the backend captured fresh template state.
- */
- readonly reused: boolean;
-}
-
-/**
- * Pluggable sandbox backend.
- *
- * A `SandboxBackend` is a value an author attaches to a
- * {@link SandboxDefinition} to choose which underlying runtime hosts the
- * sandbox. eve ships built-in backends (`docker()`,
- * `justbash()`, `microsandbox()`,
- * `vercel()`, and the availability-aware
- * `defaultSandbox()`), but the interface is public so authors can write
- * their own.
- *
- * A backend implements the full two-phase lifecycle:
- * {@link SandboxBackend.prewarm} captures reusable template state at
- * build time, and {@link SandboxBackend.create} starts or reattaches a
- * live session from that template at runtime.
- */
-export interface SandboxBackend<BO = Record<string, never>, SO = Record<string, never>> {
- /**
- * Stable identifier for this backend implementation.
- *
- * Participates in cache-key derivation and the persisted reconnect
- * state, so two backends that should not share template state
- * must use distinct names. Built-in backends use `"vercel"` and
- * `"local"`. Custom backends pick a unique string.
- */
- readonly name: string;
- /**
- * Creates or reattaches one live sandbox session from a template
- * previously captured by {@link SandboxBackend.prewarm}. Throws
- * {@link SandboxTemplateNotProvisionedError} when the requested
- * template is missing.
- */
- create(input: SandboxBackendCreateInput): Promise<SandboxBackendHandle<SO>>;
- /**
- * Build-time prewarm hook. eve invokes this for every authored
- * sandbox in the compiled graph before serving traffic so the backend
- * can capture reusable template state. Idempotent against existing state
- * keyed by `templateKey`.
- *
- * Returns whether the state was reused from a prior run or captured
- * fresh so the build pipeline can surface that in its logs.
- */
- prewarm(input: SandboxBackendPrewarmInput<BO>): Promise<SandboxBackendPrewarmResult>;
-}
diff --git a/packages/eve/src/shared/sandbox-definition.ts b/packages/eve/src/shared/sandbox-definition.ts
deleted file mode 100644
index 1351fba34..000000000
--- a/packages/eve/src/shared/sandbox-definition.ts
+++ /dev/null
@@ -1,132 +0,0 @@
-import type { SandboxSession } from "#shared/sandbox-session.js";
-import type { SandboxBackend } from "#shared/sandbox-backend.js";
-import type { SessionContext } from "#context/session-context.js";
-
-/**
- * Opens the template session inside a `bootstrap` hook. Optional `options`
- * (typed by the backend's bootstrap-use options `BO`) are applied to the
- * template before the snapshot is captured. Resolves to the
- * {@link SandboxSession} to operate on.
- */
-export type SandboxBootstrapUseFn<O = Record<string, never>> = (
- options?: O,
-) => Promise<SandboxSession>;
-
-/**
- * Opens the live sandbox session inside an `onSession` hook. Optional
- * `options` (typed by the backend's session-use options `SO`) are applied
- * to the live session. Resolves to the {@link SandboxSession} for the
- * current turn.
- */
-export type SandboxSessionUseFn<O = Record<string, never>> = (
- options?: O,
-) => Promise<SandboxSession>;
-
-/**
- * Argument passed to a sandbox `bootstrap` hook. `use(options?)` opens the
- * template session that the snapshot is captured from; backend-specific
- * `options` (typed by the backend's bootstrap-use options `BO`) are applied
- * to that template.
- */
-export interface SandboxBootstrapContext<O = Record<string, never>> {
- readonly use: SandboxBootstrapUseFn<O>;
-}
-
-/**
- * Argument passed to a sandbox `onSession` hook, invoked once per live
- * session. `ctx` contains the active session metadata; sandbox access during
- * initialization goes through `use(options?)`, which opens the live session
- * and applies backend-specific `options` (typed by the backend's session-use
- * options `SO`).
- */
-export interface SandboxSessionContext<O = Record<string, never>> {
- readonly ctx: Pick<SessionContext, "session">;
- readonly use: SandboxSessionUseFn<O>;
-}
-
-/**
- * Resolves a build-time revalidation key for a bootstrap snapshot. eve
- * evaluates it during compile/build and freezes the result into compiled
- * artifacts. Supply one only for external inputs that affect bootstrap
- * output; authored source and managed seeds are tracked automatically.
- */
-export type SandboxRevalidationKeyFn = () => Promise<string> | string;
-
-/**
- * Public sandbox definition authored in `agent/sandbox.ts` (shorthand)
- * or `agent/sandbox/sandbox.ts` (folder layout, when paired with an
- * authored `sandbox/workspace/` subtree).
- *
- * Each agent (and each subagent) owns exactly one sandbox. When the
- * module file is absent the framework auto-provides a default sandbox
- * via `defaultSandbox()`. Authors override lifecycle and backend by
- * creating `agent/sandbox.ts` (or `agent/sandbox/sandbox.ts` when they
- * also want a workspace folder); subagents override independently via
- * `subagents/<name>/sandbox.ts` (or the folder form) and do not inherit
- * their parent's sandbox (skill seeds differ per agent).
- */
-interface SandboxDefinitionBase<BO = Record<string, never>, SO = Record<string, never>> {
- /**
- * Backend that runs this sandbox.
- *
- * Accepts either a {@link SandboxBackend} value or a zero-arg factory
- * function that returns one. The factory form is invoked lazily on
- * first framework access and the result is memoized for the lifetime
- * of the process, so backend-internal state (such as the Vercel
- * backend's prewarmed-template cache) is preserved across every call.
- * Use the factory form to defer evaluation, for example when create
- * options depend on environment variables that aren't set at module
- * load time:
- *
- * ```ts
- * defineSandbox({
- * backend: () => vercel({ env: { TOKEN: process.env.TOKEN ?? "" } }),
- * });
- * ```
- *
- * When this field is omitted, eve substitutes `defaultSandbox()` at
- * runtime, which picks the best available backend: `vercel()`
- * on hosted Vercel (where `process.env.VERCEL` is set), then Docker,
- * microsandbox, or just-bash
- * everywhere else. Set `backend` explicitly to pin the sandbox to a
- * specific backend regardless of environment.
- */
- readonly backend: SandboxBackend<BO, SO> | (() => SandboxBackend<BO, SO>);
- /** Human-readable description of this sandbox, surfaced in tooling. */
- readonly description?: string;
- /**
- * Runs once per live session before authored steps use the sandbox.
- * Call `input.use(options?)` to open the session and apply per-session
- * backend options (typed by `SO`).
- */
- onSession?(input: SandboxSessionContext<SO>): Promise<void> | void;
-}
-
-export interface SandboxDefinitionWithBootstrap<
- BO = Record<string, never>,
- SO = Record<string, never>,
-> extends SandboxDefinitionBase<BO, SO> {
- bootstrap(input: SandboxBootstrapContext<BO>): Promise<void> | void;
- /**
- * Optional build-time revalidation key for the reusable sandbox
- * snapshot produced by {@link bootstrap}. eve evaluates this
- * function during compile/build, stores the resolved string in
- * compiled artifacts, and uses that frozen value for both prewarm and
- * runtime session create. Authored sandbox source and
- * framework-managed seed contents are included automatically; provide
- * this key only for external inputs that affect bootstrap output.
- */
- readonly revalidationKey?: SandboxRevalidationKeyFn;
-}
-
-export interface SandboxDefinitionWithoutBootstrap<
- BO = Record<string, never>,
- SO = Record<string, never>,
-> extends SandboxDefinitionBase<BO, SO> {
- bootstrap?: undefined;
- readonly revalidationKey?: never;
-}
-
-export type SandboxDefinition<BO = Record<string, never>, SO = Record<string, never>> =
- | SandboxDefinitionWithBootstrap<BO, SO>
- | SandboxDefinitionWithoutBootstrap<BO, SO>;
diff --git a/packages/eve/src/shared/sandbox-environment.ts b/packages/eve/src/shared/sandbox-environment.ts
new file mode 100644
index 000000000..d568d6c36
--- /dev/null
+++ b/packages/eve/src/shared/sandbox-environment.ts
@@ -0,0 +1,182 @@
+import { createHash } from "node:crypto";
+
+import { ContextContainer, contextStorage, type AlsContext } from "#context/container.js";
+import type { SessionAuth, SessionParent, SessionTurn } from "#context/keys.js";
+import type { SandboxProviderRuntime } from "#shared/sandbox-provider.js";
+import type {
+ RuntimeSandboxSession,
+ RuntimeSandboxSessionFor,
+ SandboxSession,
+} from "#shared/sandbox-session.js";
+
+const ENVIRONMENT = Symbol.for("eve.sandbox-environment");
+const PROVIDER_RUNTIME = Symbol.for("eve.sandbox-provider-runtime");
+const CONFIGURATION_HASH = Symbol.for("eve.sandbox-environment-configuration-hash");
+const SELECTOR_ENVIRONMENT = Symbol.for("eve.sandbox-selector-environment");
+
+export interface SandboxSelectorContext {
+ readonly session: {
+ readonly auth: SessionAuth;
+ readonly id: string;
+ readonly parent?: SessionParent;
+ readonly turn: SessionTurn;
+ };
+}
+
+export type SandboxSelector = (
+ context: SandboxSelectorContext,
+) => Promise<RuntimeSandboxSession> | RuntimeSandboxSession;
+
+export type SandboxOpenArguments<Options> = Options extends undefined
+ ? []
+ : Record<never, never> extends Options
+ ? [options?: Options]
+ : [options: Options];
+
+export interface SandboxEnvironmentIdentity {
+ readonly [CONFIGURATION_HASH]: string;
+ readonly [ENVIRONMENT]: true;
+ readonly [PROVIDER_RUNTIME]: SandboxProviderRuntime;
+ readonly provider: string;
+}
+
+export interface SandboxEnvironment<
+ Options extends object | undefined = object,
+ Session extends SandboxSession = SandboxSession,
+> extends SandboxEnvironmentIdentity {
+ open(...args: SandboxOpenArguments<Options>): Promise<RuntimeSandboxSessionFor<Session>>;
+}
+
+interface ConstructorRuntime {
+ open(input: {
+ readonly configurationHash: string;
+ readonly environment: object;
+ readonly environmentConfigurationHash: string;
+ readonly options: object | undefined;
+ readonly provider: SandboxProviderRuntime;
+ }): Promise<RuntimeSandboxSession>;
+}
+
+const RUNTIMES = Symbol.for("eve.sandbox-constructor-runtimes");
+const globals = globalThis as typeof globalThis & {
+ [RUNTIMES]?: WeakMap<AlsContext, ConstructorRuntime>;
+};
+const runtimes = (globals[RUNTIMES] ??= new WeakMap<AlsContext, ConstructorRuntime>());
+
+export function createSandboxEnvironment<
+ Options extends object | undefined = object,
+ Session extends SandboxSession = SandboxSession,
+>(input: {
+ readonly configuration?: unknown;
+ readonly runtime: SandboxProviderRuntime;
+}): SandboxEnvironment<Options, Session> {
+ let environment: SandboxEnvironment<Options, Session>;
+
+ environment = {
+ [CONFIGURATION_HASH]: hashConstructorOptions({ environment: input.configuration, sandbox: {} }),
+ [ENVIRONMENT]: true,
+ [PROVIDER_RUNTIME]: input.runtime,
+ provider: input.runtime.providerName,
+ async open(...args: SandboxOpenArguments<Options>) {
+ const options = args[0] as object | undefined;
+ const context = contextStorage.getStore();
+ const runtime = context === undefined ? undefined : runtimes.get(context);
+ if (runtime === undefined) {
+ throw new Error("Sandbox environments can only open sandboxes inside defineSandbox().");
+ }
+ return (await runtime.open({
+ configurationHash: hashConstructorOptions({
+ environment: input.configuration,
+ sandbox: options,
+ }),
+ environment,
+ environmentConfigurationHash: environment[CONFIGURATION_HASH],
+ options,
+ provider: input.runtime,
+ })) as RuntimeSandboxSessionFor<Session>;
+ },
+ };
+ return environment;
+}
+
+function hashConstructorOptions(options: unknown): string {
+ return createHash("sha256").update(stableSerialize(options)).digest("hex");
+}
+
+function stableSerialize(value: unknown, seen = new WeakSet<object>()): string {
+ if (
+ value === null ||
+ typeof value === "boolean" ||
+ typeof value === "number" ||
+ typeof value === "string"
+ ) {
+ return JSON.stringify(value);
+ }
+ if (typeof value === "function") return `function:${value.toString()}`;
+ if (Array.isArray(value))
+ return `[${value.map((entry) => stableSerialize(entry, seen)).join(",")}]`;
+ if (typeof value === "object") {
+ if (seen.has(value)) return "[circular]";
+ seen.add(value);
+ const constructorName = value.constructor?.name ?? "Object";
+ const serialized = `{${Object.entries(value)
+ .sort(([left], [right]) => left.localeCompare(right))
+ .map(([key, entry]) => `${JSON.stringify(key)}:${stableSerialize(entry, seen)}`)
+ .join(",")}}`;
+ seen.delete(value);
+ return `${constructorName}:${serialized}`;
+ }
+ return typeof value;
+}
+
+export function getSandboxEnvironmentConfigurationHash(
+ environment: SandboxEnvironmentIdentity,
+): string {
+ return environment[CONFIGURATION_HASH];
+}
+
+export function getSandboxEnvironmentRuntime(
+ environment: SandboxEnvironmentIdentity,
+): SandboxProviderRuntime {
+ return environment[PROVIDER_RUNTIME];
+}
+
+export function bindSandboxEnvironment(
+ selector: SandboxSelector,
+ environment: SandboxEnvironmentIdentity,
+): SandboxSelector {
+ Object.defineProperty(selector, SELECTOR_ENVIRONMENT, { value: environment });
+ return selector;
+}
+
+export function getBoundSandboxEnvironment(value: unknown): SandboxEnvironmentIdentity | undefined {
+ const environment =
+ typeof value === "function" ? Reflect.get(value, SELECTOR_ENVIRONMENT) : undefined;
+ return isSandboxEnvironment(environment) ? environment : undefined;
+}
+
+export function isSandboxEnvironment(value: unknown): value is SandboxEnvironmentIdentity {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ Reflect.get(value, ENVIRONMENT) === true &&
+ typeof Reflect.get(value, "provider") === "string" &&
+ typeof Reflect.get(value, "open") === "function"
+ );
+}
+
+export async function runWithSandboxConstructorRuntime<T>(
+ runtime: ConstructorRuntime,
+ callback: () => Promise<T> | T,
+): Promise<T> {
+ const existing = contextStorage.getStore();
+ const context = existing ?? new ContextContainer();
+ const previous = runtimes.get(context);
+ runtimes.set(context, runtime);
+ try {
+ return existing === undefined ? await contextStorage.run(context, callback) : await callback();
+ } finally {
+ if (previous === undefined) runtimes.delete(context);
+ else runtimes.set(context, previous);
+ }
+}
diff --git a/packages/eve/src/shared/sandbox-network-policy.test.ts b/packages/eve/src/shared/sandbox-network-policy.test.ts
new file mode 100644
index 000000000..340f7cfd4
--- /dev/null
+++ b/packages/eve/src/shared/sandbox-network-policy.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from "vitest";
+
+import { isSandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";
+
+describe("isSandboxNetworkPolicy", () => {
+ it.each(["allow-all", "deny-all"])("accepts %s", (policy) => {
+ expect(isSandboxNetworkPolicy(policy)).toBe(true);
+ });
+
+ it("accepts domain, subnet, matcher, transform, and forwarding rules", () => {
+ expect(
+ isSandboxNetworkPolicy({
+ allow: {
+ "api.example.com": [
+ {
+ match: {
+ headers: [{ key: { exact: "authorization" } }],
+ method: ["POST"],
+ path: { startsWith: "/v1/" },
+ },
+ transform: [{ headers: { authorization: "Bearer secret" } }],
+ },
+ ],
+ "proxy.example.com": [{ forwardURL: "https://proxy.example.com" }],
+ },
+ subnets: { allow: ["10.0.0.0/8"], deny: ["10.1.0.0/16"] },
+ }),
+ ).toBe(true);
+ });
+
+ it.each([
+ undefined,
+ null,
+ "invalid",
+ { allow: [1] },
+ { allow: { "api.example.com": [{}] } },
+ { allow: { "api.example.com": [{ forwardURL: 1 }] } },
+ { allow: { "api.example.com": [{ forwardURL: "https://proxy", transform: [] }] } },
+ { allow: { "api.example.com": [{ match: { path: {} }, transform: [] }] } },
+ { allow: { "api.example.com": [{ transform: [{ headers: { authorization: 1 } }] }] } },
+ { extra: true },
+ { subnets: { allow: [1] } },
+ ])("rejects malformed policy %#", (policy) => {
+ expect(isSandboxNetworkPolicy(policy)).toBe(false);
+ });
+});
diff --git a/packages/eve/src/shared/sandbox-network-policy.ts b/packages/eve/src/shared/sandbox-network-policy.ts
index 71a01f1ba..340d2ef99 100644
--- a/packages/eve/src/shared/sandbox-network-policy.ts
+++ b/packages/eve/src/shared/sandbox-network-policy.ts
@@ -3,7 +3,7 @@ import type * as Vercel from "#compiled/@vercel/sandbox/index.js";
/**
* Firewall network policy applied to a live sandbox session.
*
- * eve-owned alias of the backend network-policy shape. Use it to restrict
+ * 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:
@@ -18,9 +18,106 @@ import type * as Vercel from "#compiled/@vercel/sandbox/index.js";
* });
* ```
*
- * The Docker backend honors only the coarse `"allow-all"` and
- * `"deny-all"` policies; the just-bash backend rejects `setNetworkPolicy`
+ * The Docker provider honors only the coarse `"allow-all"` and
+ * `"deny-all"` policies; the just-bash provider rejects `setNetworkPolicy`
* entirely (its network policy is fixed at sandbox creation and it runs
* no binaries to govern).
*/
export type SandboxNetworkPolicy = Vercel.NetworkPolicy;
+
+/** Initial network configuration shared by network-capable sandbox providers. */
+export interface SandboxNetworkOptions {
+ readonly networkPolicy?: SandboxNetworkPolicy;
+}
+
+export function isSandboxNetworkPolicy(value: unknown): value is SandboxNetworkPolicy {
+ if (value === "allow-all" || value === "deny-all") return true;
+ if (!isRecord(value) || !hasOnlyKeys(value, ["allow", "subnets"])) return false;
+ if (value.allow !== undefined && !isNetworkAllowList(value.allow)) return false;
+ return value.subnets === undefined || isSubnetPolicy(value.subnets);
+}
+
+function isNetworkAllowList(value: unknown): boolean {
+ if (isStringArray(value)) return true;
+ if (!isRecord(value)) return false;
+ return Object.values(value).every(
+ (rules) => Array.isArray(rules) && rules.every(isNetworkPolicyRule),
+ );
+}
+
+function isNetworkPolicyRule(value: unknown): boolean {
+ if (!isRecord(value) || !hasOnlyKeys(value, ["forwardURL", "match", "transform"])) return false;
+ if (value.match !== undefined && !isNetworkPolicyMatch(value.match)) return false;
+ const hasTransform = value.transform !== undefined;
+ const hasForwardUrl = value.forwardURL !== undefined;
+ if (hasTransform === hasForwardUrl) return false;
+ if (hasForwardUrl) return typeof value.forwardURL === "string";
+ return (
+ Array.isArray(value.transform) &&
+ value.transform.every(
+ (transform) =>
+ isRecord(transform) &&
+ hasOnlyKeys(transform, ["headers"]) &&
+ (transform.headers === undefined || isStringRecord(transform.headers)),
+ )
+ );
+}
+
+function isNetworkPolicyMatch(value: unknown): boolean {
+ if (!isRecord(value) || !hasOnlyKeys(value, ["headers", "method", "path", "queryString"])) {
+ return false;
+ }
+ return (
+ (value.path === undefined || isNetworkPolicyMatcher(value.path)) &&
+ (value.method === undefined || isStringArray(value.method)) &&
+ (value.queryString === undefined || isKeyValueMatcherArray(value.queryString)) &&
+ (value.headers === undefined || isKeyValueMatcherArray(value.headers))
+ );
+}
+
+function isKeyValueMatcherArray(value: unknown): boolean {
+ return (
+ Array.isArray(value) &&
+ value.every(
+ (matcher) =>
+ isRecord(matcher) &&
+ hasOnlyKeys(matcher, ["key", "value"]) &&
+ (matcher.key === undefined || isNetworkPolicyMatcher(matcher.key)) &&
+ (matcher.value === undefined || isNetworkPolicyMatcher(matcher.value)),
+ )
+ );
+}
+
+function isNetworkPolicyMatcher(value: unknown): boolean {
+ if (!isRecord(value) || !hasOnlyKeys(value, ["exact", "regex", "startsWith"])) return false;
+ const matchers = [value.exact, value.startsWith, value.regex];
+ return (
+ matchers.filter((matcher) => matcher !== undefined).length === 1 &&
+ matchers.every((matcher) => matcher === undefined || typeof matcher === "string")
+ );
+}
+
+function isSubnetPolicy(value: unknown): boolean {
+ return (
+ isRecord(value) &&
+ hasOnlyKeys(value, ["allow", "deny"]) &&
+ (value.allow === undefined || isStringArray(value.allow)) &&
+ (value.deny === undefined || isStringArray(value.deny))
+ );
+}
+
+function isStringArray(value: unknown): value is string[] {
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string");
+}
+
+function isStringRecord(value: unknown): value is Record<string, string> {
+ return isRecord(value) && Object.values(value).every((entry) => typeof entry === "string");
+}
+
+function hasOnlyKeys(value: Readonly<Record<string, unknown>>, keys: readonly string[]): boolean {
+ return Object.keys(value).every((key) => keys.includes(key));
+}
+
+function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
+ return value !== null && typeof value === "object" && !Array.isArray(value);
+}
diff --git a/packages/eve/src/shared/sandbox-prepared-artifacts.ts b/packages/eve/src/shared/sandbox-prepared-artifacts.ts
new file mode 100644
index 000000000..766311b03
--- /dev/null
+++ b/packages/eve/src/shared/sandbox-prepared-artifacts.ts
@@ -0,0 +1,54 @@
+import { z } from "#compiled/zod/index.js";
+import type { SandboxPreparedArtifact } from "#shared/sandbox-provider.js";
+
+export const SANDBOX_PREPARED_ARTIFACTS_KIND = "eve-sandbox-prepared-artifacts";
+export const SANDBOX_PREPARED_ARTIFACTS_VERSION = 2;
+
+export interface SandboxPreparedArtifactEntry {
+ readonly artifact: SandboxPreparedArtifact;
+ readonly nodeId: string;
+ readonly providerName: string;
+}
+
+export interface SandboxPreparedArtifactsManifest {
+ readonly entries: readonly SandboxPreparedArtifactEntry[];
+ readonly kind: typeof SANDBOX_PREPARED_ARTIFACTS_KIND;
+ readonly version: typeof SANDBOX_PREPARED_ARTIFACTS_VERSION;
+}
+
+const sandboxPreparedArtifactSchema: z.ZodType<SandboxPreparedArtifact> = z.lazy(() =>
+ z.union([
+ z.null(),
+ z.boolean(),
+ z.number(),
+ z.string(),
+ z.array(sandboxPreparedArtifactSchema),
+ z.record(z.string(), sandboxPreparedArtifactSchema),
+ ]),
+);
+
+export const sandboxPreparedArtifactsManifestSchema: z.ZodType<SandboxPreparedArtifactsManifest> = z
+ .object({
+ entries: z.array(
+ z
+ .object({
+ artifact: sandboxPreparedArtifactSchema,
+ nodeId: z.string().min(1),
+ providerName: z.string().min(1),
+ })
+ .strict(),
+ ),
+ kind: z.literal(SANDBOX_PREPARED_ARTIFACTS_KIND),
+ version: z.literal(SANDBOX_PREPARED_ARTIFACTS_VERSION),
+ })
+ .strict();
+
+export function createSandboxPreparedArtifactsManifest(
+ entries: readonly SandboxPreparedArtifactEntry[],
+): SandboxPreparedArtifactsManifest {
+ return {
+ entries: [...entries].sort((left, right) => left.nodeId.localeCompare(right.nodeId)),
+ kind: SANDBOX_PREPARED_ARTIFACTS_KIND,
+ version: SANDBOX_PREPARED_ARTIFACTS_VERSION,
+ };
+}
diff --git a/packages/eve/src/shared/sandbox-provider.test.ts b/packages/eve/src/shared/sandbox-provider.test.ts
new file mode 100644
index 000000000..b9c1648d4
--- /dev/null
+++ b/packages/eve/src/shared/sandbox-provider.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, expectTypeOf, it, vi } from "vitest";
+
+import { getSandboxEnvironmentRuntime } from "#shared/sandbox-environment.js";
+import { defineSandboxProvider } from "#shared/sandbox-provider.js";
+
+const provider = defineSandboxProvider<
+ { readonly image?: string },
+ { readonly networkPolicy?: "allow-all" | "deny-all" },
+ { readonly templateId: string },
+ { readonly nativeId: string; readonly version: 1 }
+>({
+ name: "test-provider",
+ stateProtocolVersion: 4,
+ environment: (environmentOptions) => ({
+ async prepare() {
+ return { templateId: environmentOptions?.image ?? "default" };
+ },
+ async resume(_context, _artifact, state) {
+ return handle(state.nativeId);
+ },
+ async start(context) {
+ const nativeId = `native-${context.session.id}`;
+ return { handle: handle(nativeId), state: { nativeId, version: 1 } };
+ },
+ }),
+});
+
+function handle(nativeId: string) {
+ return {
+ sandbox: {
+ resolvePath: (path: string) => path,
+ run: vi.fn(),
+ spawn: vi.fn(),
+ readFile: vi.fn(),
+ readBinaryFile: vi.fn(),
+ readTextFile: vi.fn(),
+ writeFile: vi.fn(),
+ writeBinaryFile: vi.fn(),
+ writeTextFile: vi.fn(),
+ removePath: vi.fn(),
+ },
+ onRuntimeShutdown: vi.fn(async () => {}),
+ onSessionDelete: vi.fn(async () => {}),
+ onSessionStop: vi.fn(async () => {}),
+ nativeId,
+ };
+}
+
+describe("defineSandboxProvider", () => {
+ it("preserves provider-owned environment and open option types", () => {
+ const environment = provider.environment({ image: "node:24" });
+ expect(environment.provider).toBe("test-provider");
+ expect(getSandboxEnvironmentRuntime(environment).stateProtocolVersion).toBe(4);
+ expectTypeOf(environment.open).parameter(0).toEqualTypeOf<
+ | {
+ readonly networkPolicy?: "allow-all" | "deny-all";
+ }
+ | undefined
+ >();
+ });
+
+ it("stores one direct implementation without extracting provider options", async () => {
+ const environment = provider.environment({ image: "node:24" });
+ const implementation = getSandboxEnvironmentRuntime(environment).implementation;
+ const artifact = await implementation.prepare({
+ files: { list: async () => [], read: async () => new Uint8Array(), readText: async () => "" },
+ host: {
+ loadOptionalPackage: async ({ importModule }) => await importModule(),
+ resolveProjectPath: (path) => path,
+ },
+ resources: { source: { kind: "none" } },
+ sourceRevision: "test-source-revision",
+ storagePath: "/tmp/test",
+ });
+ expect(artifact).toEqual({ templateId: "node:24" });
+ });
+});
diff --git a/packages/eve/src/shared/sandbox-provider.ts b/packages/eve/src/shared/sandbox-provider.ts
new file mode 100644
index 000000000..d52187566
--- /dev/null
+++ b/packages/eve/src/shared/sandbox-provider.ts
@@ -0,0 +1,285 @@
+import {
+ createSandboxEnvironment,
+ type SandboxEnvironment,
+ type SandboxSelectorContext,
+} from "#shared/sandbox-environment.js";
+import type { SandboxSession } from "#shared/sandbox-session.js";
+
+export interface SandboxDeleteOptions {
+ readonly abortSignal?: AbortSignal;
+}
+
+export interface SandboxProviderResourceFile {
+ readonly content: string | Uint8Array;
+ readonly relativePath: string;
+}
+
+export interface SandboxProviderResourceTree {
+ readonly files: readonly SandboxProviderResourceFile[];
+ readonly key: string;
+ readonly mountPath: string;
+ readonly targetPath: string;
+}
+
+export type SandboxProviderResourceSource =
+ | { readonly kind: "none" }
+ | { readonly key: string; readonly kind: "inline" }
+ | { readonly key: string; readonly kind: "materialized"; readonly path: string };
+
+export interface SandboxProviderResources {
+ readonly skills?: SandboxProviderResourceTree;
+ readonly source: SandboxProviderResourceSource;
+ readonly workspace?: SandboxProviderResourceTree;
+}
+
+export function sandboxProviderResourceIdentity(resources: SandboxProviderResources): object {
+ return {
+ skills: resources.skills?.key,
+ workspace: resources.workspace?.key,
+ };
+}
+
+export interface SandboxProviderTargetFile {
+ readonly content: string | Uint8Array;
+ readonly path: string;
+}
+
+export function providerResourceTargetFiles(
+ resources: SandboxProviderResources,
+): SandboxProviderTargetFile[] {
+ return [resources.workspace, resources.skills].flatMap((resource) =>
+ resource === undefined
+ ? []
+ : resource.files.map((file) => ({
+ content: file.content,
+ path: `${resource.targetPath}/${file.relativePath}`,
+ })),
+ );
+}
+
+export type SandboxPreparedArtifact =
+ | null
+ | boolean
+ | number
+ | string
+ | readonly SandboxPreparedArtifact[]
+ | { readonly [key: string]: SandboxPreparedArtifact };
+
+export function isSandboxPreparedArtifact(value: unknown): value is SandboxPreparedArtifact {
+ if (
+ value === null ||
+ typeof value === "boolean" ||
+ typeof value === "number" ||
+ typeof value === "string"
+ ) {
+ return true;
+ }
+ if (Array.isArray(value)) return value.every(isSandboxPreparedArtifact);
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ Object.values(value).every(isSandboxPreparedArtifact)
+ );
+}
+
+export function isSandboxPreparedArtifactRecord(
+ artifact: unknown,
+): artifact is { readonly [key: string]: SandboxPreparedArtifact } {
+ return typeof artifact === "object" && artifact !== null && !Array.isArray(artifact);
+}
+
+export interface SandboxProviderFiles {
+ list(): Promise<readonly string[]>;
+ read(path: string): Promise<Uint8Array>;
+ readText(path: string): Promise<string>;
+}
+
+export interface SandboxProviderHost {
+ loadOptionalPackage<T>(input: {
+ readonly autoInstall: boolean;
+ readonly importModule: () => Promise<T>;
+ readonly missingMessage: string;
+ readonly packageName: string;
+ }): Promise<T>;
+ resolveProjectPath(path: string): string;
+}
+
+export interface SandboxProviderPrepareContext {
+ readonly files: SandboxProviderFiles;
+ readonly host: SandboxProviderHost;
+ readonly log?: (message: string) => void;
+ readonly resources: SandboxProviderResources;
+ readonly sourceRevision: string;
+ readonly storagePath: string;
+}
+
+export interface SandboxProviderSessionContext {
+ readonly host: SandboxProviderHost;
+ readonly session: SandboxSelectorContext["session"];
+ readonly storagePath: string;
+}
+
+export interface SandboxProviderHandle<Session extends SandboxSession = SandboxSession> {
+ readonly sandbox: Session;
+ onRuntimeShutdown(): Promise<void>;
+ onSessionDelete(options?: SandboxDeleteOptions): Promise<void>;
+ onSessionStop(): Promise<void>;
+}
+
+export interface SandboxProviderImplementation<
+ OpenOptions extends object | undefined,
+ PreparedArtifact extends SandboxPreparedArtifact,
+ SessionState,
+ Session extends SandboxSession = SandboxSession,
+> {
+ prepare(context: SandboxProviderPrepareContext): Promise<PreparedArtifact>;
+ resume(
+ context: SandboxProviderSessionContext,
+ artifact: Readonly<PreparedArtifact>,
+ state: Readonly<SessionState>,
+ ): Promise<SandboxProviderHandle<Session>>;
+ start(
+ context: SandboxProviderSessionContext,
+ options: Readonly<OpenOptions> | undefined,
+ artifact: Readonly<PreparedArtifact>,
+ ): Promise<{ readonly handle: SandboxProviderHandle<Session>; readonly state: SessionState }>;
+}
+
+type SandboxOptionArguments<Options extends object | undefined> = Options extends undefined
+ ? [options?: undefined]
+ : Record<never, never> extends Options
+ ? [options?: Readonly<Options>]
+ : [options: Readonly<Options>];
+
+export type SandboxProviderDefinition<
+ EnvironmentOptions extends object | undefined,
+ OpenOptions extends object | undefined,
+ PreparedArtifact extends SandboxPreparedArtifact,
+ SessionState,
+ Session extends SandboxSession,
+> = {
+ readonly name: string;
+ readonly stateProtocolVersion?: number;
+ environment(
+ ...args: SandboxOptionArguments<EnvironmentOptions>
+ ): SandboxProviderImplementation<OpenOptions, PreparedArtifact, SessionState, Session>;
+};
+
+export interface SandboxProvider<
+ EnvironmentOptions extends object | undefined,
+ OpenOptions extends object | undefined,
+ Session extends SandboxSession,
+> {
+ readonly name: string;
+ environment(
+ ...args: SandboxOptionArguments<EnvironmentOptions>
+ ): SandboxEnvironment<OpenOptions, Session>;
+}
+
+type ErasedSandboxProviderImplementation = SandboxProviderImplementation<
+ object | undefined,
+ SandboxPreparedArtifact,
+ SandboxPreparedArtifact,
+ SandboxSession
+>;
+
+export interface SandboxProviderRuntime {
+ readonly implementation: ErasedSandboxProviderImplementation;
+ readonly providerName: string;
+ readonly stateProtocolVersion: number;
+}
+
+export function defineSandboxProvider<
+ EnvironmentOptions extends object | undefined = undefined,
+ OpenOptions extends object | undefined = undefined,
+ PreparedArtifact extends SandboxPreparedArtifact = SandboxPreparedArtifact,
+ SessionState = SandboxPreparedArtifact,
+ Session extends SandboxSession = SandboxSession,
+>(
+ definition: SandboxProviderDefinition<
+ EnvironmentOptions,
+ OpenOptions,
+ PreparedArtifact,
+ SessionState,
+ Session
+ >,
+): SandboxProvider<EnvironmentOptions, OpenOptions, Session> {
+ const stateProtocolVersion = definition.stateProtocolVersion ?? 1;
+ return {
+ name: definition.name,
+ environment(...args: SandboxOptionArguments<EnvironmentOptions>) {
+ return createSandboxEnvironment<OpenOptions, Session>({
+ configuration: args[0],
+ runtime: {
+ implementation: eraseSandboxProviderImplementation(definition.environment(...args)),
+ providerName: definition.name,
+ stateProtocolVersion,
+ },
+ });
+ },
+ };
+}
+
+function eraseSandboxProviderImplementation<
+ Options extends object | undefined,
+ Artifact extends SandboxPreparedArtifact,
+ SessionState,
+ Session extends SandboxSession,
+>(
+ implementation: SandboxProviderImplementation<Options, Artifact, SessionState, Session>,
+): ErasedSandboxProviderImplementation {
+ return implementation as ErasedSandboxProviderImplementation;
+}
+
+export function createSandboxProviderResources(input: {
+ readonly resourcesKey?: string;
+ readonly resourcesPath?: string;
+ readonly seedFiles?: readonly {
+ readonly content: string | Uint8Array;
+ readonly path: string;
+ }[];
+}): SandboxProviderResources {
+ if (input.resourcesKey === undefined) return { source: { kind: "none" } };
+ const files = input.seedFiles ?? [];
+ const source: SandboxProviderResourceSource =
+ input.resourcesPath !== undefined
+ ? { key: input.resourcesKey, kind: "materialized", path: input.resourcesPath }
+ : { key: input.resourcesKey, kind: "inline" };
+ return {
+ skills: createResourceTree({
+ files: files.filter((file) => file.path.startsWith("$HOME/.agents/skills/")),
+ key: `${input.resourcesKey}:skills`,
+ mountPath: "/eve/resources/skills",
+ prefix: "$HOME/.agents/skills/",
+ targetPath: "$HOME/.agents/skills",
+ }),
+ source,
+ workspace: createResourceTree({
+ files: files.filter((file) => !file.path.startsWith("$HOME/.agents/skills/")),
+ key: `${input.resourcesKey}:workspace`,
+ mountPath: "/eve/resources/workspace",
+ prefix: "/workspace/",
+ targetPath: "/workspace",
+ }),
+ };
+}
+
+function createResourceTree(input: {
+ readonly files: readonly { readonly content: string | Uint8Array; readonly path: string }[];
+ readonly key: string;
+ readonly mountPath: string;
+ readonly prefix: string;
+ readonly targetPath: string;
+}): SandboxProviderResourceTree {
+ return {
+ files: input.files.map((file) => ({
+ content: file.content,
+ relativePath: file.path.startsWith(input.prefix)
+ ? file.path.slice(input.prefix.length)
+ : file.path,
+ })),
+ key: input.key,
+ mountPath: input.mountPath,
+ targetPath: input.targetPath,
+ };
+}
diff --git a/packages/eve/src/shared/sandbox-session.ts b/packages/eve/src/shared/sandbox-session.ts
index 855d30cc6..3c84edd80 100644
--- a/packages/eve/src/shared/sandbox-session.ts
+++ b/packages/eve/src/shared/sandbox-session.ts
@@ -1,6 +1,6 @@
import type { Experimental_SandboxSession as AiSdkSandbox } from "ai";
-import type { SandboxDeleteOptions } from "#shared/sandbox-backend.js";
+import type { SandboxDeleteOptions } from "#shared/sandbox-provider.js";
import type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";
/**
@@ -83,12 +83,11 @@ export interface SandboxRemovePathOptions {
* 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. `id` and
- * `resolvePath` are eve-specific extensions that the runtime relies on
- * for caching and `/workspace` path anchoring.
+ * 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 backend. Absolute paths pass through unchanged.
+ * for every provider. Absolute paths pass through unchanged.
*
*/
export interface SandboxSession extends Pick<
@@ -102,17 +101,6 @@ export interface SandboxSession extends Pick<
| "writeBinaryFile"
| "writeTextFile"
> {
- /**
- * Stable identifier for the backend session this handle wraps.
- *
- * Persists across reconnects to the same logical session: two calls
- * that resume the same underlying backend sandbox observe the same
- * `id`. Template sessions constructed during bootstrap expose the
- * template key; live sessions expose the session key assigned by the
- * runtime. Useful as a cache key for per-session state that must
- * outlive individual step executions.
- */
- readonly id: string;
/**
* Anchors a sandbox-relative path to `/workspace` and returns the
* resulting absolute path.
@@ -121,21 +109,8 @@ export interface SandboxSession extends Pick<
* The read and write methods already apply this internally.
*/
resolvePath(path: string): string;
- /**
- * Applies a firewall network policy to this live sandbox at run time,
- * for changing the policy *during* a turn (e.g. brokering a credential
- * resolved mid-turn, or tightening egress after fetching data). A
- * per-domain `transform` injects headers at the firewall so secrets
- * never enter the sandbox process. The policy takes effect from the time
- * the call resolves, so await it before the egress you want governed.
- *
- * When the policy is known at session start, prefer configuring it up
- * front in the sandbox backend factory or `onSession`'s `use()`. The
- * Docker backend honors only `"allow-all"` and `"deny-all"`;
- * the just-bash backend rejects this call entirely (its network policy
- * is fixed at sandbox creation and it runs no binaries to govern).
- */
- setNetworkPolicy(policy: SandboxNetworkPolicy): Promise<void>;
+ /** Applies a firewall policy when the selected provider supports mutable networking. */
+ setNetworkPolicy?(policy: SandboxNetworkPolicy): Promise<void>;
/**
* Removes one file or directory from the sandbox filesystem.
*
@@ -151,27 +126,37 @@ export interface SandboxSession extends Pick<
* Unlike the I/O-only session used during sandbox initialization, this handle
* exposes provider-backed lifecycle operations.
*/
+export interface MutableNetworkSandboxSession extends SandboxSession {
+ /** Applies a firewall policy to the live sandbox. */
+ setNetworkPolicy(policy: SandboxNetworkPolicy): Promise<void>;
+}
+
+export type FixedNetworkSandboxSession = Omit<SandboxSession, "setNetworkPolicy">;
+
export interface RuntimeSandboxSession extends SandboxSession {
- /** Permanently deletes this sandbox and its disposable backend state. */
+ /** Permanently deletes this sandbox and its disposable provider state. */
delete(options?: SandboxDeleteOptions): Promise<void>;
/**
* Stops the backing sandbox compute while preserving the durable session.
* A later runtime callback reopens the session through its configured
- * backend. Providers may also support resuming the same handle.
+ * provider. Providers may also support resuming the same handle.
*/
stop(): Promise<void>;
}
+export type RuntimeSandboxSessionFor<Session extends SandboxSession> = Session &
+ Pick<RuntimeSandboxSession, "delete" | "stop">;
+
/**
* Internal sandbox session, used to construct the public {@link SandboxSession}.
*
- * Backend implementers only need to provide byte-oriented file I/O and
+ * 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 backends look symmetric with
+ * 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.
@@ -180,12 +165,8 @@ export interface InternalSandboxSession extends Pick<
AiSdkSandbox,
"spawn" | "readFile" | "writeFile"
> {
- /**
- * Stable identifier surfaced on the public {@link SandboxSession}.
- */
- readonly id: string;
- /** Removes an already-resolved path from the backend filesystem. */
+ /** Removes an already-resolved path from the provider filesystem. */
removePath(options: SandboxRemovePathOptions): Promise<void>;
- /** Translates a user-facing path to the backend's native path. */
+ /** Translates a user-facing path to the provider's native path. */
resolvePath(path: string): string;
}
diff --git a/packages/eve/src/shared/sandbox-template-error.ts b/packages/eve/src/shared/sandbox-template-error.ts
new file mode 100644
index 000000000..748672da5
--- /dev/null
+++ b/packages/eve/src/shared/sandbox-template-error.ts
@@ -0,0 +1,24 @@
+export class SandboxTemplateNotProvisionedError extends Error {
+ readonly providerName: string;
+ readonly templateKey: string;
+
+ constructor(input: { readonly providerName: string; readonly templateKey: string }) {
+ super(
+ `Sandbox template "${input.templateKey}" is not provisioned for provider "${input.providerName}". Run \`eve build\` before serving traffic.`,
+ );
+ this.name = "SandboxTemplateNotProvisionedError";
+ this.providerName = input.providerName;
+ this.templateKey = input.templateKey;
+ }
+
+ static is(error: unknown): error is SandboxTemplateNotProvisionedError {
+ return (
+ error instanceof SandboxTemplateNotProvisionedError ||
+ (typeof error === "object" &&
+ error !== null &&
+ Reflect.get(error, "name") === "SandboxTemplateNotProvisionedError" &&
+ typeof Reflect.get(error, "providerName") === "string" &&
+ typeof Reflect.get(error, "templateKey") === "string")
+ );
+ }
+}
diff --git a/packages/eve/src/subagents/tool.test.ts b/packages/eve/src/subagents/tool.test.ts
index 0408defb5..dce98097b 100644
--- a/packages/eve/src/subagents/tool.test.ts
+++ b/packages/eve/src/subagents/tool.test.ts
@@ -61,10 +61,10 @@ function buildRuntimeSubagentRunInput(
});
}
-function makeInheritingGraph(nodeId: string) {
+function makeInheritingGraph(nodeId: string): import("./tool.js").SubagentSandboxGraph {
return {
nodesByNodeId: new Map([
- [nodeId, { sandboxRegistry: { sandbox: { definition: { inheritsParent: true } } } }],
+ [nodeId, { sandboxRegistry: { sandbox: { definition: { kind: "parent" } } } }],
]),
};
}
diff --git a/packages/eve/src/subagents/tool.ts b/packages/eve/src/subagents/tool.ts
index b241e4c82..5e4fc7cb0 100644
--- a/packages/eve/src/subagents/tool.ts
+++ b/packages/eve/src/subagents/tool.ts
@@ -52,7 +52,7 @@ export interface SubagentSandboxGraph {
{
readonly sandboxRegistry: {
readonly sandbox: {
- readonly definition: { readonly inheritsParent?: boolean };
+ readonly definition: { readonly kind: "independent" | "parent" };
} | null;
};
}
@@ -123,10 +123,10 @@ export function buildSubagentRunInput(input: {
subagentName: action.subagentName,
};
if (input.taskId !== undefined) adapterState.taskId = input.taskId;
- const sharesSandbox =
- input.graph?.nodesByNodeId.get(action.nodeId)?.sandboxRegistry.sandbox?.definition
- .inheritsParent === true || input.selfAgent;
- if (sharesSandbox) {
+ const reusesOwnerSandbox =
+ input.graph?.nodesByNodeId.get(action.nodeId)?.sandboxRegistry.sandbox?.definition.kind ===
+ "parent" || input.selfAgent;
+ if (reusesOwnerSandbox) {
if (session.sandboxState !== undefined) {
adapterState.parentSandboxState = session.sandboxState;
}
diff --git a/packages/eve/src/tools/framework/agent-contract.ts b/packages/eve/src/tools/framework/agent-contract.ts
index d46680e24..e07957f3f 100644
--- a/packages/eve/src/tools/framework/agent-contract.ts
+++ b/packages/eve/src/tools/framework/agent-contract.ts
@@ -6,7 +6,7 @@ export const AGENT_TOOL_DESCRIPTION = [
"Delegate a focused subtask to a copy of yourself, or continue or steer a previous delegation with `agentId`.",
"Use it to isolate complex work or split a large task into independent pieces.",
"Issue multiple `agent` calls in one response to run a small fixed set in parallel.",
- "A new child has fresh history and state but shares your tools and sandbox, so include essential context in `message` and give parallel writers non-overlapping scopes.",
+ "A new child has fresh history and state but reuses your tools and sandbox, so include essential context in `message` and give parallel writers non-overlapping scopes.",
].join(" ");
export const SUBAGENT_TOOL_INPUT_SCHEMA = z.strictObject({
diff --git a/packages/eve/test/default-backend.test.ts b/packages/eve/test/default-backend.test.ts
deleted file mode 100644
index 59280305a..000000000
--- a/packages/eve/test/default-backend.test.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { describe, expect, it } from "vitest";
-import {
- defaultSandbox,
- selectDefaultSandbox,
- type DefaultSandboxProbes,
-} from "../src/public/sandbox/backends/default.js";
-
-function probes(overrides: Partial<DefaultSandboxProbes>): DefaultSandboxProbes {
- return {
- isDeployedOnVercel: () => false,
- isDockerAvailable: () => false,
- isMicrosandboxSupported: () => false,
- ...overrides,
- };
-}
-
-describe("selectDefaultSandbox", () => {
- it("prefers Vercel Sandbox when deploying on Vercel, before any local probe", () => {
- let probed = false;
- const backend = selectDefaultSandbox(
- undefined,
- probes({
- isDeployedOnVercel: () => true,
- isDockerAvailable: () => {
- probed = true;
- return true;
- },
- }),
- );
- expect(backend.name).toBe("vercel");
- expect(probed).toBe(false);
- });
-
- it("picks docker when a compatible daemon is available", () => {
- const backend = selectDefaultSandbox(
- undefined,
- probes({ isDockerAvailable: () => true, isMicrosandboxSupported: () => true }),
- );
- expect(backend.name).toBe("docker");
- });
-
- it("falls back to microsandbox on supported hosts without docker", () => {
- const backend = selectDefaultSandbox(
- undefined,
- probes({ isMicrosandboxSupported: () => true }),
- );
- expect(backend.name).toBe("microsandbox");
- });
-
- it("falls back to just-bash when nothing else is available", () => {
- const backend = selectDefaultSandbox(undefined, probes({}));
- expect(backend.name).toBe("just-bash");
- });
-});
-
-describe("defaultSandbox", () => {
- it("constructs a lazy backend without probing at construction time", () => {
- // Constructing must not touch the host: probing happens on first
- // use (name access / create / prewarm) via the lazy wrapper.
- const backend = defaultSandbox({ docker: { image: "alpine:3" } });
- expect(typeof backend.create).toBe("function");
- expect(typeof backend.prewarm).toBe("function");
- });
-});
diff --git a/packages/eve/test/normalize-sandbox.test.ts b/packages/eve/test/normalize-sandbox.test.ts
deleted file mode 100644
index 1c624dfc0..000000000
--- a/packages/eve/test/normalize-sandbox.test.ts
+++ /dev/null
@@ -1,176 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { normalizeSandboxDefinition } from "../src/internal/authored-definition/sandbox.js";
-import { docker } from "../src/public/sandbox/backends/docker.js";
-import { vercel } from "../src/public/sandbox/backends/vercel.js";
-
-const ERROR_MESSAGE = "Test error";
-
-describe("normalizeSandboxDefinition", () => {
- it("accepts an empty definition", () => {
- expect(normalizeSandboxDefinition({}, ERROR_MESSAGE)).toEqual({});
- });
-
- it("accepts a definition that names a backend factory result", () => {
- const result = normalizeSandboxDefinition({ backend: docker() }, ERROR_MESSAGE);
- expect(result.backend?.name).toBe("docker");
- });
-
- it("accepts the vercel factory result", () => {
- const result = normalizeSandboxDefinition({ backend: vercel() }, ERROR_MESSAGE);
- expect(result.backend?.name).toBe("vercel");
- });
-
- it("accepts a custom inline backend", () => {
- const customBackend = {
- name: "custom",
- async create() {
- return {} as never;
- },
- };
- const result = normalizeSandboxDefinition({ backend: customBackend }, ERROR_MESSAGE);
- expect(result.backend?.name).toBe("custom");
- });
-
- it("accepts bootstrap, onSession, and description fields", () => {
- const bootstrap = async () => {};
- const onSession = async () => {};
- const result = normalizeSandboxDefinition(
- {
- backend: docker(),
- bootstrap,
- description: "A test sandbox.",
- onSession,
- },
- ERROR_MESSAGE,
- );
- expect(result.description).toBe("A test sandbox.");
- expect(result.bootstrap).toBe(bootstrap);
- expect(result.revalidationKey).toBeUndefined();
- expect(result.onSession).toBe(onSession);
- });
-
- it("accepts bootstrap with a revalidationKey", () => {
- const bootstrap = async () => {};
- const revalidationKey = () => "test-bootstrap";
- const result = normalizeSandboxDefinition(
- {
- bootstrap,
- revalidationKey,
- },
- ERROR_MESSAGE,
- );
-
- expect(result.bootstrap).toBe(bootstrap);
- expect(result.revalidationKey).toBe(revalidationKey);
- });
-
- it("rejects revalidationKey without bootstrap", () => {
- expect(() =>
- normalizeSandboxDefinition(
- {
- revalidationKey: () => "unused",
- },
- ERROR_MESSAGE,
- ),
- ).toThrow(/"revalidationKey" field can only be set/);
- });
-
- it("rejects non-function revalidationKey values", () => {
- expect(() =>
- normalizeSandboxDefinition(
- {
- bootstrap: async () => {},
- revalidationKey: "not a function",
- },
- ERROR_MESSAGE,
- ),
- ).toThrow(ERROR_MESSAGE);
- });
-
- it("rejects legacy cacheKey values", () => {
- expect(() =>
- normalizeSandboxDefinition(
- {
- bootstrap: async () => {},
- cacheKey: () => "unused",
- },
- ERROR_MESSAGE,
- ),
- ).toThrow(/Unknown key "cacheKey"/);
- });
-
- it("rejects a non-object backend value", () => {
- expect(() => normalizeSandboxDefinition({ backend: 5 }, ERROR_MESSAGE)).toThrow(
- /SandboxBackend value/,
- );
- });
-
- it("rejects a backend without a name", () => {
- expect(() =>
- normalizeSandboxDefinition({ backend: { create: async () => ({}) as never } }, ERROR_MESSAGE),
- ).toThrow(/non-empty string "name"/);
- });
-
- it("rejects a backend without a create function", () => {
- expect(() => normalizeSandboxDefinition({ backend: { name: "x" } }, ERROR_MESSAGE)).toThrow(
- /"create" function/,
- );
- });
-
- it("rejects a backend whose prewarm is not a function", () => {
- expect(() =>
- normalizeSandboxDefinition(
- {
- backend: {
- name: "x",
- create: async () => ({}) as never,
- prewarm: "not a function",
- },
- },
- ERROR_MESSAGE,
- ),
- ).toThrow(/"backend.prewarm"/);
- });
-
- it("rejects a definition with the now-removed `adapter` key", () => {
- expect(() => normalizeSandboxDefinition({ adapter: "vercel" }, ERROR_MESSAGE)).toThrow(
- ERROR_MESSAGE,
- );
- });
-
- it("rejects a non-string description", () => {
- expect(() => normalizeSandboxDefinition({ description: 5 }, ERROR_MESSAGE)).toThrow(
- /"description" field must be a string/,
- );
- });
-
- it("accepts a backend factory callback and invokes it lazily, once", () => {
- let calls = 0;
- const backend = {
- name: "lazy-test",
- async create() {
- return {} as never;
- },
- async prewarm() {
- return { reused: false };
- },
- };
- const result = normalizeSandboxDefinition(
- {
- backend: () => {
- calls += 1;
- return backend;
- },
- },
- ERROR_MESSAGE,
- );
-
- expect(calls).toBe(0); // not yet invoked at normalize time
- expect(result.backend?.name).toBe("lazy-test");
- expect(calls).toBe(1);
- // subsequent accesses reuse the cached value
- expect(result.backend?.name).toBe("lazy-test");
- expect(calls).toBe(1);
- });
-});
diff --git a/packages/eve/test/resolve-agent.test.ts b/packages/eve/test/resolve-agent.test.ts
index 3cd35ab21..e90fad84d 100644
--- a/packages/eve/test/resolve-agent.test.ts
+++ b/packages/eve/test/resolve-agent.test.ts
@@ -42,7 +42,11 @@ describe("resolveAgent", () => {
]),
);
expect(resolved.sandbox).toMatchObject({
- backend: expect.objectContaining({ create: expect.any(Function), name: expect.any(String) }),
+ environment: {
+ open: expect.any(Function),
+ provider: expect.any(String),
+ },
+ kind: "independent",
logicalPath: "sandbox.ts",
});
expect(resolved.skills).toContainEqual(
diff --git a/packages/eve/test/runtime-agent-graph.test.ts b/packages/eve/test/runtime-agent-graph.test.ts
index 966c7c883..3916be360 100644
--- a/packages/eve/test/runtime-agent-graph.test.ts
+++ b/packages/eve/test/runtime-agent-graph.test.ts
@@ -23,7 +23,9 @@ describe("resolveRuntimeAgentGraph", () => {
const names = graph.root.turnAgent.tools.map((tool) => tool.name);
expect(graph.root.nodeId).toBe("__root__");
- expect(graph.root.sandboxRegistry.sandbox.definition.backend.name).toBe("vercel");
+ const definition = graph.root.sandboxRegistry.sandbox.definition;
+ expect(definition.kind).toBe("independent");
+ if (definition.kind === "independent") expect(definition.environment.provider).toBe("vercel");
expect(names).toEqual(manifest.tools.map((tool) => tool.name));
expect(names).toContain("web_search");
expect(graph.root.agent.tools.every((tool) => tool.owner.kind === "framework")).toBe(true);
diff --git a/packages/eve/test/scenarios/agent-info-route.scenario.test.ts b/packages/eve/test/scenarios/agent-info-route.scenario.test.ts
index 45bb5bb69..6650fea0e 100644
--- a/packages/eve/test/scenarios/agent-info-route.scenario.test.ts
+++ b/packages/eve/test/scenarios/agent-info-route.scenario.test.ts
@@ -83,7 +83,7 @@ describe("eve agent info route", () => {
const payload = (await response.json()) as AgentInfoResponse;
expect(payload.kind).toBe("eve-agent-info");
- expect(payload.version).toBe(4);
+ expect(payload.version).toBe(5);
expect(payload.mode).toBe("development");
expect(payload.agent.model.id).toBe("openai/gpt-5.4");
expect(payload.instructions.static[0]?.content).toContain("precise assistant");
diff --git a/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts b/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts
index a653e5449..be6e66c03 100644
--- a/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts
+++ b/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts
@@ -411,11 +411,10 @@ describe("app runtime dependency tracing", () => {
join(appRoot, "agent", "sandbox.ts"),
[
'import { defineSandbox } from "eve/sandbox";',
- 'import { justbash } from "eve/sandbox/just-bash";',
+ 'import { JustBashSandbox } from "eve/sandbox/just-bash";',
"",
- "export default defineSandbox({",
- " backend: justbash(),",
- "});",
+ "export const environment = JustBashSandbox.environment();",
+ "export default defineSandbox(() => environment.open());",
"",
].join("\n"),
);
diff --git a/packages/eve/test/scenarios/compile-agent.scenario.test.ts b/packages/eve/test/scenarios/compile-agent.scenario.test.ts
index 2b53979d7..115e40218 100644
--- a/packages/eve/test/scenarios/compile-agent.scenario.test.ts
+++ b/packages/eve/test/scenarios/compile-agent.scenario.test.ts
@@ -773,11 +773,12 @@ describe("compileAgent", () => {
},
]);
expect(result.manifest.sandbox).toEqual({
- description: undefined,
+ providerName: expect.any(String),
+ environmentExportName: "environment",
exportName: undefined,
+ inheritsParent: undefined,
logicalPath: "sandbox/sandbox.cjs",
- revalidationKey: undefined,
- sourceHash: expect.any(String),
+ revisionHash: expect.any(String),
sourceId: "sandbox/sandbox.cjs",
sourceKind: "module",
});
@@ -1292,105 +1293,6 @@ describe("compileAgent", () => {
);
});
- it("stores resolved sandbox bootstrap revalidation keys in compiled artifacts", async () => {
- const { agentRoot, appRoot } = await createAppRoot(
- "eve-compile-sandbox-revalidation-key-",
- APP_ROOT_OPTIONS,
- );
-
- await mkdir(join(agentRoot, "sandbox"), {
- recursive: true,
- });
- await writeFile(join(agentRoot, "agent.mjs"), 'export default { model: "openai/gpt-5.4" };\n');
- await writeFile(join(agentRoot, "instructions.md"), "You are a precise assistant.");
- await writeFile(
- join(agentRoot, "sandbox", "sandbox.mjs"),
- [
- "export default {",
- " async revalidationKey() {",
- ' return "bootstrap-revalidation-key-v1";',
- " },",
- " async bootstrap({ use }) {",
- " const sandbox = await use();",
- ' await sandbox.run({ command: "echo bootstrap" });',
- " },",
- "};",
- "",
- ].join("\n"),
- );
-
- const result = await compileAgent({
- startPath: appRoot,
- });
-
- expect(result.manifest.sandbox).toEqual({
- description: undefined,
- exportName: undefined,
- logicalPath: "sandbox/sandbox.mjs",
- revalidationKey: "bootstrap-revalidation-key-v1",
- sourceHash: expect.any(String),
- sourceId: "sandbox/sandbox.mjs",
- sourceKind: "module",
- });
- });
-
- it("compiles sandbox bootstrap without a revalidation key", async () => {
- const { agentRoot, appRoot } = await createAppRoot(
- "eve-compile-sandbox-without-revalidation-key-",
- APP_ROOT_OPTIONS,
- );
-
- await mkdir(join(agentRoot, "sandbox"), {
- recursive: true,
- });
- await writeFile(join(agentRoot, "agent.mjs"), 'export default { model: "openai/gpt-5.4" };\n');
- await writeFile(join(agentRoot, "instructions.md"), "You are a precise assistant.");
- await writeFile(
- join(agentRoot, "sandbox", "sandbox.mjs"),
- [
- "export default {",
- " async bootstrap({ use }) {",
- " const sandbox = await use();",
- ' await sandbox.run({ command: "echo bootstrap" });',
- " },",
- "};",
- "",
- ].join("\n"),
- );
-
- const result = await compileAgent({
- startPath: appRoot,
- });
-
- expect(result.manifest.sandbox).toEqual({
- description: undefined,
- exportName: undefined,
- logicalPath: "sandbox/sandbox.mjs",
- revalidationKey: undefined,
- sourceHash: expect.any(String),
- sourceId: "sandbox/sandbox.mjs",
- sourceKind: "module",
- });
- });
-
- it("rejects sandbox bootstrap revalidation keys that resolve to empty or non-string values", async () => {
- const emptyKeyApp = await createSandboxRevalidationKeyValidationApp({
- name: "empty",
- revalidationKeyExpression: '() => ""',
- });
- const nonStringKeyApp = await createSandboxRevalidationKeyValidationApp({
- name: "non-string",
- revalidationKeyExpression: "() => 123",
- });
-
- await expect(compileAgent({ startPath: emptyKeyApp.appRoot })).rejects.toThrow(
- /must return a non-empty string/,
- );
- await expect(compileAgent({ startPath: nonStringKeyApp.appRoot })).rejects.toThrow(
- /must return a string/,
- );
- });
-
it("compiles authored subagent sandboxes into child runtime nodes", async () => {
const { agentRoot, appRoot } = await createAppRoot(
"eve-compile-subagent-sandbox-",
@@ -1417,12 +1319,13 @@ describe("compileAgent", () => {
await writeFile(
join(subagentRoot, "sandbox", "sandbox.mjs"),
[
- "export default {",
- " async onSession({ use }) {",
- " const sandbox = await use();",
- ' await sandbox.run({ command: "mkdir -p .research" });',
- " },",
- "};",
+ 'import { DefaultSandbox, defineSandbox } from "eve/sandbox";',
+ "export const environment = DefaultSandbox.environment();",
+ "export default defineSandbox(async () => {",
+ " const sandbox = await environment.open();",
+ ' await sandbox.run({ command: "mkdir -p .research" });',
+ " return sandbox;",
+ "});",
"",
].join("\n"),
);
@@ -1528,40 +1431,6 @@ describe("compileAgent", () => {
});
});
-async function createSandboxRevalidationKeyValidationApp(input: {
- readonly name: string;
- readonly revalidationKeyExpression: string;
-}): Promise<{ readonly agentRoot: string; readonly appRoot: string }> {
- const app = await createAppRoot(
- `eve-compile-sandbox-${input.name}-revalidation-key-`,
- APP_ROOT_OPTIONS,
- );
-
- await mkdir(join(app.agentRoot, "sandbox"), {
- recursive: true,
- });
- await writeFile(
- join(app.agentRoot, "agent.mjs"),
- 'export default { model: "openai/gpt-5.4" };\n',
- );
- await writeFile(join(app.agentRoot, "instructions.md"), "You are a precise assistant.");
- await writeFile(
- join(app.agentRoot, "sandbox", "sandbox.mjs"),
- [
- "export default {",
- ` revalidationKey: ${input.revalidationKeyExpression},`,
- " async bootstrap({ use }) {",
- " const sandbox = await use();",
- ' await sandbox.run({ command: "echo bootstrap" });',
- " },",
- "};",
- "",
- ].join("\n"),
- );
-
- return app;
-}
-
async function expectTscToPass(
args: readonly string[],
options: { readonly cwd: string },
diff --git a/packages/eve/test/scenarios/eval-command-environment.scenario.test.ts b/packages/eve/test/scenarios/eval-command-environment.scenario.test.ts
index a6011b68a..e24b03556 100644
--- a/packages/eve/test/scenarios/eval-command-environment.scenario.test.ts
+++ b/packages/eve/test/scenarios/eval-command-environment.scenario.test.ts
@@ -369,10 +369,10 @@ describe("eve eval environment loading", () => {
};
const exit = vi.spyOn(process, "exit").mockImplementation(() => undefined as never);
const close = vi.fn(async () => {});
- const handle = { shutdown: vi.fn(async () => {}) };
+ const handle = { onRuntimeShutdown: vi.fn(async () => {}) };
const evaluation = makeEvaluation("local");
- trackActiveSandboxHandle({ backendName: "microsandbox", handle, sessionKey: "session-1" });
+ trackActiveSandboxHandle({ providerName: "microsandbox", handle, sessionId: "session-1" });
process.chdir(fixtureRoot);
mockedEvalDependencies.createDevelopmentServer.mockReturnValue({
close,
@@ -401,7 +401,7 @@ describe("eve eval environment loading", () => {
}
expect(close).toHaveBeenCalledTimes(1);
- expect(handle.shutdown).toHaveBeenCalledTimes(1);
+ expect(handle.onRuntimeShutdown).toHaveBeenCalledTimes(1);
expect(process.env.EVE_EVALUATION).toBe("1");
expect(process.env.EVE_EVALUATION_RUN_ID).toMatch(/^[0-9a-f-]{36}$/u);
expect(exit).toHaveBeenCalledWith(0);
diff --git a/packages/eve/test/scenarios/framework-next-build.scenario.test.ts b/packages/eve/test/scenarios/framework-next-build.scenario.test.ts
index 31dbc9b80..d2f086543 100644
--- a/packages/eve/test/scenarios/framework-next-build.scenario.test.ts
+++ b/packages/eve/test/scenarios/framework-next-build.scenario.test.ts
@@ -22,6 +22,7 @@ const NEXT_EVE_MIDDLEWARE_DESCRIPTOR = {
...NEXT_EVE_PROXY_DESCRIPTOR,
files: {
...NEXT_EVE_PROXY_DESCRIPTOR.files,
+ "next.config.mjs": `import { withEve } from "eve/next";\n\nexport default withEve({}, { eveBuildCommand: "pnpm exec eve build --skip-sandbox-prewarm" });\n`,
".vercel/project.json": `${JSON.stringify(
{
orgId: "team_eve_scenario",
@@ -88,6 +89,7 @@ Triage the support queue.
"next.config.mjs": `import { withEve } from "eve/next";
export default withEve({}, {
+ eveBuildCommand: "pnpm exec eve build --skip-sandbox-prewarm",
agents: {
billing: "./agents/billing",
support: "./agents/support",
@@ -129,7 +131,12 @@ async function readVercelOutputRoutes(outputRoot: string): Promise<readonly unkn
async function runVercelBuild(appRoot: string): Promise<void> {
await runPnpmCommand({
- args: ["exec", "./node_modules/.bin/vercel", "build", "--yes"],
+ args: [
+ "exec",
+ "./node_modules/.bin/vercel",
+ "build",
+ "--yes",
+ ],
cwd: appRoot,
env: {
...process.env,
diff --git a/packages/eve/test/scenarios/hostless-agent-workspace.scenario.test.ts b/packages/eve/test/scenarios/hostless-agent-workspace.scenario.test.ts
index 42efeaa7d..93be09c25 100644
--- a/packages/eve/test/scenarios/hostless-agent-workspace.scenario.test.ts
+++ b/packages/eve/test/scenarios/hostless-agent-workspace.scenario.test.ts
@@ -25,7 +25,7 @@ describe("hostless agent workspace", () => {
projectId: "prj_eve_collection_scenario",
projectName: "hostless-agent-workspace",
settings: {
- buildCommand: "pnpm exec eve build",
+ buildCommand: "pnpm exec eve build --skip-sandbox-prewarm",
framework: null,
outputDirectory: null,
rootDirectory: null,
@@ -40,7 +40,15 @@ describe("hostless agent workspace", () => {
installDependencies: true,
name: "hostless-agent-workspace",
});
- await runPnpmCommand({ args: ["exec", "vercel", "build", "--yes"], cwd: app.appRoot });
+ await runPnpmCommand({
+ args: [
+ "exec",
+ "vercel",
+ "build",
+ "--yes",
+ ],
+ cwd: app.appRoot,
+ });
const outputRoot = join(app.appRoot, ".vercel", "output");
const config = JSON.parse(await readFile(join(outputRoot, "config.json"), "utf8"));
diff --git a/packages/eve/test/scenarios/load-agent-info-data.scenario.test.ts b/packages/eve/test/scenarios/load-agent-info-data.scenario.test.ts
index 57ce0f02e..fef4380cb 100644
--- a/packages/eve/test/scenarios/load-agent-info-data.scenario.test.ts
+++ b/packages/eve/test/scenarios/load-agent-info-data.scenario.test.ts
@@ -34,7 +34,12 @@ describe("loadAgentInfoData", () => {
});
await writeFile(
join(agentRoot, "sandbox", "sandbox.ts"),
- ["export default {};", ""].join("\n"),
+ [
+ 'import { DefaultSandbox, defineSandbox } from "eve/sandbox";',
+ "export const environment = DefaultSandbox.environment();",
+ "export default defineSandbox(() => environment.open());",
+ "",
+ ].join("\n"),
);
await compileAgent({
@@ -65,6 +70,7 @@ describe("loadAgentInfoData", () => {
const agentInfoCompiledArtifactsSource = resolveAgentInfoCompiledArtifactsSource({
kind: "production",
+ sandboxScope: "test-sandbox-scope",
});
expect(agentInfoCompiledArtifactsSource.kind).toBe("bundled");
const data = await loadAgentInfoManifestData({
diff --git a/packages/eve/test/scenarios/public-api-portability.scenario.test.ts b/packages/eve/test/scenarios/public-api-portability.scenario.test.ts
index 44a99afd3..67e8cc3b4 100644
--- a/packages/eve/test/scenarios/public-api-portability.scenario.test.ts
+++ b/packages/eve/test/scenarios/public-api-portability.scenario.test.ts
@@ -65,43 +65,60 @@ export default withEve(config);
{
descriptor: {
files: {
- "agent/sandbox.ts": `import { defaultBackend, defineSandbox } from "eve/sandbox";
-import { docker } from "eve/sandbox/docker";
-import { justbash } from "eve/sandbox/just-bash";
-import { microsandbox } from "eve/sandbox/microsandbox";
-import { Drive, vercel } from "eve/sandbox/vercel";
+ "agent/sandbox.ts": `import { DefaultSandbox, defineSandbox } from "eve/sandbox";
+import { defineSandboxProvider } from "eve/sandbox/provider";
+import { DockerSandbox } from "eve/sandbox/docker";
+import { JustBashSandbox } from "eve/sandbox/just-bash";
+import { MicrosandboxSandbox } from "eve/sandbox/microsandbox";
+import { Drive, VercelSandbox } from "eve/sandbox/vercel";
-const fallback = defaultBackend({
- docker: { image: "ghcr.io/vercel/eve:latest" },
- justBash: {},
- microsandbox: {},
- vercel: { resources: { vcpus: 2 } },
+const custom = defineSandboxProvider({
+ name: "custom",
+ environment() {
+ return {
+ async prepare() { return null; },
+ async resume() { throw new Error("unused"); },
+ async start() { throw new Error("unused"); },
+ };
+ },
});
-void Drive;
+void custom.environment();
-void docker;
-void justbash;
-void microsandbox;
+export const environment = process.env.VERCEL === "1"
+ ? VercelSandbox.environment({ resources: { vcpus: 2 } })
+ : DefaultSandbox.environment({ docker: { image: "ghcr.io/vercel/eve:latest" } });
+void Drive;
+async function verifyMutableNetworkCapability() {
+ const sandbox = await DockerSandbox.dockerfile().open({ networkPolicy: "deny-all" });
+ await sandbox.setNetworkPolicy("allow-all");
+}
+void verifyMutableNetworkCapability;
+void DockerSandbox.image("ghcr.io/acme/agent:latest");
+void JustBashSandbox.environment();
+void MicrosandboxSandbox.dockerfile();
+void MicrosandboxSandbox.image("ghcr.io/acme/agent:latest");
-export default defineSandbox({
- backend: process.env.VERCEL === "1" ? vercel() : fallback,
-});
+export default defineSandbox(() => environment.open());
`,
},
name: "sandbox-public-api-portability",
},
include: [
"src/public/sandbox/index.ts",
+ "src/public/sandbox/provider.ts",
"src/public/sandbox/docker.ts",
"src/public/sandbox/just-bash.ts",
"src/public/sandbox/microsandbox.ts",
"src/public/sandbox/vercel.ts",
],
- name: "lets tsc typecheck sandbox backend factories from nested subpath imports",
+ name: "lets tsc typecheck sandbox environments from nested subpath imports",
packageExports: {
"./sandbox": {
types: "./dist/src/public/sandbox/index.d.ts",
},
+ "./sandbox/provider": {
+ types: "./dist/src/public/sandbox/provider.d.ts",
+ },
"./sandbox/docker": {
types: "./dist/src/public/sandbox/docker.d.ts",
},
@@ -346,9 +363,17 @@ async function expectPortableFixtureToTypecheck(testCase: PortabilityCase): Prom
)}\n`,
);
- await runFile(process.execPath, [TSC_BIN_PATH, "-p", consumerTsconfigPath], {
- cwd: appRoot,
- });
+ try {
+ await runFile(process.execPath, [TSC_BIN_PATH, "-p", consumerTsconfigPath], {
+ cwd: appRoot,
+ });
+ } catch (error) {
+ const stderr =
+ typeof error === "object" && error !== null && "stderr" in error
+ ? String(error.stderr)
+ : String(error);
+ throw new Error(`Portable consumer typecheck failed:\n${stderr}`, { cause: error });
+ }
}
async function writeDescriptorAppFiles(input: {
diff --git a/packages/eve/test/scenarios/runtime-loaders.scenario.test.ts b/packages/eve/test/scenarios/runtime-loaders.scenario.test.ts
index b341ff2cb..3f62260f7 100644
--- a/packages/eve/test/scenarios/runtime-loaders.scenario.test.ts
+++ b/packages/eve/test/scenarios/runtime-loaders.scenario.test.ts
@@ -190,7 +190,12 @@ async function writeRuntimeLoaderSubagentFixture(agentRoot: string): Promise<voi
);
await writeFile(
join(researcherRoot, "sandbox", "sandbox.mjs"),
- ["export default {};\n"].join("\n"),
+ [
+ 'import { DefaultSandbox, defineSandbox } from "eve/sandbox";',
+ "export const environment = DefaultSandbox.environment();",
+ "export default defineSandbox(() => environment.open());",
+ "",
+ ].join("\n"),
);
}
diff --git a/packages/eve/test/scenarios/runtime-sandbox-keys.scenario.test.ts b/packages/eve/test/scenarios/runtime-sandbox-keys.scenario.test.ts
deleted file mode 100644
index 12e4be169..000000000
--- a/packages/eve/test/scenarios/runtime-sandbox-keys.scenario.test.ts
+++ /dev/null
@@ -1,364 +0,0 @@
-import { mkdir, writeFile } from "node:fs/promises";
-import { join } from "node:path";
-
-import { afterEach, describe, expect, it, vi } from "vitest";
-
-import {
- createBundledRuntimeCompiledArtifactsSource,
- createDiskRuntimeCompiledArtifactsSource,
-} from "../../src/runtime/compiled-artifacts-source.js";
-import { createRuntimeSandboxTemplateKey } from "../../src/runtime/sandbox/keys.js";
-import { useTemporaryDirectories } from "../../src/internal/testing/use-temporary-app-roots.js";
-
-/**
- * Scenario-tier coverage for `createRuntimeSandboxTemplateKey`. The key
- * derivation reads `compile-metadata.json` off the real filesystem and
- * resolves template scopes via `realpath(appRoot)` — both are intentional
- * dependencies on disk semantics that the integration tier no longer
- * admits. The equivalent in-memory coverage of the authored-grammar rules
- * lives in the discover/compile integration tier; here we prove the
- * disk-backed fallback paths behave as documented.
- */
-const createScratchDirectory = useTemporaryDirectories();
-const BOOTSTRAP_SOURCE_HASH = "bootstrap-source-hash";
-
-afterEach(() => {
- vi.unstubAllEnvs();
-});
-
-async function createTemporaryAppRoot(options?: { sourceGraphHash?: string }): Promise<string> {
- const appRoot = await createScratchDirectory("eve-sbx-keys-");
- await mkdir(join(appRoot, ".eve", "compile"), { recursive: true });
- await writeFile(
- join(appRoot, ".eve", "compile", "compile-metadata.json"),
- `${JSON.stringify({
- compile: {
- moduleMap: { path: ".eve/compile/module-map.mjs", sha256: "deadbeef" },
- },
- discovery: {
- diagnostics: { path: ".eve/discovery/diagnostics.json", sha256: "deadbeef" },
- manifest: { path: ".eve/discovery/agent-discovery-manifest.json", sha256: "deadbeef" },
- sourceGraphHash: options?.sourceGraphHash ?? "test-source-graph-hash",
- summary: { errors: 0, warnings: 0 },
- },
- generator: { name: "eve", version: "0.0.0-test" },
- kind: "eve-compile-metadata",
- status: "ready",
- version: 6,
- })}\n`,
- );
- return appRoot;
-}
-
-const WORKSPACE_PLAN = { contentHash: "workspace-hash", kind: "workspace-content" } as const;
-
-function stubEmptyVercelProjectSources(): void {
- vi.stubEnv("VERCEL_PROJECT_ID", "");
- vi.stubEnv("VERCEL_OIDC_TOKEN", "");
- // A deployment id must never participate in template scopes; set one to
- // prove the fallback ignores it.
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_123");
-}
-
-describe("createRuntimeSandboxTemplateKey", () => {
- it("falls back to the realpath of the disk app root for the Vercel adapter when no project id is resolvable", async () => {
- stubEmptyVercelProjectSources();
-
- const appRoot = await createTemporaryAppRoot();
- const compiledArtifactsSource = createDiskRuntimeCompiledArtifactsSource(appRoot);
-
- const firstKey = await createRuntimeSandboxTemplateKey({
- backendName: "vercel",
- compiledArtifactsSource,
- nodeId: "__root__",
- sourceId: "sandbox/sandbox.ts",
- templatePlan: WORKSPACE_PLAN,
- });
-
- const secondKey = await createRuntimeSandboxTemplateKey({
- backendName: "vercel",
- compiledArtifactsSource,
- nodeId: "__root__",
- sourceId: "sandbox/sandbox.ts",
- templatePlan: WORKSPACE_PLAN,
- });
-
- expect(firstKey).toMatch(/^eve-sbx-tpl-vercel-/);
- expect(secondKey).toBe(firstKey);
- });
-
- it("isolates Vercel template keys per app root when no project id is resolvable", async () => {
- stubEmptyVercelProjectSources();
-
- const firstAppRoot = await createTemporaryAppRoot();
- const secondAppRoot = await createTemporaryAppRoot();
-
- const firstKey = await createRuntimeSandboxTemplateKey({
- backendName: "vercel",
- compiledArtifactsSource: createDiskRuntimeCompiledArtifactsSource(firstAppRoot),
- nodeId: "__root__",
- sourceId: "sandbox/sandbox.ts",
- templatePlan: WORKSPACE_PLAN,
- });
- const secondKey = await createRuntimeSandboxTemplateKey({
- backendName: "vercel",
- compiledArtifactsSource: createDiskRuntimeCompiledArtifactsSource(secondAppRoot),
- nodeId: "__root__",
- sourceId: "sandbox/sandbox.ts",
- templatePlan: WORKSPACE_PLAN,
- });
-
- expect(firstKey).not.toBe(secondKey);
- });
-
- it("falls back to the bundled cache key for the Vercel adapter when no app root and no project id are available", async () => {
- stubEmptyVercelProjectSources();
-
- const key = await createRuntimeSandboxTemplateKey({
- backendName: "vercel",
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- nodeId: "__root__",
- sourceId: "sandbox/sandbox.ts",
- templatePlan: WORKSPACE_PLAN,
- });
-
- expect(key).toMatch(/^eve-sbx-tpl-vercel-/);
- });
-
- it("uses stable Vercel project scope for workspace-content templates", async () => {
- vi.stubEnv("VERCEL_PROJECT_ID", "prj_123");
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_one");
-
- const firstKey = await createRuntimeSandboxTemplateKey({
- backendName: "vercel",
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- nodeId: "__root__",
- sourceId: "eve:default-sandbox",
- templatePlan: { contentHash: "workspace-hash", kind: "workspace-content" },
- });
-
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_two");
-
- const secondKey = await createRuntimeSandboxTemplateKey({
- backendName: "vercel",
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- nodeId: "__root__",
- sourceId: "eve:default-sandbox",
- templatePlan: { contentHash: "workspace-hash", kind: "workspace-content" },
- });
-
- expect(secondKey).toBe(firstKey);
- });
-
- it("uses stable Vercel project scope for bootstrap templates", async () => {
- vi.stubEnv("VERCEL_PROJECT_ID", "prj_bootstrap");
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_bootstrap_one");
-
- const firstKey = await createRuntimeSandboxTemplateKey({
- backendName: "vercel",
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- nodeId: "__root__",
- sourceId: "sandbox/sandbox.ts",
- templatePlan: {
- contentHash: "workspace-hash",
- kind: "bootstrap",
- revalidationKey: "bootstrap-day-1",
- sourceHash: BOOTSTRAP_SOURCE_HASH,
- },
- });
-
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_bootstrap_two");
-
- const secondKey = await createRuntimeSandboxTemplateKey({
- backendName: "vercel",
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- nodeId: "__root__",
- sourceId: "sandbox/sandbox.ts",
- templatePlan: {
- contentHash: "workspace-hash",
- kind: "bootstrap",
- revalidationKey: "bootstrap-day-1",
- sourceHash: BOOTSTRAP_SOURCE_HASH,
- },
- });
-
- expect(secondKey).toBe(firstKey);
- });
-
- it("ignores VERCEL_TEAM_ID so build-time prewarm and deployed runtime agree", async () => {
- // Vercel has no team system variable at runtime, so a team-scoped key
- // could never be resolved by the deployed function.
- vi.stubEnv("VERCEL_PROJECT_ID", "prj_team_parity");
-
- const input = {
- backendName: "vercel",
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- nodeId: "__root__",
- sourceId: "eve:default-sandbox",
- templatePlan: { contentHash: "workspace-hash", kind: "workspace-content" },
- } as const;
-
- vi.stubEnv("VERCEL_TEAM_ID", "team_build");
- const buildKey = await createRuntimeSandboxTemplateKey(input);
-
- vi.stubEnv("VERCEL_TEAM_ID", "");
- const runtimeKey = await createRuntimeSandboxTemplateKey(input);
-
- expect(runtimeKey).toBe(buildKey);
- });
-
- it("uses source and workspace inputs for bootstrap templates without a revalidation key", async () => {
- vi.stubEnv("VERCEL_PROJECT_ID", "prj_bootstrap");
-
- const firstKey = await createRuntimeSandboxTemplateKey({
- backendName: "vercel",
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- nodeId: "__root__",
- sourceId: "sandbox/sandbox.ts",
- templatePlan: {
- contentHash: "workspace-hash",
- kind: "bootstrap",
- sourceHash: BOOTSTRAP_SOURCE_HASH,
- },
- });
- const secondKey = await createRuntimeSandboxTemplateKey({
- backendName: "vercel",
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- nodeId: "__root__",
- sourceId: "sandbox/sandbox.ts",
- templatePlan: {
- contentHash: "workspace-hash",
- kind: "bootstrap",
- sourceHash: BOOTSTRAP_SOURCE_HASH,
- },
- });
-
- expect(secondKey).toBe(firstKey);
- });
-
- it("changes bootstrap template keys when the revalidation key changes", async () => {
- vi.stubEnv("VERCEL_PROJECT_ID", "prj_bootstrap");
-
- const firstKey = await createRuntimeSandboxTemplateKey({
- backendName: "vercel",
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- nodeId: "__root__",
- sourceId: "sandbox/sandbox.ts",
- templatePlan: {
- contentHash: "workspace-hash",
- kind: "bootstrap",
- revalidationKey: "bootstrap-day-1",
- sourceHash: BOOTSTRAP_SOURCE_HASH,
- },
- });
- const secondKey = await createRuntimeSandboxTemplateKey({
- backendName: "vercel",
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- nodeId: "__root__",
- sourceId: "sandbox/sandbox.ts",
- templatePlan: {
- contentHash: "workspace-hash",
- kind: "bootstrap",
- revalidationKey: "bootstrap-day-2",
- sourceHash: BOOTSTRAP_SOURCE_HASH,
- },
- });
-
- expect(secondKey).not.toBe(firstKey);
- });
-
- it("changes bootstrap template keys when authored sandbox source changes", async () => {
- vi.stubEnv("VERCEL_PROJECT_ID", "prj_bootstrap");
-
- const firstKey = await createRuntimeSandboxTemplateKey({
- backendName: "vercel",
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- nodeId: "__root__",
- sourceId: "sandbox/sandbox.ts",
- templatePlan: {
- contentHash: "workspace-hash",
- kind: "bootstrap",
- revalidationKey: "bootstrap-day-1",
- sourceHash: "bootstrap-source-hash-one",
- },
- });
- const secondKey = await createRuntimeSandboxTemplateKey({
- backendName: "vercel",
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- nodeId: "__root__",
- sourceId: "sandbox/sandbox.ts",
- templatePlan: {
- contentHash: "workspace-hash",
- kind: "bootstrap",
- revalidationKey: "bootstrap-day-1",
- sourceHash: "bootstrap-source-hash-two",
- },
- });
-
- expect(secondKey).not.toBe(firstKey);
- });
-
- it("changes bootstrap template keys when workspace content changes", async () => {
- vi.stubEnv("VERCEL_PROJECT_ID", "prj_bootstrap");
-
- const firstKey = await createRuntimeSandboxTemplateKey({
- backendName: "vercel",
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- nodeId: "__root__",
- sourceId: "sandbox/sandbox.ts",
- templatePlan: {
- contentHash: "workspace-hash-one",
- kind: "bootstrap",
- revalidationKey: "bootstrap-day-1",
- sourceHash: BOOTSTRAP_SOURCE_HASH,
- },
- });
- const secondKey = await createRuntimeSandboxTemplateKey({
- backendName: "vercel",
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- nodeId: "__root__",
- sourceId: "sandbox/sandbox.ts",
- templatePlan: {
- contentHash: "workspace-hash-two",
- kind: "bootstrap",
- revalidationKey: "bootstrap-day-1",
- sourceHash: BOOTSTRAP_SOURCE_HASH,
- },
- });
-
- expect(secondKey).not.toBe(firstKey);
- });
-
- it("changes workspace-content template keys when the content hash changes", async () => {
- vi.stubEnv("VERCEL_PROJECT_ID", "prj_123");
-
- const firstKey = await createRuntimeSandboxTemplateKey({
- backendName: "vercel",
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- nodeId: "__root__",
- sourceId: "eve:default-sandbox",
- templatePlan: { contentHash: "workspace-hash-one", kind: "workspace-content" },
- });
- const secondKey = await createRuntimeSandboxTemplateKey({
- backendName: "vercel",
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- nodeId: "__root__",
- sourceId: "eve:default-sandbox",
- templatePlan: { contentHash: "workspace-hash-two", kind: "workspace-content" },
- });
-
- expect(secondKey).not.toBe(firstKey);
- });
-
- it("returns null for sandboxes that do not need a template", async () => {
- const key = await createRuntimeSandboxTemplateKey({
- backendName: "vercel",
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- nodeId: "__root__",
- sourceId: "eve:default-sandbox",
- templatePlan: { kind: "none" },
- });
-
- expect(key).toBeNull();
- });
-});
diff --git a/packages/eve/test/scenarios/sandbox-workspace-folders.scenario.test.ts b/packages/eve/test/scenarios/sandbox-workspace-folders.scenario.test.ts
index 4d9c36492..6b9fa6b36 100644
--- a/packages/eve/test/scenarios/sandbox-workspace-folders.scenario.test.ts
+++ b/packages/eve/test/scenarios/sandbox-workspace-folders.scenario.test.ts
@@ -7,7 +7,8 @@ import { discoverAgent } from "../../src/discover/discover-agent.js";
import { resolveDiscoveryProject } from "../../src/discover/project.js";
// The just-bash engine keeps this scenario hermetic (no Docker daemon
// requirement); the workspace devDependency provides the install.
-import { createJustBashSandboxBackend } from "../../src/execution/sandbox/bindings/just-bash.js";
+import { createJustBashSandboxProvider } from "../../src/execution/sandbox/bindings/just-bash.js";
+import { createSandboxProviderHarness } from "../../src/internal/testing/sandbox-provider-harness.js";
import { useScenarioApp } from "../../src/internal/testing/scenario-app.js";
import { SANDBOX_WORKSPACES_DESCRIPTOR } from "../../src/internal/testing/scenario-apps/sandbox-workspaces.js";
import { materializeWorkspaceDirectory } from "../../src/runtime/workspace/seed-files.js";
@@ -38,64 +39,60 @@ describe("sandbox workspace folder convention", () => {
).flat();
const appRoot = await createScratchDirectory("eve-sandbox-workspace-folders-");
- const backend = createJustBashSandboxBackend();
+ const backend = createSandboxProviderHarness(createJustBashSandboxProvider(), undefined);
- await backend.prewarm({
- runtimeContext: { appRoot },
+ await backend.prepare({
+ appRoot,
seedFiles: files.map((file) => ({ content: file.content, path: file.path })),
- templateKey: "template-default-workspace",
});
- const handle = await backend.create({
- runtimeContext: { appRoot },
- sessionKey: "session-default-workspace",
- templateKey: "template-default-workspace",
+ const handle = await backend.openSession({
+ appRoot,
+ sandboxName: "session-default-workspace",
});
- const notesContent = await handle.session.readTextFile({ path: "/workspace/notes.md" });
+ const notesContent = await handle.sandbox.readTextFile({ path: "/workspace/notes.md" });
expect(notesContent).not.toBeNull();
- expect(handle.session.resolvePath("/workspace/notes.md")).toBe("/workspace/notes.md");
- expect(handle.session.resolvePath("notes.md")).toBe("/workspace/notes.md");
+ expect(handle.sandbox.resolvePath("/workspace/notes.md")).toBe("/workspace/notes.md");
+ expect(handle.sandbox.resolvePath("notes.md")).toBe("/workspace/notes.md");
// Missing files resolve to `null` instead of throwing.
- const missing = await handle.session.readTextFile({ path: "/workspace/does-not-exist.txt" });
+ const missing = await handle.sandbox.readTextFile({ path: "/workspace/does-not-exist.txt" });
expect(missing).toBeNull();
// writeFile round-trip: the session can layer a new file on top of
// the seeded workspace without running a shell command.
- await handle.session.writeTextFile({ content: "round-trip", path: "/workspace/authored.txt" });
- const roundTrip = await handle.session.readTextFile({ path: "/workspace/authored.txt" });
+ await handle.sandbox.writeTextFile({ content: "round-trip", path: "/workspace/authored.txt" });
+ const roundTrip = await handle.sandbox.readTextFile({ path: "/workspace/authored.txt" });
expect(roundTrip).toBe("round-trip");
- await handle.shutdown();
+ await handle.onRuntimeShutdown();
});
it("opens an empty prewarmed template when the sandbox has no authored workspace files", async () => {
const appRoot = await createScratchDirectory("eve-sandbox-no-workspace-");
- const backend = createJustBashSandboxBackend();
+ const backend = createSandboxProviderHarness(createJustBashSandboxProvider(), undefined);
- await backend.prewarm({
- runtimeContext: { appRoot },
+ await backend.prepare({
+ appRoot,
seedFiles: [],
- templateKey: "template-empty-workspace",
});
- const handle = await backend.create({
- runtimeContext: { appRoot },
- sessionKey: "session-empty-workspace",
- templateKey: "template-empty-workspace",
+ const handle = await backend.openSession({
+ appRoot,
+ sandboxName: "session-empty-workspace",
});
// An empty prewarmed template snapshots a clean `/workspace` and
// nothing else; the session opens against it without writing
// anything visible at the workspace root.
- const result = await handle.session.run({
+ const result = await handle.sandbox.run({
command: "ls /workspace 2>/dev/null | wc -l",
});
expect(result.exitCode).toBe(0);
expect(Number(result.stdout.trim())).toBe(0);
- await handle.shutdown();
+ await handle.onRuntimeShutdown();
});
it("materializes a fixture default workspace folder into a deterministic file list", async () => {
diff --git a/packages/eve/test/scenarios/vercel-build-prewarm.scenario.test.ts b/packages/eve/test/scenarios/vercel-build-prewarm.scenario.test.ts
index b0b267221..6d0acf947 100644
--- a/packages/eve/test/scenarios/vercel-build-prewarm.scenario.test.ts
+++ b/packages/eve/test/scenarios/vercel-build-prewarm.scenario.test.ts
@@ -6,12 +6,8 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { compileAgent } from "../../src/compiler/compile-agent.js";
import { prewarmAppSandboxes } from "../../src/execution/sandbox/prewarm.js";
import { runVercelBuildPrewarm } from "../../src/internal/nitro/host/vercel-build-prewarm.js";
-import type {
- SandboxBackendPrewarmInput,
- SandboxBackendPrewarmResult,
-} from "../../src/public/definitions/sandbox-backend.js";
+import type { SandboxProviderPrepareContext } from "../../src/shared/sandbox-provider.js";
import { useTemporaryDirectories } from "../../src/internal/testing/use-temporary-app-roots.js";
-import { stubSpawnProcess } from "../_helpers/sandbox-session-stub.js";
const createScratchDirectory = useTemporaryDirectories();
@@ -21,53 +17,6 @@ describe("Vercel build-time sandbox prewarm", () => {
vi.unstubAllEnvs();
});
- it("prewarms root and subagent sandbox templates without running onSession", async () => {
- vi.stubEnv("VERCEL", "1");
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_test_build_prewarm");
-
- const appRoot = await createScenarioAppRoot();
- const events = createPrewarmEvents();
- const log = vi.fn();
-
- await compileAgent({
- startPath: appRoot,
- });
- await prewarmAppSandboxes({
- appRoot,
- log,
- dispatch: createRecordingDispatch(events),
- });
-
- expect(events.templateKeys).toHaveLength(2);
- expect(events.templateKeys.every((templateKey) => templateKey.startsWith("eve-sbx-tpl-"))).toBe(
- true,
- );
- expect([...events.commands].sort()).toEqual(["echo child-bootstrap", "echo root-bootstrap"]);
- expect(log.mock.calls.map(([message]) => message)).toEqual([
- "eve: initializing 2 sandbox templates...",
- "eve: initialized 2 sandbox templates (0 reused, 2 built).",
- ]);
- });
-
- it("fails the hosted build when sandbox bootstrap fails during prewarm", async () => {
- vi.stubEnv("VERCEL", "1");
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "");
- vi.stubEnv("VERCEL_OIDC_TOKEN", createVercelOidcToken("prj_hosted_build"));
-
- const appRoot = await createScenarioAppRoot();
-
- await compileAgent({
- startPath: appRoot,
- });
-
- await expect(
- runVercelBuildPrewarm({
- appRoot,
- dispatch: createFailingBootstrapDispatch(),
- }),
- ).rejects.toThrow("bootstrap command failed");
- });
-
it("skips sandbox prewarm outside a Vercel build", async () => {
await expect(
runVercelBuildPrewarm({
@@ -96,23 +45,6 @@ describe("Vercel build-time sandbox prewarm", () => {
);
});
- it("allows a Vercel build without OIDC when no sandbox template is required", async () => {
- vi.stubEnv("VERCEL", "1");
- vi.stubEnv("VERCEL_OIDC_TOKEN", "");
-
- const appRoot = await createTemplateFreeScenarioAppRoot();
-
- await compileAgent({
- startPath: appRoot,
- });
-
- await expect(
- runVercelBuildPrewarm({
- appRoot,
- }),
- ).resolves.toBe(true);
- });
-
it("prewarms sandbox templates for a local Vercel build without a deployment id", async () => {
vi.stubEnv("VERCEL", "1");
vi.stubEnv("VERCEL_DEPLOYMENT_ID", "");
@@ -166,21 +98,6 @@ function createVercelOidcToken(projectId: string): string {
return `header.${payload}.signature`;
}
-async function createTemplateFreeScenarioAppRoot(): Promise<string> {
- const appRoot = await createScratchDirectory("eve-vercel-build-without-prewarm-");
- const agentRoot = join(appRoot, "agent");
-
- await mkdir(agentRoot, { recursive: true });
- await writeFile(
- join(appRoot, "package.json"),
- JSON.stringify({ name: "vercel-build-without-prewarm", type: "module" }, null, 2),
- );
- await writeFile(join(agentRoot, "agent.ts"), 'export default { model: "openai/gpt-5.4" };\n');
- await writeFile(join(agentRoot, "instructions.md"), "Root system prompt.\n");
-
- return appRoot;
-}
-
async function createScenarioAppRoot(
input: { readonly withSkills?: boolean } = {},
): Promise<string> {
@@ -223,19 +140,7 @@ async function createScenarioAppRoot(
}
await writeFile(
join(agentRoot, "sandbox", "sandbox.ts"),
- [
- "export default {",
- ' revalidationKey: () => "root-bootstrap-v1",',
- " async bootstrap({ use }) {",
- " const sandbox = await use();",
- ' await sandbox.run({ command: "echo root-bootstrap" });',
- " },",
- " onSession() {",
- ' throw new Error("root onSession should not run during build prewarm");',
- " },",
- "};",
- "",
- ].join("\n"),
+ preparedSandboxSource("echo root-bootstrap"),
);
await writeFile(
join(subagentRoot, "agent.ts"),
@@ -256,116 +161,42 @@ async function createScenarioAppRoot(
}
await writeFile(
join(subagentRoot, "sandbox", "sandbox.ts"),
- [
- "export default {",
- ' revalidationKey: () => "child-bootstrap-v1",',
- " async bootstrap({ use }) {",
- " const sandbox = await use();",
- ' await sandbox.run({ command: "echo child-bootstrap" });',
- " },",
- " onSession() {",
- ' throw new Error("child onSession should not run during build prewarm");',
- " },",
- "};",
- "",
- ].join("\n"),
+ preparedSandboxSource("echo child-bootstrap"),
);
return appRoot;
}
-function createRecordingDispatch(events: ReturnType<typeof createPrewarmEvents>) {
- return async ({
- input,
- }: {
- input: SandboxBackendPrewarmInput;
- }): Promise<SandboxBackendPrewarmResult> => {
- events.templateKeys.push(input.templateKey);
-
- const seedFiles = input.seedFiles ?? [];
- if (seedFiles.length > 0) {
- events.seededTemplates.push("default");
- events.writtenFilePaths.push(...seedFiles.map((file) => file.path));
- }
-
- if (input.bootstrap !== undefined) {
- await input.bootstrap({
- use: async () => ({
- id: input.templateKey,
- async readFile() {
- return null;
- },
- async readBinaryFile() {
- return null;
- },
- async readTextFile() {
- return null;
- },
- async setNetworkPolicy() {},
- async removePath() {},
- resolvePath(path: string) {
- return path;
- },
- async run({ command }: { command: string }) {
- events.commands.push(command);
- return {
- exitCode: 0,
- stderr: "",
- stdout: "",
- };
- },
- async spawn() {
- return stubSpawnProcess();
- },
- async writeFile() {},
- async writeBinaryFile() {},
- async writeTextFile() {},
- }),
- });
- }
-
- return { reused: false };
- };
+function preparedSandboxSource(command: string): string {
+ return [
+ 'import { DefaultSandbox, defineSandbox } from "eve/sandbox";',
+ "export const environment = DefaultSandbox.environment({",
+ " prepare: async (sandbox) => {",
+ ` await sandbox.run({ command: ${JSON.stringify(command)} });`,
+ " },",
+ "});",
+ "export default defineSandbox(() => environment.open());",
+ "",
+ ].join("\n");
}
-function createFailingBootstrapDispatch() {
- return async ({
- input,
- }: {
- input: SandboxBackendPrewarmInput;
- }): Promise<SandboxBackendPrewarmResult> => {
- if (input.bootstrap !== undefined) {
- await input.bootstrap({
- use: async () => ({
- id: input.templateKey,
- async readFile() {
- return null;
- },
- async readBinaryFile() {
- return null;
- },
- async readTextFile() {
- return null;
- },
- async setNetworkPolicy() {},
- async removePath() {},
- resolvePath(path: string) {
- return path;
- },
- async run() {
- throw new Error("bootstrap command failed");
- },
- async spawn() {
- return stubSpawnProcess();
- },
- async writeFile() {},
- async writeBinaryFile() {},
- async writeTextFile() {},
- }),
- });
+function createRecordingDispatch(events: ReturnType<typeof createPrewarmEvents>) {
+ return async ({ context }: { context: SandboxProviderPrepareContext }) => {
+ events.templateKeys.push(context.storagePath);
+ const files = [
+ ...(context.resources.workspace?.files.map((file) => ({
+ path: `${context.resources.workspace?.targetPath}/${file.relativePath}`,
+ })) ?? []),
+ ...(context.resources.skills?.files.map((file) => ({
+ path: `${context.resources.skills?.targetPath}/${file.relativePath}`,
+ })) ?? []),
+ ];
+ if (files.length > 0) {
+ events.seededTemplates.push("default");
+ events.writtenFilePaths.push(...files.map((file) => file.path));
}
- return { reused: false };
+ return { storagePath: context.storagePath };
};
}
diff --git a/packages/eve/test/tui-client/lib/server.ts b/packages/eve/test/tui-client/lib/server.ts
index 9b17df835..877a54b93 100644
--- a/packages/eve/test/tui-client/lib/server.ts
+++ b/packages/eve/test/tui-client/lib/server.ts
@@ -250,7 +250,7 @@ async function waitForAgentServer(input: {
/** Reads the agent name from a versioned `/eve/v1/info` response. */
export function getAgentNameFromInfoPayload(payload: unknown): string | undefined {
- if (!isRecord(payload) || payload.kind !== "eve-agent-info" || payload.version !== 4) {
+ if (!isRecord(payload) || payload.kind !== "eve-agent-info" || payload.version !== 5) {
return undefined;
}
diff --git a/packages/eve/test/vercel/vercel-sandbox-bundling.vercel.test.ts b/packages/eve/test/vercel/vercel-sandbox-bundling.vercel.test.ts
index 28fdf50f1..329b0252e 100644
--- a/packages/eve/test/vercel/vercel-sandbox-bundling.vercel.test.ts
+++ b/packages/eve/test/vercel/vercel-sandbox-bundling.vercel.test.ts
@@ -47,9 +47,9 @@ describe.sequential("sandbox-bundling Vercel deployment integration", () => {
async () => {
// Reaching this point already proves the deployed function evaluated
// its top-level module graph without crashing: the hosted bundle must
- // prune the local sandbox backend (Docker engine + optional just-bash
- // engine) via the sandbox-backend prune plugin, and resolve the Vercel
- // backend's vendored `@vercel/sandbox` chunk. The end-to-end message
+ // prune the local sandbox providers (Docker engine + optional just-bash
+ // engine) via the sandbox execution-adapter plugin and resolve the Vercel
+ // provider's vendored `@vercel/sandbox` chunk. The end-to-end message
// round-trip then confirms the framework runtime path is wired up and
// the response stream completes.
if (deploymentFixture === undefined) {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index fbef76099..7991100fa 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1006,6 +1006,31 @@ importers:
specifier: 'catalog:'
version: 7.0.2
+ e2e/fixtures/agent-microsandbox-dockerfile:
+ dependencies:
+ '@eve-e2e/config':
+ specifier: workspace:*
+ version: link:../e2e-config
+ '@workflow/world-postgres':
+ specifier: 'catalog:'
+ eve:
+ specifier: workspace:*
+ version: link:../../../packages/eve
+ microsandbox:
+ specifier: 0.5.5
+ version: 0.5.5
+ zod:
+ specifier: 'catalog:'
+ version: 4.5.4
+ devDependencies:
+ '@types/node':
+ specifier: 'catalog:'
+ version: 24.13.3
+ typescript:
+ specifier: 'catalog:'
+ version: 7.0.2
+
e2e/fixtures/agent-model:
dependencies:
'@eve-e2e/config':
diff --git a/research/authored-sandbox-stop.md b/research/authored-sandbox-stop.md
index 239b12905..8dc7eaced 100644
--- a/research/authored-sandbox-stop.md
+++ b/research/authored-sandbox-stop.md
@@ -48,19 +48,19 @@ flowchart LR
Parked --> Resume["Later callback reopens"]
```
-- Each built-in backend maps `stop()` to its native lifecycle operation:
+- Each built-in provider maps `stop()` to its native lifecycle operation:
Vercel stops its persistent sandbox, Docker stops its session container,
microsandbox stops and detaches its VM, and just-bash disposes its interpreter.
- A resolved stop preserves the durable session state. A later callback opens
- the same session through the normal backend `create()` path. Vercel also
+ the same session through the provider's normal `open()` path. Vercel also
automatically resumes the same handle on later I/O, matching its inactivity
timeout behavior.
- eve does not create stop-specific reconnect state. Ordinary step persistence
- continues recording the backend's existing reconnect metadata.
+ continues recording the provider's existing reconnect metadata.
- A provider stop failure rejects the authored call. Server-shutdown cleanup
remains a separate best-effort lifecycle path.
-- Custom `SandboxBackend` handles implement `stop()` alongside `shutdown()` so
- the runtime session contract is supported by every provider.
+- Custom `defineSandboxProvider()` handles implement `stop()` alongside
+ `shutdown()` so the runtime session contract is supported by every provider.
## Scope
diff --git a/research/programmatic-agent-sources.md b/research/programmatic-agent-sources.md
index 6258196c6..56366d1dd 100644
--- a/research/programmatic-agent-sources.md
+++ b/research/programmatic-agent-sources.md
@@ -577,24 +577,24 @@ compilation use the same composer and normalizers as production.
After migration, the framework provides exactly these default identities
through source composition:
-| Identity | Definition | Registered for | Notes |
-| ---------------------------- | -------------------------------------- | ---------------- | --------------------------------------------------------------------- |
-| `agent.ts` | `defineAgent` | every local node | default model config; phase-one composition |
-| `sandbox.ts` | `defineSandbox({})` | every local node | selects `defaultSandbox()`; stable semantic revision |
-| `tools/bash.ts` | `defineTool` | every local node | ordinary executor |
-| `tools/read_file.ts` | `defineTool` | every local node | ordinary executor |
-| `tools/write_file.ts` | `defineTool` | every local node | ordinary executor |
-| `tools/todo.ts` | `defineTool` | every local node | ordinary executor |
-| `tools/web_fetch.ts` | `defineTool` | every local node | ordinary executor |
-| `tools/load_skill.ts` | `defineTool` | every local node | ordinary executor |
-| `tools/connection_search.ts` | `defineDynamic` | every local node | discovers and qualifies connection tools |
-| `tools/ask_question.ts` | internal native tool + `request-input` | every local node | visibility: `requires-request-input` |
-| `tools/agent.ts` | internal native tool + `dispatch` | root node | action: `subagent-call`; visibility: `root-session` |
-| `tools/task_update.ts` | internal native tool + `dispatch` | root node | action: `task-update`; tasks mode; visibility: `delegated-task-child` |
-| `tools/task_cancel.ts` | internal native tool + `dispatch` | root node | action: `task-cancel`; tasks mode; visibility: `root-session` |
-| `tools/web_search.ts` | `webSearch` sentinel + `provider-tool` | every local node | materialized at eligible model calls |
-| `channels/eve.ts` | `eveChannel` factory | root node | complete `/eve/v1` surface: protocol, callbacks, health, info |
-| `channels/home.ts` | `defineChannel` | root node | `GET` and `HEAD` at `/` |
+| Identity | Definition | Registered for | Notes |
+| ---------------------------- | ----------------------------------------- | ---------------- | --------------------------------------------------------------------- |
+| `agent.ts` | `defineAgent` | every local node | default model config; phase-one composition |
+| `sandbox.ts` | `defineSandbox(() => environment.open())` | every local node | exports `DefaultSandbox.environment()`; stable semantic revision |
+| `tools/bash.ts` | `defineTool` | every local node | ordinary executor |
+| `tools/read_file.ts` | `defineTool` | every local node | ordinary executor |
+| `tools/write_file.ts` | `defineTool` | every local node | ordinary executor |
+| `tools/todo.ts` | `defineTool` | every local node | ordinary executor |
+| `tools/web_fetch.ts` | `defineTool` | every local node | ordinary executor |
+| `tools/load_skill.ts` | `defineTool` | every local node | ordinary executor |
+| `tools/connection_search.ts` | `defineDynamic` | every local node | discovers and qualifies connection tools |
+| `tools/ask_question.ts` | internal native tool + `request-input` | every local node | visibility: `requires-request-input` |
+| `tools/agent.ts` | internal native tool + `dispatch` | root node | action: `subagent-call`; visibility: `root-session` |
+| `tools/task_update.ts` | internal native tool + `dispatch` | root node | action: `task-update`; tasks mode; visibility: `delegated-task-child` |
+| `tools/task_cancel.ts` | internal native tool + `dispatch` | root node | action: `task-cancel`; tasks mode; visibility: `root-session` |
+| `tools/web_search.ts` | `webSearch` sentinel + `provider-tool` | every local node | materialized at eligible model calls |
+| `channels/eve.ts` | `eveChannel` factory | root node | complete `/eve/v1` surface: protocol, callbacks, health, info |
+| `channels/home.ts` | `defineChannel` | root node | `GET` and `HEAD` at `/` |
Every identity above is replaceable and disableable through ordinary slot
composition. `glob` and `grep` are published at `eve/tools/glob` and
@@ -755,11 +755,11 @@ long qualified names, and persisted callback identity remain unchanged.
### Default sandbox
-Register a public `defineSandbox({})` value at `sandbox.ts` for all local nodes.
-An authored `sandbox.ts` replaces it through normal source composition. The
-standard semantics of a selected sandbox definition with no explicit backend
-still choose `defaultSandbox()` for the current environment, but graph
-resolution never invents a framework sandbox. Every successfully compiled
+Register a public `defineSandbox(() => environment.open())` value and exported
+`DefaultSandbox.environment()` at `sandbox.ts` for all local nodes. An authored
+`sandbox.ts` replaces both through normal source composition. Provider selection
+belongs to the exported environment; graph resolution never invents a framework
+sandbox. Every successfully compiled
local node contains exactly one selected sandbox with a source ID and binding;
disabling the only candidate cannot be repaired by a runtime fallback.
diff --git a/research/sandbox-environments-open.md b/research/sandbox-environments-open.md
new file mode 100644
index 000000000..26b6ebd63
--- /dev/null
+++ b/research/sandbox-environments-open.md
@@ -0,0 +1,200 @@
+---
+issue: TBD
+status: draft
+last_updated: "2026-09-16"
+---
+
+# Sandbox environments and provider sessions
+
+## Decision
+
+Authors configure an immutable provider environment, then open its sandbox for the current eve session:
+
+```ts
+export const environment = VercelSandbox.environment({
+ prepare: async (sandbox) => {
+ await sandbox.run({ command: "pnpm install --frozen-lockfile" });
+ },
+});
+
+export default defineSandbox(async ({ session }) => {
+ const sandbox = await environment.open({ networkPolicy: "deny-all" });
+ await sandbox.writeTextFile({ path: ".eve/session", content: session.id });
+ return sandbox;
+});
+```
+
+`environment.open()` returns the exact `RuntimeSandboxSession` selected by the sandbox definition. It is the only author-facing environment operation.
+
+## Provider-owned options and hooks
+
+Environment configuration and live options are single provider-owned objects. Core passes them unchanged and never reserves, injects, extracts, or interprets fields such as `prepare`.
+
+Omission remains `undefined`. Providers normalize optional input themselves. Objects with required fields remain required; positional arguments are not supported.
+
+Providers own callback names, argument types, ordering, and lifecycle timing. A snapshot provider may expose `prepare(sandbox)`. A custom provider may expose a start-only callback in its open options. Built-in providers instead initialize the live sandbox in `defineSandbox()` after `open()`. Dockerfile image providers expose no authored preparation callback when immutable setup belongs in the Dockerfile.
+
+Provider callbacks and runtime callback arguments are never stored in prepared artifacts. Provider-defined session-hook return values may enter serialized provider session state only when `resume()` needs them.
+
+## Public sandbox sessions
+
+`SandboxSession` is an I/O-only surface used by preparation and provider-defined session hooks. It contains process and file operations and eve-owned `resolvePath()`. Providers express additional capabilities in their exact session type. It has no `id`, `stop()`, or `delete()`.
+
+`environment.open()` returns the provider-specific session type plus `stop()` and `delete()`. Core erases that exact type only at the heterogeneous runtime registry boundary.
+
+Authors use `ctx.session.id` for durable eve identity. Provider-native IDs and core artifact keys remain private. `resolvePath()` remains unchanged: relative paths resolve beneath `/workspace`, and absolute paths pass through.
+
+`setNetworkPolicy()` is required on the session types returned by dedicated Vercel, Docker, and microsandbox environments. just-bash and providers that reuse one native network boundary omit it from their session types and require policy at creation time.
+
+## Provider contract
+
+```ts
+interface SandboxProviderImplementation<OpenOptions, Artifact, SessionState, Session> {
+ prepare(context: SandboxProviderPrepareContext): Promise<Artifact>;
+
+ start(
+ context: SandboxProviderSessionContext,
+ options: Readonly<OpenOptions> | undefined,
+ artifact: Readonly<Artifact>,
+ ): Promise<{
+ handle: SandboxProviderHandle<Session>;
+ state: SessionState;
+ }>;
+
+ resume(
+ context: SandboxProviderSessionContext,
+ artifact: Readonly<Artifact>,
+ state: Readonly<SessionState>,
+ ): Promise<SandboxProviderHandle<Session>>;
+}
+
+interface SandboxProviderSessionContext {
+ readonly session: SandboxSelectorContext["session"];
+ readonly storagePath: string;
+}
+
+interface SandboxProviderHandle<Session> {
+ readonly sandbox: Session;
+ onSessionStop(): Promise<void>;
+ onRuntimeShutdown(): Promise<void>;
+ onSessionDelete(options?: SandboxDeleteOptions): Promise<void>;
+}
+```
+
+`Artifact` and `SessionState` are JSON-compatible provider-owned types. Core erases exact types only at the heterogeneous runtime registry boundary.
+
+### Preparation
+
+`prepare()` is mandatory and returns only the complete artifact. A provider with no build work may return `null`. Cache reuse is provider logging, not shared return data.
+
+Managed workspace and skills are available only during preparation. The artifact captures their files or exact provider references. Runtime never rebuilds, rehydrates, repairs, or reinterprets build inputs.
+
+Core keeps its artifact storage key private and passes the artifact directly to `start()` and `resume()`. There is no `base | prepared` source union.
+
+### Provider-discovered files
+
+Preparation context exposes a tracked filesystem scoped to the authored sandbox directory:
+
+```ts
+interface SandboxProviderFiles {
+ list(): Promise<readonly string[]>;
+ read(path: string): Promise<Uint8Array>;
+ readText(path: string): Promise<string>;
+}
+```
+
+Providers discover their own Dockerfiles and build contexts through this surface. Core tracks, hashes, and watches reads. Providers do not receive the application root for authored file discovery.
+
+Provider contexts expose `storagePath` for private caches, local VM state, and temporary files. Core owns project layout.
+
+### Start and resume
+
+Core evaluates `defineSandbox()` and calls `start()` when no serialized provider session state exists. After initialization succeeds, core checkpoints the selected provider and state. Later workflow steps and process restarts bypass the selector and call `resume()` directly. Failed initial selector code deletes the newly started handle and leaves no durable state, so a later access can retry initialization.
+
+`start()` receives provider-owned open options and the exact artifact. `resume()` receives only the current session context, the target deployment's exact artifact, and persisted provider state. Open options and callbacks are never serialized or reconstructed by core. Credentials, clients, fetch implementations, and signals needed for lookup belong to environment/provider configuration rather than start-only open options. A provider must include any immutable option-derived data needed for reconnection in its own JSON-compatible state.
+
+Provider state is immutable after `start()` in this contract. `resume()` reconnects or restarts persisted native state but does not recreate missing native compute from unavailable callbacks. If native state is gone, resume fails. Deletion clears provider state; the next access evaluates the selector and starts again.
+
+During deployment handoff, the target provider validates state against its current implementation and artifact. Incompatibility rejects activation, leaving the existing owner on its current deployment. Core does not persist old artifacts or migrate provider state.
+
+### Minimal session state
+
+Provider session state contains only values that cannot be cheaply and deterministically recovered, such as an opaque platform ID. It does not duplicate prepared artifacts, credentials, clients, callbacks, or derivable hashes. It may contain immutable option-derived values required for direct resume. Providers version and validate their state in `resume()`.
+
+Provider state is returned only by `start()` and is immutable for the durable session. Handles do not expose a later state-capture operation or create/restore union.
+
+### Lifecycle hooks
+
+Provider-handle hooks describe the eve event, not a required native effect:
+
+- `onSessionStop()` handles authored `sandbox.stop()` while preserving provider session state.
+- `onRuntimeShutdown()` releases a process-local attachment without changing durable state.
+- `onSessionDelete()` handles authored deletion; core clears provider state after it succeeds.
+
+Dedicated providers normally map these hooks to native stop or delete. Providers that reuse native resources map them to logical detachment. Core has no native ownership flag or provider-owned lifetime branch.
+
+## Native identity
+
+Core does not derive provider instance keys or native names. Each provider derives identity from the inputs it owns.
+
+Dedicated providers include `session.id`:
+
+```text
+session ID
++ validated artifact
++ immutable environment options
++ serialized immutable open-option identity
++ provider contract version
+→ native identity
+```
+
+A reused provider excludes the eve session ID:
+
+```text
+validated artifact
++ immutable environment options
++ provider contract version
+→ reused native identity
+```
+
+Identity derivation excludes credentials, signals, clients, callbacks, logs, and mutable turn data. Providers canonicalize supported values and reject unsupported non-serializable identity inputs.
+
+Core does not expose a universal generation or revalidation field. It does not pass its internal artifact key to providers. Compatibility is the provider-derived identity; no `sandboxConfig` or second provider manifest is added.
+
+## Dedicated Vercel behavior
+
+The Vercel provider retains the useful pre-redesign behavior inside its own implementation:
+
+1. `start()` derives a deterministic native name from `session.id`, the validated artifact, environment options, open options, and a Vercel contract version.
+2. It looks up that name and creates only when absent.
+3. The selector initializes the live sandbox after `open()` before returning it.
+4. It returns immutable state such as `{ version: 1, sandboxName }`.
+5. `resume()` looks up that name directly from state. If native compute is missing, resume fails rather than recreating callback side effects.
+
+Snapshot-unavailable replacement behavior remains provider-owned. No author controls the native name.
+
+## Reused providers
+
+Cross-session native reuse is not a core feature. A custom provider may derive native identity without `session.id` while returning one session-owned logical view per eve session.
+
+The experimental reused Vercel provider uses the same prepared image and Drive mechanics but has a distinct provider contract. It exposes immutable shared network policy and no mutable `setNetworkPolicy()`. Its lifecycle hooks do not tear down native compute used by other sessions.
+
+Concurrent creation, initialization recovery, attachment accounting, active-handle deduplication, and garbage collection remain provider implementation details. Core tracks one logical handle per eve session.
+
+## Default selection
+
+`defineSandboxProvider()` has one implementation contract and no `select` escape hatch. `DefaultSandbox` is an explicit facade that probes the host and returns a concrete Vercel, Docker, microsandbox, or just-bash environment. Every concrete provider uses `defineSandboxProvider()`.
+
+Core exposes no public environment `kind`. Providers discover their own preparation inputs through the tracked filesystem.
+
+## Observable invariants
+
+- Authors use only `environment.open(options)`.
+- Environment and open options are provider-owned single objects; omission remains `undefined`.
+- Core invokes provider `prepare()`, `start()`, and `resume()` directly.
+- Prepared artifacts are immutable, complete, and consumed directly at runtime.
+- A successfully initialized selector runs once; resume bypasses it and may repeat across process restarts.
+- Provider session state is immutable, minimal, JSON-compatible, and provider-validated.
+- Existing sessions retain their pinned generation across deployment handoff or remain on the old deployment when incompatible.
+- Core contains no provider-native identity, sharing, ownership, or repair branch.
+- Public sandbox sessions expose operations rather than provider or core identity.
diff --git a/scripts/guard-invariants.mjs b/scripts/guard-invariants.mjs
index 22b650c3c..86c1dc12e 100644
--- a/scripts/guard-invariants.mjs
+++ b/scripts/guard-invariants.mjs
@@ -109,6 +109,10 @@
* executor. The generic inbox and state cursor must not
* 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
+ * orchestration, registries, key derivation, or session state.
+ * Built-ins and authored providers must share one contract.
*
* Baselines for rules with pre-existing violations live in
* `guard-invariants-baseline.json`. Counts and allowlists in that file
@@ -1354,6 +1358,43 @@ function diffCounts(current, baseline) {
// ---------- Entry point ----------
+async function checkRule44SandboxProviders() {
+ const providerNames = ["docker", "just-bash", "microsandbox", "vercel"];
+ const forbidden = [
+ "#execution/sandbox/ensure.js",
+ "#execution/sandbox/prewarm.js",
+ "#runtime/sandbox/registry.js",
+ "#sandbox/state.js",
+ ];
+ const issues = [];
+ 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")) {
+ issues.push({
+ file,
+ message: "Built-in sandbox providers must use defineSandboxProvider().",
+ });
+ }
+ if (source.includes("createSandboxEnvironment")) {
+ issues.push({
+ file,
+ message:
+ "Built-in sandbox providers must not bypass defineSandboxProvider() through createSandboxEnvironment().",
+ });
+ }
+ for (const specifier of forbidden) {
+ if (source.includes(specifier)) {
+ issues.push({
+ file,
+ message: `Built-in sandbox providers may not bypass the provider contract through ${specifier}.`,
+ });
+ }
+ }
+ }
+ return issues;
+}
+
async function main() {
const baselineRaw = await readFile(BASELINE_PATH, "utf8");
const baseline = JSON.parse(baselineRaw);
@@ -1493,6 +1534,11 @@ async function main() {
violations.push(...state.rule43);
violations.push(...state.rule44);
+ // Rule 44
+ for (const issue of await checkRule44SandboxProviders()) {
+ violations.push({ rule: 44, ...issue });
+ }
+
if (violations.length === 0) {
process.stdout.write("[eve:guard:invariants] ok — all mechanical lints passed.\n");
return;