Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve)!: make sandbox provider start an upsert keyed by the session (#5132)

Andrew Barba3f698dda36bf
diff --git a/.changeset/sandbox-upsert-contract.md b/.changeset/sandbox-upsert-contract.md
new file mode 100644
index 000000000..cd652a7bc
--- /dev/null
+++ b/.changeset/sandbox-upsert-contract.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+Sandbox providers now key each sandbox by its session: `start()` must return the existing sandbox for `ctx.session.id` when one exists, and the required `onSessionEnd(ctx, state | null, { reason })` takes no artifact and must delete by key when `state` is `null`. Session end now removes a sandbox even when the session never recorded it, such as one a subagent sharing the sandbox opened first. Built-in providers keep a session's sandbox across rebuilds and open-option changes.
diff --git a/docs/channels/mcp.mdx b/docs/channels/mcp.mdx
index 9545eacc3..fba795e7d 100644
--- a/docs/channels/mcp.mdx
+++ b/docs/channels/mcp.mdx
@@ -308,13 +308,13 @@ Tool sessions need an authenticated caller. With `auth: none()` every request is
In a tool session:
- The sandbox opens on the first `ctx.getSandbox()` and is kept for later calls with the same key. Concurrent first calls share one sandbox.
-- The sandbox belongs to the agent's current sandbox definition. A deploy that changes it (the template, its snapshot, or the open options in `sandbox.ts` and its resources) starts a fresh, empty sandbox for the same key; the old one expires as below.
+- The sandbox is found from the session id alone. A deploy that changes the sandbox definition (the template, its snapshot, the open options in `sandbox.ts`, or its resources) keeps using the existing sandbox for the key; the current definition applies only when a sandbox is created, such as after the old one expires as below. Deployments that share a sandbox namespace, such as preview and production deployments of one Vercel project, also share the sandbox for the same principal and key.
- `ctx.session.id` is the same for every call with the key.
- Traces still show each call as its own run. Its `agent.run.id` and `gen_ai.conversation.id` are a fresh id for that call, not `ctx.session.id`, so traces do not link calls that share a key.
- Authored state still starts from its initial value on every call, and updates are not kept. Keep data that must outlive a call in the sandbox.
- Calls may still run in parallel, and nothing orders them.
-Tool sessions need a sandbox provider that finds the session's sandbox again: Vercel Sandbox or just-bash. On another provider, a call with a key fails with a `Sandbox provider "<name>" cannot keep a sandbox between invokeTool calls` error when the tool opens its sandbox. Tools that never open a sandbox still run. just-bash keeps its sandboxes on the local disk, so on Vercel Functions a just-bash tool session lasts only as long as the function instance.
+Tool sessions need a sandbox provider whose kept sandboxes stay bounded: Vercel Sandbox or just-bash. On another provider, a call with a key fails with a `Sandbox provider "<name>" cannot keep a sandbox between invokeTool calls` error when the tool opens its sandbox. Tools that never open a sandbox still run. just-bash keeps its sandboxes on the local disk, so on Vercel Functions a just-bash tool session lasts only as long as the function instance.
A tool session has no end, so eve bounds how long its sandbox is kept. On Vercel Sandbox, a tool-session sandbox's saved filesystem expires a day after its last use, and each call that resumes it restarts that day. The next call with the key after that replaces it with a fresh, empty sandbox. If two calls with the key find the expired filesystem at the same time, each can replace the sandbox, and files the first one writes can be lost. Vercel only keeps the latest snapshot of the sandbox. Tool sessions use this one-day expiry whatever `snapshotExpiration` `sandbox.ts` sets; sessions that conversations start keep the authored setting.
diff --git a/docs/sandbox/index.mdx b/docs/sandbox/index.mdx
index 601a56f99..e88fd4acd 100644
--- a/docs/sandbox/index.mdx
+++ b/docs/sandbox/index.mdx
@@ -54,7 +54,7 @@ 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:
+Pass options for the live sandbox to `open()`, then configure the returned sandbox before returning it. `open()` applies its options only when it creates the sandbox. Initialization can run more than once against the same sandbox, for example when a subagent that shares the sandbox opens it before the parent does, or on the next access after an initialization that failed. Make it safe to repeat:
```ts
import { defineSandbox } from "eve/sandbox";
@@ -113,6 +113,8 @@ export default defineParentSandbox();
An inheriting subagent cannot declare its own managed workspace or skill files.
+The parent and every subagent that shares its sandbox, including children of the built-in `agent` tool, use one sandbox keyed by the parent's session. Whichever session opens it first runs the parent's `defineSandbox()` selector to create it. When the parent session ends, eve deletes the sandbox, even one that only a subagent opened.
+
## Managed workspace and skills
Use the sandbox directory for authored workspace seeds:
@@ -182,16 +184,20 @@ export const AcmeSandbox = defineSandboxProvider<
{ image: string; prepare?: (sandbox: SandboxSession) => Promise<void> },
{ networkPolicy?: "allow-all" | "deny-all" },
{ templateId: string },
- { remoteId: string; version: 1 },
+ { name: string; version: 1 },
SandboxSession
>({
name: "acme",
environment(options) {
const client = createAcmeClient(options);
+ // The session key alone names the sandbox, so every caller finds the same one.
+ const sandboxName = (sessionId: string) => `eve-${sessionId}`;
return {
- async onSessionEnd(_ctx, _artifact, state, { reason }) {
- await client.delete({ id: state.remoteId, reason });
+ async onSessionEnd(ctx, state, { reason }) {
+ // `state` is null when the session never recorded it, for example when
+ // only a subagent that shares the sandbox opened it.
+ await client.deleteIfExists({ name: state?.name ?? sandboxName(ctx.session.id), reason });
},
async prepare(ctx) {
@@ -205,19 +211,18 @@ export const AcmeSandbox = defineSandboxProvider<
},
async start(ctx, liveOptions, artifact) {
- const remote = await client.open({
- identity: sessionIdentity(ctx.session.id, artifact, liveOptions),
+ const name = sandboxName(ctx.session.id);
+ // Returns the sandbox with this name, or atomically creates it with these options.
+ const remote = await client.getOrCreate({
+ name,
networkPolicy: liveOptions?.networkPolicy,
templateId: artifact.templateId,
});
- return {
- handle: createHandle(remote),
- state: { remoteId: remote.id, version: 1 },
- };
+ return { handle: createHandle(remote), state: { name, version: 1 } };
},
async resume(_ctx, artifact, state) {
- const remote = await client.resume({ id: state.remoteId, templateId: artifact.templateId });
+ const remote = await client.resume({ name: state.name, templateId: artifact.templateId });
return createHandle(remote);
},
};
@@ -225,11 +230,13 @@ export const AcmeSandbox = defineSandboxProvider<
});
```
-`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.
+`prepare()` returns the complete JSON-serializable artifact.
+
+`start()` must be an idempotent upsert keyed by `ctx.session.id`: return the live sandbox for that key when one exists, and create it otherwise. eve can call `start()` for one key more than once, from different processes and deployments, and concurrently. A subagent that shares its parent's sandbox can open it before the parent does, and two processes can race to create it. Derive the sandbox's identity from the key, plus a provider-level namespace such as a project or account when names would otherwise collide. Never derive it from the open options or the artifact, which can differ between callers and deployments; apply them only when `start()` creates the sandbox. eve persists the minimal JSON-compatible state `start()` returns. Process restarts call `resume()` with only the current context, that state, and the target deployment's exact artifact.
-`onSessionEnd()` is invoked when the durable session reaches a completed, expired, or failed terminal outcome. It receives the exact prepared artifact, persisted provider state, and a `reason` of `"completed"`, `"expired"`, or `"failed"`. Implement idempotent permanent cleanup from those values rather than depending on a live handle. eve retries the cleanup step and logs an exhausted failure without replacing the session's terminal outcome. A session that never opened a sandbox and a child that borrows its parent's sandbox do not call the hook.
+`onSessionEnd()` is required. eve calls it for every owning durable session that reaches a completed, expired, or failed terminal outcome, including sessions with no recorded sandbox state. A failed step or process loss can create a sandbox before its state is checkpointed, so the last checkpoint cannot establish that no sandbox exists. The hook receives the session context, the persisted provider state or `null`, and a `reason` of `"completed"`, `"expired"`, or `"failed"`. Delete whatever exists under `ctx.session.id` without depending on a live handle, and find it from the key when the state is `null`. The hook must succeed when nothing exists and must be idempotent: eve retries the cleanup step and logs an exhausted failure without replacing the session's terminal outcome. A subagent that shares its parent's sandbox does not call the hook, because cleanup belongs to the parent. An `invokeTool` call without a key also calls `onSessionEnd()` when the call ends if it requested sandbox access, including an initialization attempt that failed.
-Provider handles implement `onSandboxStop()`, `onRuntimeShutdown()`, and `onSandboxDelete()`. These handle-level methods cover authored stop or delete calls, process shutdown, and failed initialization; `onSessionEnd()` is the single provider hook for durable terminal session cleanup.
+Provider handles implement `onSandboxStop()`, `onRuntimeShutdown()`, and `onSandboxDelete()`. These handle-level methods cover authored stop or delete calls and process shutdown; `onSessionEnd()` is the single provider hook for durable terminal session cleanup. eve does not delete a sandbox whose initialization failed: the next access runs the selector against it again, and session end removes it.
Open options belong to `start()` and are not serialized or passed to `resume()`. A provider must put any immutable option-derived data needed for reconnection in its session state. With the current immutable-state contract, `resume()` reconnects existing native state and fails if it is gone rather than recreating callback side effects. A custom provider may define start-only callback fields, but built-in providers initialize the sandbox in `defineSandbox()` after `open()`.
@@ -247,9 +254,11 @@ Preparation discovers authored files through `ctx.files`; core keeps project lay
## Lifecycle
-Session-owned sandboxes persist across turns and deployments while their provider state remains available. `sandbox.stop()` stops compute without deleting persisted state; a later access resumes that state directly. `sandbox.delete()` clears provider state, so the next `ctx.getSandbox()` reruns the selector and starts a fresh sandbox from the current environment. When the durable session reaches a terminal outcome, eve calls the provider's `onSessionEnd()` hook to release any remaining session-owned resources.
+Session-owned sandboxes persist across turns and deployments while their provider state remains available. `sandbox.stop()` stops compute without deleting persisted state; a later access resumes that state directly. `sandbox.delete()` deletes the sandbox and clears provider state, so the next `ctx.getSandbox()` reruns the selector, and the provider starts a fresh sandbox under the same session key from the current environment. When the durable session reaches a terminal outcome, eve calls the provider's `onSessionEnd()` hook to delete what remains under the session's key.
+
+Before that cleanup, session end ends the session's task runs, and each run resets the subagent sessions it opened. eve does not wait for those subagents to stop. A subagent step that is still running at that moment can open the sandbox again after cleanup, and eve does not remove a sandbox created that late.
-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.
+Changing sandbox source, preparation code, Dockerfile content, environment options, workspace resources, or skills produces a new environment generation. Existing durable sessions keep their sandbox, because its identity comes from the session key alone; new sessions use the current generation.
## What to read next
diff --git a/docs/sandbox/microsandbox.mdx b/docs/sandbox/microsandbox.mdx
index 4dfbea6f0..388a4189d 100644
--- a/docs/sandbox/microsandbox.mdx
+++ b/docs/sandbox/microsandbox.mdx
@@ -28,4 +28,6 @@ Pass `networkPolicy` to `open()`. The policy applies to the live VM, not the pre
Session creation uses the recorded snapshot and image directly. Writable VM state persists through the provider's session snapshot lifecycle.
+A session's creation, reconnection, and cleanup share a cross-process lock, so separate sessions don't wait on each other. An opener reuses a running VM instead of replacing it. Restoring saved state uses a recoverable target name, so a process that exits before publishing metadata does not leave an undiscoverable VM.
+
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
index 718006e26..48906dc1d 100644
--- a/docs/sandbox/vercel.mdx
+++ b/docs/sandbox/vercel.mdx
@@ -152,9 +152,11 @@ Vercel allows up to four non-overlapping, absolute Drive mount paths per 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.
+`open()` also accepts Vercel compute resources, timeout, environment variables, and Drive mounts. These options apply only when creating the sandbox. Reopening the same key or resuming recorded state keeps the native sandbox's original environment variables, mounts, and network policy. Pass `env` to `run()` or `spawn()` for a per-command override, or call `setNetworkPolicy()` to change the live network policy.
-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.
+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 keeps the sandbox and runs the selector against it again on the next access, so make initialization safe to repeat; session end deletes the sandbox. After initialization succeeds, the provider persists only immutable JSON-compatible state. If the named Vercel Sandbox later disappears, resume fails rather than recreating initialization side effects.
eve owns the persistent sandbox identity and prepared snapshot source.
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/sandbox.ts b/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/sandbox.ts
index 2df47e5c9..ce6741cfb 100644
--- a/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/sandbox.ts
+++ b/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/sandbox.ts
@@ -10,6 +10,8 @@ const provider = defineSandboxProvider<undefined, undefined, null, CustomState,
name: "custom-provider-session",
environment() {
return {
+ // Each handle keeps its files in memory, so nothing outlives the session.
+ async onSessionEnd() {},
async prepare() {
return null;
},
diff --git a/packages/eve/extension-contracts/reports/channel/v65.json b/packages/eve/extension-contracts/reports/channel/v65.json
new file mode 100644
index 000000000..2badcae83
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/channel/v65.json
@@ -0,0 +1,24 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "channel",
+ "epoch": 65,
+ "sha256": "811b953ed67624bc2f7928b7637743c41c434038314e135b2189f65c4276b3f5",
+ "exports": [
+ "DELETE",
+ "GET",
+ "HEAD",
+ "InvalidSessionHistoryError",
+ "OPTIONS",
+ "PATCH",
+ "POST",
+ "PUT",
+ "SessionStrandedError",
+ "WS",
+ "attachmentError",
+ "createWebSocketUpgradeServer",
+ "defineChannel",
+ "disableRoute",
+ "isChannel",
+ "isDisabledRouteSentinel"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/connection/v54.json b/packages/eve/extension-contracts/reports/connection/v54.json
new file mode 100644
index 000000000..03a2b65f6
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/connection/v54.json
@@ -0,0 +1,16 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "connection",
+ "epoch": 54,
+ "sha256": "7bbcde10b4e6892d12047b5a2aed088ed6f211eda65d1cf874c1843017e15df4",
+ "exports": [
+ "ConnectionAuthorizationFailedError",
+ "ConnectionAuthorizationRequiredError",
+ "defineDynamic",
+ "defineInteractiveAuthorization",
+ "defineMcpClientConnection",
+ "defineOpenAPIConnection",
+ "isConnectionAuthorizationFailedError",
+ "isConnectionAuthorizationRequiredError"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v89.json b/packages/eve/extension-contracts/reports/dynamicTool/v89.json
new file mode 100644
index 000000000..65c345466
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicTool/v89.json
@@ -0,0 +1,16 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicTool",
+ "epoch": 89,
+ "sha256": "326671018a0af382e8a0c90f452e92fe9b0e3ccbb0c33f823585437766328f62",
+ "exports": [
+ "DynamicToolEntry",
+ "DynamicToolEvents",
+ "DynamicToolResult",
+ "DynamicToolSet",
+ "auto",
+ "defineDurableCallback",
+ "defineDurableSchema",
+ "defineDynamic"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/hook/v49.json b/packages/eve/extension-contracts/reports/hook/v49.json
new file mode 100644
index 000000000..cf6b4975a
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/hook/v49.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "hook",
+ "epoch": 49,
+ "sha256": "ed483669dc896c68d65e51d0a83f6299e77ec25831a7c077e9d1a11be42b32ab",
+ "exports": ["defineHook"]
+}
diff --git a/packages/eve/extension-contracts/reports/state/v14.json b/packages/eve/extension-contracts/reports/state/v14.json
new file mode 100644
index 000000000..f5fdb738e
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/state/v14.json
@@ -0,0 +1,15 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "state",
+ "epoch": 14,
+ "sha256": "d02dddceb28ba6209b50229b4a5f6cd61b0e3f9f2415bf2f56f2e9c65c61834b",
+ "exports": [
+ "Session",
+ "SessionAuth",
+ "SessionAuthContext",
+ "SessionContext",
+ "SessionParent",
+ "SessionTurn",
+ "defineState"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/tool/v97.json b/packages/eve/extension-contracts/reports/tool/v97.json
new file mode 100644
index 000000000..779c61ce7
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/tool/v97.json
@@ -0,0 +1,29 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "tool",
+ "epoch": 97,
+ "sha256": "24bb3922f3ed2db58f72aff79413c774d99667f60e6a353234ff093fe11ec6c5",
+ "exports": [
+ "AgentRouterInput",
+ "AgentRouterTool",
+ "WorkflowStepToolContext",
+ "WorkflowTool",
+ "WorkflowToolDefinition",
+ "WorkflowToolInput",
+ "WorkflowToolOptions",
+ "agentRouter",
+ "decide",
+ "defaultWebSearch",
+ "defineTool",
+ "defineWorkflowTool",
+ "disableTool",
+ "isDisabledToolSentinel",
+ "isWebSearchToolDefinition",
+ "serializeModelInputSchema",
+ "toolOutput",
+ "toolOutputPart",
+ "toolResultFrom",
+ "webSearch",
+ "workflow"
+ ]
+}
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index 93018436d..d041d30f5 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -22,10 +22,10 @@ interface ExtensionCapabilityContract {
const EXTENSION_CAPABILITY_CONTRACTS = {
extension: { current: 1, supported: [1], dropped: {} },
tool: {
- current: 96,
+ current: 97,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 76, 77, 78, 80, 81, 82, 84,
- 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96,
+ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 97,
],
dropped: {
14: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
@@ -86,14 +86,16 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
75: "eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai",
79: "Sandbox provider handle hooks were renamed to onSandboxStop and onSandboxDelete.",
83: 'webSearch provider "openai" was replaced by "native" before it shipped in a release',
+ 95: "Custom sandbox providers must implement onSessionEnd(context, state, options) and make start an upsert keyed by the session id.",
+ 96: "Custom sandbox providers must implement onSessionEnd(context, state, options) and make start an upsert keyed by the session id.",
},
},
dynamicTool: {
- current: 88,
+ current: 89,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 31, 32, 33, 52, 54,
60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 72, 73, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
- 85, 86, 87, 88,
+ 85, 86, 87, 89,
],
dropped: {
21: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
@@ -131,13 +133,14 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
59: "Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.",
71: "AI SDK evaluation models became decision models; auto() accepts decision models only",
74: "Sandbox provider handle hooks were renamed to onSandboxStop and onSandboxDelete.",
+ 88: "Custom sandbox providers must implement onSessionEnd(context, state, options) and make start an upsert keyed by the session id.",
},
},
channel: {
- current: 64,
+ current: 65,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 29, 31, 36, 37, 38, 39, 40, 41, 42,
- 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
+ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 65,
],
dropped: {
12: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
@@ -157,6 +160,7 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
34: 'Background task delivery was removed: sends no longer accept taskDeliveryPolicy and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.',
35: "Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.",
53: "Sandbox provider handle hooks were renamed to onSandboxStop and onSandboxDelete.",
+ 64: "Custom sandbox providers must implement onSessionEnd(context, state, options) and make start an upsert keyed by the session id.",
},
},
schedule: {
@@ -190,10 +194,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
connection: {
- current: 53,
+ current: 54,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 26, 32, 33, 34,
- 35, 36, 37, 38, 39, 40, 41, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
+ 35, 36, 37, 38, 39, 40, 41, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54,
],
dropped: {
9: "Dynamic connection resolvers no longer receive conversation or channel continuation data",
@@ -206,12 +210,13 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
30: "Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.",
31: "Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.",
42: "Sandbox provider handle hooks were renamed to onSandboxStop and onSandboxDelete.",
+ 53: "Custom sandbox providers must implement onSessionEnd(context, state, options) and make start an upsert keyed by the session id.",
},
},
hook: {
- current: 48,
+ current: 49,
supported: [
- 20, 21, 22, 23, 25, 27, 31, 32, 33, 34, 35, 36, 37, 38, 39, 41, 42, 43, 44, 45, 46, 47, 48,
+ 20, 21, 22, 23, 25, 27, 31, 32, 33, 34, 35, 36, 37, 38, 39, 41, 42, 43, 44, 45, 46, 47, 49,
],
dropped: {
1: "Model identity moved from session.started runtime metadata to step.started call attribution.",
@@ -239,6 +244,7 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
29: 'Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.',
30: "Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.",
40: "Sandbox provider handle hooks were renamed to onSandboxStop and onSandboxDelete.",
+ 48: "Custom sandbox providers must implement onSessionEnd(context, state, options) and make start an upsert keyed by the session id.",
},
},
skill: { current: 3, supported: [1, 2, 3], dropped: {} },
@@ -271,12 +277,13 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
config: { current: 1, supported: [1], dropped: {} },
state: {
- current: 13,
- supported: [1, 2, 3, 4, 5, 7, 9, 10, 12, 13],
+ current: 14,
+ supported: [1, 2, 3, 4, 5, 7, 9, 10, 12, 14],
dropped: {
6: "Sandbox sessions no longer expose core identity and mutable networking is provider-specific.",
8: "SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities",
11: "Sandbox provider handle hooks were renamed to onSandboxStop and onSandboxDelete.",
+ 13: "Custom sandbox providers must implement onSessionEnd(context, state, options) and make start an upsert keyed by the session id.",
},
},
} as const satisfies Record<string, ExtensionCapabilityContract>;
diff --git a/packages/eve/src/compiler/normalize-sandbox.test.ts b/packages/eve/src/compiler/normalize-sandbox.test.ts
index da245e685..dfc0dd7f8 100644
--- a/packages/eve/src/compiler/normalize-sandbox.test.ts
+++ b/packages/eve/src/compiler/normalize-sandbox.test.ts
@@ -5,6 +5,7 @@ import { defineSandboxProvider } from "#shared/sandbox-provider.js";
const provider = defineSandboxProvider({
name: "test",
environment: () => ({
+ async onSessionEnd() {},
async prepare() {
return null;
},
diff --git a/packages/eve/src/context/sandbox-terminal.integration.test.ts b/packages/eve/src/context/sandbox-terminal.integration.test.ts
new file mode 100644
index 000000000..ea10df508
--- /dev/null
+++ b/packages/eve/src/context/sandbox-terminal.integration.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from "vitest";
+
+import { SandboxKey } from "#context/keys.js";
+import { withContextScope } from "#context/run-step.js";
+import { deserializeContext } from "#context/serialize.js";
+import { createDurableSessionState } from "#execution/durable-session-store.js";
+import { endSessionSandboxStep } from "#execution/session/end-sandbox-step.js";
+import type { HarnessSession } from "#harness/types.js";
+import { createTestRuntime } from "#internal/testing/app-harness.js";
+import { buildSerializedContext } from "#internal/testing/entry-test-helpers.js";
+import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
+
+// Exercise the failed scope and terminal step with the last successful checkpoint,
+// not the failed access's uncommitted captureState().
+describe("sandbox terminal cleanup after a failed scope", () => {
+ it.each(["failed", "expired"] as const)(
+ "cleans up by key on %s after initialization opened a sandbox then threw",
+ async (reason) => {
+ const runtime = await createTestRuntime();
+ await runtime.run(async () => {
+ const serializedContext = {
+ ...buildSerializedContext({ channelKind: "http" }),
+ "eve.sessionId": `sandbox-initialization-${reason}`,
+ };
+ const ctx = await deserializeContext(serializedContext);
+ const registered = ctx.require(BundleKey).graph.root.sandboxRegistry.sandbox;
+ if (registered?.definition.kind !== "independent") throw new Error("Missing sandbox.");
+ const initialize = registered.definition.selector;
+ Object.assign(registered.definition, {
+ selector: async (context: Parameters<typeof initialize>[0]) => {
+ await initialize(context);
+ throw new Error("Initialization failed after opening the sandbox.");
+ },
+ });
+ const checkpoint: HarnessSession = {
+ agent: { modelReference: { id: "unused" }, system: "", tools: [] },
+ compaction: { recentWindowSize: 10, threshold: 100_000 },
+ continuationToken: "sandbox-initialization",
+ history: [],
+ sessionId: serializedContext["eve.sessionId"],
+ };
+ await expect(
+ withContextScope(ctx, checkpoint, async (session) => {
+ await ctx.require(SandboxKey).get();
+ return { result: undefined, session };
+ }),
+ ).rejects.toThrow("Initialization failed after opening the sandbox.");
+ expect(checkpoint.sandboxState).toBeUndefined();
+ expect(runtime.sandboxCleanups).toEqual([]);
+
+ await endSessionSandboxStep({
+ reason,
+ serializedContext,
+ sessionState: createDurableSessionState({ session: checkpoint }),
+ });
+
+ expect(runtime.sandboxCleanups).toEqual([checkpoint.sessionId]);
+ });
+ },
+ );
+});
diff --git a/packages/eve/src/execution/coordination-dispatch-step.ts b/packages/eve/src/execution/coordination-dispatch-step.ts
index ac7986247..49cabfe5c 100644
--- a/packages/eve/src/execution/coordination-dispatch-step.ts
+++ b/packages/eve/src/execution/coordination-dispatch-step.ts
@@ -79,7 +79,7 @@ async function dispatchCoordination(
}
const { batch, session } = prepared;
- let nextSession = session;
+ let nextSession: HarnessSessionBase = session;
const results: RuntimeActionResult[] = [];
const started: TaskStartedStreamEvent["data"][] = [];
const starts = withPrestartedRuns(
diff --git a/packages/eve/src/execution/coordination-dispatch.integration.test.ts b/packages/eve/src/execution/coordination-dispatch.integration.test.ts
index d32fc22a9..c57c401d6 100644
--- a/packages/eve/src/execution/coordination-dispatch.integration.test.ts
+++ b/packages/eve/src/execution/coordination-dispatch.integration.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it, vi } from "vitest";
import { workflowEntry } from "#execution/session/entry.js";
import { workflowToolRunWorkflowReference } from "#execution/workflow-runtime.js";
import { createTestRuntime } from "#internal/testing/app-harness.js";
-import { buildSerializedContext } from "#internal/testing/entry-test-helpers.js";
+import { buildSerializedContext, captureEvents } from "#internal/testing/entry-test-helpers.js";
import { captureTurnEvents, filterEventsByType } from "#internal/testing/events.js";
import { deployServiceWorkflow } from "#internal/testing/workflow-tool-fixtures.js";
import { startSessionOwner } from "#internal/testing/workflow-test-helpers.js";
@@ -98,8 +98,59 @@ describe("coordination dispatch", () => {
}
});
}, 60_000);
+
+ it("cleans up the sandbox key of a session that started a run, though it never opened a sandbox", async () => {
+ const runtime = await createTestRuntime({
+ agent: { name: "task-dispatch-sandbox-cleanup" },
+ modules: [
+ {
+ logicalPath: "tools/deploy_service.ts",
+ loadNamespace: async () => ({
+ default: defineWorkflowTool({
+ description: "Deploy a service.",
+ inputSchema: {
+ type: "object",
+ properties: { service: { type: "string" } },
+ required: ["service"],
+ },
+ task: deployServiceWorkflow,
+ }),
+ }),
+ },
+ ],
+ });
+
+ await runtime.run(async () => {
+ // An agent the run opens can share the session's sandbox and create it
+ // under the session's key, which the session's own state never records.
+ const dispatching = await runUntilSessionEnds('Run deploy_service with service "api"');
+ const plain = await runUntilSessionEnds("hello there");
+
+ expect(runtime.sandboxCleanups).toEqual([dispatching, plain]);
+ });
+ }, 60_000);
});
+async function runUntilSessionEnds(message: string): Promise<string> {
+ const run = await startSessionOwner(workflowEntry, [
+ {
+ kind: "initial",
+ ownerDeploymentId: "dpl_inline",
+ input: { message },
+ serializedContext: buildSerializedContext({ channelKind: "http" }),
+ sessionTimeoutMs: 25,
+ },
+ ]);
+ const stream = captureEvents(run);
+ try {
+ await stream.nextUntil("session completion", (event) => event.type === "session.completed");
+ await run.returnValue;
+ return run.runId;
+ } finally {
+ stream.dispose();
+ }
+}
+
async function listWorkflowToolRunIds(): Promise<Set<string>> {
const world = await getWorld();
const ids = new Set<string>();
diff --git a/packages/eve/src/execution/invoke-tool.test.ts b/packages/eve/src/execution/invoke-tool.test.ts
index 8f774f445..bb797f6a1 100644
--- a/packages/eve/src/execution/invoke-tool.test.ts
+++ b/packages/eve/src/execution/invoke-tool.test.ts
@@ -48,9 +48,10 @@ function tool(
};
}
+/** A provider that keeps each call's sandbox under its session id; `deleted` records cleanup by id. */
function sandboxes(options: { readonly startGate?: Promise<void> } = {}) {
const started: string[] = [];
- const deleted = vi.fn(async () => {});
+ const deleted = vi.fn(async (_sessionId: string) => {});
const shutdown = vi.fn(async () => {});
const start = vi.fn(async (context: { readonly session: { readonly id: string } }) => {
started.push(context.session.id);
@@ -60,7 +61,7 @@ function sandboxes(options: { readonly startGate?: Promise<void> } = {}) {
handle: {
sandbox: sandbox.session,
onRuntimeShutdown: shutdown,
- onSandboxDelete: deleted,
+ onSandboxDelete: async () => deleted(context.session.id),
onSandboxStop: async () => {},
},
state: null,
@@ -69,6 +70,8 @@ function sandboxes(options: { readonly startGate?: Promise<void> } = {}) {
const environment = defineSandboxProvider({
name: "memory",
environment: () => ({
+ onSessionEnd: async (context: { readonly session: { readonly id: string } }) =>
+ deleted(context.session.id),
prepare: async () => null,
resume: async () => {
throw new Error("a call's sandbox is never resumed");
@@ -94,11 +97,12 @@ function sandboxes(options: { readonly startGate?: Promise<void> } = {}) {
}
/**
- * A provider whose `start` reopens a session's sandbox by session id, as
- * Vercel Sandbox and just-bash do, opted into tool sessions.
- * Each open hands out its own handle over the shared sandbox, as just-bash
- * runs one interpreter per handle; `released` records which handles a call
- * let go of, and `stopped` which were stopped through the sandbox API.
+ * A provider whose `start` is an upsert on the session id, opted into tool
+ * sessions as Vercel Sandbox and just-bash are. Each open hands out its own
+ * handle over the shared sandbox, as just-bash runs one interpreter per
+ * handle; `released` records which handles a call let go of, and `stopped`
+ * and `shutdown` which were stopped through the sandbox API or at server
+ * shutdown.
*/
function keyedSandboxes(options: { readonly failSelector?: () => boolean } = {}) {
const live = new Map<string, { sandbox: ReturnType<typeof mockSandbox> }>();
@@ -106,6 +110,7 @@ function keyedSandboxes(options: { readonly failSelector?: () => boolean } = {})
const handles: object[] = [];
const released: object[] = [];
const stopped = vi.fn();
+ const shutdown = vi.fn(async () => {});
const deleted = vi.fn((sessionId: string) => void live.delete(sessionId));
const reopen = (sessionId: string) => {
let entry = live.get(sessionId);
@@ -116,7 +121,7 @@ function keyedSandboxes(options: { readonly failSelector?: () => boolean } = {})
}
const handle = {
sandbox: entry.sandbox.session,
- onRuntimeShutdown: async () => {},
+ onRuntimeShutdown: shutdown,
onSandboxDelete: async () => deleted(sessionId),
onSandboxStop: stopped,
};
@@ -128,6 +133,8 @@ function keyedSandboxes(options: { readonly failSelector?: () => boolean } = {})
environment: () =>
withToolSessionSandboxes(
{
+ onSessionEnd: async (context: { readonly session: { readonly id: string } }) =>
+ deleted(context.session.id),
prepare: async () => null,
resume: async (context: { readonly session: { readonly id: string } }) =>
reopen(context.session.id),
@@ -159,7 +166,7 @@ function keyedSandboxes(options: { readonly failSelector?: () => boolean } = {})
workspaceResourceRoot: { logicalPath: "", rootEntries: [] },
},
};
- return { deleted, handles, live, registry, released, starts, stopped };
+ return { deleted, handles, live, registry, released, shutdown, starts, stopped };
}
/** A tool that appends to a note in its sandbox and returns the note, after `gate` opens. */
@@ -378,64 +385,41 @@ describe("invokeTool", () => {
expect(new Set(starts).size).toBe(4);
});
- it("lets go of each keyed call's own handle when it ends, and nothing else", async () => {
- const { handles, registry, released, stopped } = keyedSandboxes();
+ it("leaves a keyed sandbox running and lets go of each call's handle when it ends", async () => {
+ const { deleted, handles, registry, released, shutdown, stopped } = keyedSandboxes();
let openGate!: () => void;
const held = runtimeWith(
[noteTool(new Promise<void>((resolve) => (openGate = resolve)))],
registry,
);
- const runtime = runtimeWith([noteTool()], registry);
- const note = (text: string, run = runtime) =>
- invokeTool(run, "note", { text }, { auth: alice, key: "desk" });
+ const failing = tool("failing", async (_input: unknown, ctx) => {
+ await ctx.getSandbox();
+ throw new Error("boom");
+ });
+ const runtime = runtimeWith([noteTool(), failing], registry);
+ const call = (name: string, text: string, run = runtime) =>
+ invokeTool(run, name, { text }, { auth: alice, key: "desk" });
- const holding = note("a", held);
+ const holding = call("note", "a", held);
await vi.waitFor(() => expect(handles).toHaveLength(1));
// An overlapping call reopens the same sandbox through its own handle and
// releases only that one when it ends; the first call's handle stays open.
- expect(await note("b")).toMatchObject({ status: "completed" });
- expect(handles).toHaveLength(2);
+ expect(await call("note", "b")).toMatchObject({ status: "completed" });
expect(released).toEqual([handles[1]]);
openGate();
expect(await holding).toMatchObject({ status: "completed" });
expect(released).toEqual([handles[1], handles[0]]);
- // The sandbox itself is neither stopped nor tracked for shutdown any more.
- expect(stopped).not.toHaveBeenCalled();
- await shutdownActiveSandboxHandles();
- expect(await note("c")).toMatchObject({ output: expect.stringMatching(/^[ab]{2}c$/u) });
-
- // A call that fails, or never opens a sandbox, has no handle to let go of.
- const failing = tool("failing", () => {
- throw new Error("boom");
- });
- expect(
- await invokeTool(
- runtimeWith([failing], registry),
- "failing",
- {},
- { auth: alice, key: "desk" },
- ),
- ).toMatchObject({ status: "failed" });
+ // A call that fails after opening its sandbox still lets go of its handle.
+ expect(await call("failing", "")).toMatchObject({ status: "failed" });
expect(handles).toHaveLength(3);
- expect(released).toHaveLength(3);
- });
+ expect(released).toEqual([handles[1], handles[0], handles[2]]);
- it("lets go of a keyed call's handle even when the call fails after opening it", async () => {
- const { handles, registry, released } = keyedSandboxes();
- const failing = tool("failing", async (_input: unknown, ctx) => {
- await ctx.getSandbox();
- throw new Error("boom");
- });
- expect(
- await invokeTool(
- runtimeWith([failing], registry),
- "failing",
- {},
- { auth: alice, key: "desk" },
- ),
- ).toMatchObject({ status: "failed" });
- expect(released).toEqual(handles);
- expect(handles).toHaveLength(1);
+ // No call's handle is left for server shutdown, and the sandbox itself stays.
+ await shutdownActiveSandboxHandles();
+ expect(shutdown).not.toHaveBeenCalled();
+ expect(stopped).not.toHaveBeenCalled();
+ expect(deleted).not.toHaveBeenCalled();
+ expect(await call("note", "c")).toMatchObject({ output: expect.stringMatching(/^[ab]{2}c$/u) });
});
it("denies an anonymous caller a key before deriving a session or opening a sandbox", async () => {
@@ -463,11 +447,13 @@ describe("invokeTool", () => {
});
it("refuses a keyed sandbox on a provider that cannot keep it, and an empty key", async () => {
- const runtime = runtimeWith([noteTool()], sandboxes().registry);
+ const { registry, started } = sandboxes();
+ const runtime = runtimeWith([noteTool()], registry);
expect(await invokeTool(runtime, "note", { text: "a" }, { auth: alice, key: "desk" })).toEqual({
message: expect.stringContaining('Sandbox provider "memory" cannot keep a sandbox'),
status: "failed",
});
+ expect(started).toHaveLength(0);
expect(await invokeTool(runtime, "note", { text: "a" }, { auth: alice, key: "" })).toEqual({
message: "The tool session key must not be empty.",
status: "invalid-input",
diff --git a/packages/eve/src/execution/invoke-tool.ts b/packages/eve/src/execution/invoke-tool.ts
index 37b8220cb..07dfd7dc4 100644
--- a/packages/eve/src/execution/invoke-tool.ts
+++ b/packages/eve/src/execution/invoke-tool.ts
@@ -212,14 +212,13 @@ interface CallSandbox {
/**
* A keyed session's sandbox: found or created on the first `ctx.getSandbox()`
- * through the provider's `start`, which reopens it by session id, and kept
- * after the call. Concurrent first calls in this process share one start.
- * The call does not own the sandbox, so a failed start never deletes it, and
- * release only lets go of this call's handle: an overlapping call keeps its
- * own.
+ * through the provider's `start`, an upsert on the session id, and kept after
+ * the call. Concurrent first calls in this process share one start. The call
+ * does not own the sandbox, so a failed start never deletes it, and release
+ * only lets go of this call's handle: an overlapping call keeps its own.
*/
async function keyedSandbox(runtime: InvokeToolRuntime, sessionId: string): Promise<CallSandbox> {
- const inner = await ensureSandboxAccess({
+ const access = await ensureSandboxAccess({
compiledArtifactsSource: runtime.compiledArtifactsSource,
nodeId: runtime.nodeId,
ownsSandbox: false,
@@ -229,22 +228,26 @@ async function keyedSandbox(runtime: InvokeToolRuntime, sessionId: string): Prom
});
return {
access: {
- ...inner,
+ ...access,
async get() {
assertToolSessionSandboxSupport(runtime.sandboxRegistry);
- return await inner.get();
+ return await access.get();
},
},
async release() {
- const handle = await inner.detach();
+ const handle = await access.detach();
if (handle !== undefined) await releaseToolSessionHandle(runtime.sandboxRegistry, handle);
},
};
}
-/** The call's sandbox: opened on the first `ctx.getSandbox()`, deleted after the call. */
+/**
+ * The call's sandbox: opened on the first `ctx.getSandbox()`, removed after
+ * the call through the provider's session-end cleanup, which also reaches a
+ * start still in flight or one whose initialization failed.
+ */
async function callSandbox(runtime: InvokeToolRuntime, sessionId: string): Promise<CallSandbox> {
- const inner = await ensureSandboxAccess({
+ const access = await ensureSandboxAccess({
compiledArtifactsSource: runtime.compiledArtifactsSource,
nodeId: runtime.nodeId,
ownsSandbox: true,
@@ -252,24 +255,19 @@ async function callSandbox(runtime: InvokeToolRuntime, sessionId: string): Promi
sessionId,
state: null,
});
- // The latest requested open, kept before it settles: `execute` can finish
- // (say, by losing a race against cancellation) while the provider is still
- // starting, and release must still delete what that start creates.
- let requested: Promise<unknown> | undefined;
+ // This unkeyed access has no other opener or checkpoint: no request means no
+ // sandbox. Once requested, cleanup must cover failed or still-running starts.
+ let requested = false;
return {
access: {
- ...inner,
+ ...access,
get() {
- const opening = inner.get();
- requested = opening;
- return opening;
+ requested = true;
+ return access.get();
},
},
async release() {
- if (requested === undefined) return;
- // A failed open left nothing behind; deleting would open one just to delete it.
- const sandbox = await requested.catch(() => null);
- if (sandbox !== null) await inner.delete?.();
+ if (requested) await access.end("completed");
},
};
}
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 7453f3794..d2c661425 100644
--- a/packages/eve/src/execution/sandbox/bindings/docker.integration.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/docker.integration.test.ts
@@ -142,13 +142,14 @@ const TEMPLATE_IMAGE = dockerTemplateImageReference({
templateKey: TEMPLATE_KEY,
});
const SESSION_KEY = "eve-sbx-ses-local-session-1";
-const PROVIDER_CONTAINER_NAME = `eve-sbx-${createSandboxProviderIdentity({
- artifact: { imageReference: TEMPLATE_IMAGE },
- environment: createDockerSandboxOptionsHash(resolveDockerSandboxOptions(undefined)),
- open: {},
- sessionId: SESSION_KEY,
- version: 1,
-}).slice(0, 32)}`;
+/** The session container's name, which derives from the app's storage path and the session key alone. */
+function providerContainerName(appRoot: string): string {
+ return `eve-sbx-${createSandboxProviderIdentity({
+ namespace: appRoot,
+ sessionId: SESSION_KEY,
+ version: 2,
+ }).slice(0, 32)}`;
+}
describe("Docker provider prewarm", () => {
it("uses a colocated Dockerfile as the template base image", async () => {
@@ -449,7 +450,7 @@ describe("Docker provider create", () => {
});
const run = findCall(calls, (args) => args[0] === "run");
- expect(run?.args).toContain(PROVIDER_CONTAINER_NAME);
+ expect(run?.args).toContain(providerContainerName(appRoot));
expect(run?.args).toContain("eve.sandbox.role=session");
expect(run?.args.at(-3)).toBe(TEMPLATE_IMAGE);
@@ -466,7 +467,7 @@ describe("Docker provider create", () => {
"stop",
"-t",
"0",
- fakeDockerContainerIdentity(PROVIDER_CONTAINER_NAME),
+ fakeDockerContainerIdentity(providerContainerName(appRoot)),
]);
} finally {
if (previousRunId === undefined) {
@@ -493,7 +494,7 @@ describe("Docker provider create", () => {
expect(findCall(calls, (args) => args[0] === "start")?.args).toEqual([
"start",
- PROVIDER_CONTAINER_NAME,
+ providerContainerName(appRoot),
]);
expect(findCall(calls, (args) => args[0] === "run")).toBeUndefined();
});
@@ -530,7 +531,7 @@ describe("Docker provider create", () => {
peerCreated = true;
return {
exitCode: 125,
- stderr: `docker: Error response from daemon: Conflict. The container name "/${PROVIDER_CONTAINER_NAME}" is already in use by container "d6b4ad87".`,
+ stderr: `docker: Error response from daemon: Conflict. The container name "/${providerContainerName(appRoot)}" is already in use by container "d6b4ad87".`,
};
}
return undefined;
@@ -557,11 +558,11 @@ describe("Docker provider create", () => {
appRoot,
sandboxName: SESSION_KEY,
});
- return { calls, handle, killedStreams };
+ return { appRoot, calls, handle, killedStreams };
}
it("spawns commands through a pid-recording bash -lc wrapper with cwd and env", async () => {
- const { calls, handle } = await createRunningSessionHandle({
+ const { appRoot, calls, handle } = await createRunningSessionHandle({
respond: (args) => {
if (args[0] === "exec" && args.includes("bash")) {
return { exitCode: 0, streamStdout: "staging\n" };
@@ -585,7 +586,7 @@ describe("Docker provider create", () => {
"/workspace",
"-e",
"DEPLOY_ENV=staging",
- fakeDockerContainerIdentity(PROVIDER_CONTAINER_NAME),
+ fakeDockerContainerIdentity(providerContainerName(appRoot)),
"bash",
"-c",
]);
@@ -599,7 +600,7 @@ describe("Docker provider create", () => {
});
it("kill() tree-kills inside the container before killing the docker exec client", async () => {
- const { calls, handle, killedStreams } = await createRunningSessionHandle({});
+ const { appRoot, calls, handle, killedStreams } = await createRunningSessionHandle({});
const spawned = await handle.sandbox.spawn({ command: "sleep 300" });
const spawnExec = findCall(calls, (args) => args[0] === "exec" && args.includes("bash"));
@@ -612,7 +613,7 @@ describe("Docker provider create", () => {
const treeKill = findCall(calls, (args) => args.includes("eve-kill-tree"));
expect(treeKill?.args.slice(0, 2)).toEqual([
"exec",
- fakeDockerContainerIdentity(PROVIDER_CONTAINER_NAME),
+ fakeDockerContainerIdentity(providerContainerName(appRoot)),
]);
expect(treeKill?.args.at(-1)).toBe(pidFilePath);
expect(String(treeKill?.args.at(-3))).toContain("kill_tree");
@@ -670,14 +671,14 @@ describe("Docker provider create", () => {
});
it("maps removePath options onto rm flags", async () => {
- const { calls, handle } = await createRunningSessionHandle({});
+ const { appRoot, calls, handle } = await createRunningSessionHandle({});
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(PROVIDER_CONTAINER_NAME),
+ fakeDockerContainerIdentity(providerContainerName(appRoot)),
"rm",
"-rf",
"--",
@@ -686,7 +687,7 @@ describe("Docker provider create", () => {
});
it("applies deny-all by disconnecting every container network", async () => {
- const { calls, handle } = await createRunningSessionHandle({
+ const { appRoot, calls, handle } = await createRunningSessionHandle({
respond: (args) => {
if (isContainerInspect(args) && args[3] === "{{json .NetworkSettings.Networks}}") {
return { exitCode: 0, stdout: '{"bridge":{}}' };
@@ -704,12 +705,12 @@ describe("Docker provider create", () => {
"disconnect",
"--force",
"bridge",
- fakeDockerContainerIdentity(PROVIDER_CONTAINER_NAME),
+ fakeDockerContainerIdentity(providerContainerName(appRoot)),
]);
});
it("applies allow-all to a deny-all-created container by detaching none before bridge", async () => {
- const { calls, handle } = await createRunningSessionHandle({
+ const { appRoot, calls, handle } = await createRunningSessionHandle({
respond: (args) => {
if (isContainerInspect(args) && args[3] === "{{json .NetworkSettings.Networks}}") {
// Containers created with `--network none` report the special
@@ -731,9 +732,9 @@ describe("Docker provider create", () => {
"disconnect",
"--force",
"none",
- fakeDockerContainerIdentity(PROVIDER_CONTAINER_NAME),
+ fakeDockerContainerIdentity(providerContainerName(appRoot)),
],
- ["network", "connect", "bridge", fakeDockerContainerIdentity(PROVIDER_CONTAINER_NAME)],
+ ["network", "connect", "bridge", fakeDockerContainerIdentity(providerContainerName(appRoot))],
]);
});
diff --git a/packages/eve/src/execution/sandbox/bindings/docker.test.ts b/packages/eve/src/execution/sandbox/bindings/docker.test.ts
index 06c0cafe2..973ba827f 100644
--- a/packages/eve/src/execution/sandbox/bindings/docker.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/docker.test.ts
@@ -88,3 +88,52 @@ describe("Docker sandbox deletion", () => {
);
});
});
+
+describe("Docker sandbox session identity", () => {
+ it("names the container from the session key alone and removes it by key at session end", async () => {
+ let removed = false;
+ const run: DockerCli["run"] = vi.fn(async (args: readonly string[]) => {
+ const gone = args[0] === "rm" && removed;
+ if (args[0] === "rm") removed = true;
+ return {
+ exitCode: gone ? 1 : 0,
+ stderr: gone ? "Error response from daemon: No such container: eve-sbx" : "",
+ stdout:
+ args[0] === "container" && args[3] === "{{.State.Running}}"
+ ? "true\n"
+ : args[0] === "container" && args[3] === "{{.Id}}"
+ ? "container-id-1\n"
+ : "",
+ stdoutBytes: Buffer.alloc(0),
+ };
+ });
+ const dockerCli: DockerCli = {
+ run,
+ stream() {
+ throw new Error("stream is not used by this test");
+ },
+ };
+ const provider = createSandboxProviderHarness(
+ createDockerSandboxProvider(undefined, dockerCli),
+ {},
+ { preparedArtifact: () => ({ imageReference: "image-a" }) },
+ );
+ const session = { appRoot: "/tmp/eve-app", sandboxName: "session-key" };
+
+ const { state } = await provider.start(session);
+ const later = await provider.start({
+ ...session,
+ options: { networkPolicy: "deny-all" },
+ prepared: { imageReference: "image-b" },
+ });
+ expect(later.state).toEqual(state);
+
+ vi.mocked(run).mockClear();
+ await provider.endSession({ ...session, state: null });
+ await provider.endSession({ ...session, state: null });
+ expect(vi.mocked(run).mock.calls.map(([args]) => args)).toEqual([
+ ["rm", "-f", state.containerName],
+ ["rm", "-f", state.containerName],
+ ]);
+ });
+});
diff --git a/packages/eve/src/execution/sandbox/bindings/docker.ts b/packages/eve/src/execution/sandbox/bindings/docker.ts
index 2e821fe52..51d732802 100644
--- a/packages/eve/src/execution/sandbox/bindings/docker.ts
+++ b/packages/eve/src/execution/sandbox/bindings/docker.ts
@@ -71,7 +71,6 @@ type DockerSandboxPreparedArtifact = {
};
type DockerSandboxSessionState = {
readonly containerName: string;
- readonly generation: string;
readonly version: 2;
};
@@ -130,18 +129,18 @@ export function createDockerSandboxProvider(
createIfMissing: boolean,
) {
await ensureDaemon();
- const artifact = requirePreparedDockerArtifact(artifactValue);
- if (!(await dockerImageExists(cli, artifact.imageReference))) {
- throw new SandboxTemplateNotProvisionedError({
- providerName: DOCKER_PROVIDER_NAME,
- templateKey: artifact.imageReference,
- });
- }
let running = await inspectContainerRunning(containerName);
if (running === undefined) {
if (!createIfMissing) {
throw new Error(`Docker sandbox session container "${containerName}" no longer exists.`);
}
+ const artifact = requirePreparedDockerArtifact(artifactValue);
+ if (!(await dockerImageExists(cli, artifact.imageReference))) {
+ throw new SandboxTemplateNotProvisionedError({
+ providerName: DOCKER_PROVIDER_NAME,
+ templateKey: artifact.imageReference,
+ });
+ }
try {
await startDockerContainer({
cli,
@@ -195,6 +194,14 @@ export function createDockerSandboxProvider(
}
return {
+ async onSessionEnd(context, state) {
+ await ensureDaemon();
+ const containerName = state?.containerName ?? dockerSessionName(context);
+ const removed = await cli.run(["rm", "-f", containerName]);
+ if (removed.exitCode !== 0 && !/no such container/iu.test(removed.stderr)) {
+ expectDockerSuccess(removed, `delete sandbox session container "${containerName}"`);
+ }
+ },
async prepare(context) {
context.log?.("checking Docker daemon");
await ensureDaemon();
@@ -318,46 +325,29 @@ export function createDockerSandboxProvider(
},
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.");
- }
return await openDockerSession(context, undefined, artifactValue, state.containerName, false);
},
async start(context, openOptions, artifactValue) {
- const containerName = dockerSessionName(
- context.session.id,
- openOptions,
- artifactValue,
- optionsHash,
- );
+ const containerName = dockerSessionName(context);
return {
handle: await openDockerSession(context, openOptions, artifactValue, containerName, true),
- state: {
- containerName,
- generation: dockerGeneration(artifactValue, optionsHash),
- version: 2,
- },
+ state: { containerName, version: 2 },
};
},
};
}
-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 {
+/**
+ * The session's container name. One Docker daemon serves every app on the
+ * host, so the app's storage path namespaces the session id. The template
+ * and open options apply only when the container is created, so a session
+ * keeps its container across rebuilds.
+ */
+function dockerSessionName(context: SandboxProviderSessionContext): string {
return `eve-sbx-${createSandboxProviderIdentity({
- artifact,
- environment: optionsHash,
- open: { networkPolicy: options?.networkPolicy },
- sessionId,
- version: 1,
+ namespace: context.storagePath,
+ sessionId: context.session.id,
+ version: 2,
}).slice(0, 32)}`;
}
@@ -374,12 +364,11 @@ function requireDockerSessionState(state: SandboxPreparedArtifact): DockerSandbo
if (
!isSandboxPreparedArtifactRecord(state) ||
state.version !== 2 ||
- typeof state.containerName !== "string" ||
- typeof state.generation !== "string"
+ typeof state.containerName !== "string"
) {
throw new Error("Invalid Docker sandbox session state.");
}
- return { containerName: state.containerName, generation: state.generation, version: 2 };
+ return { containerName: state.containerName, version: 2 };
}
async function resolveDockerHandleIdentity(cli: DockerCli, containerName: string): Promise<string> {
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 d6d35df5c..a63e6dd2f 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
@@ -315,6 +315,21 @@ describe("just-bash sandbox file API", () => {
expect(content).toBe("survives reconnect");
});
+ it("removes the session root by key at session end, so the next start is fresh", async () => {
+ const appRoot = await createTemporaryCacheDirectory("session-end");
+ const provider = createJustBashProvider();
+ await provider.prepare({ appRoot, seedFiles: [] });
+ const session = { appRoot, sandboxName: "session-end" };
+ const { handle } = await provider.start(session);
+ await handle.sandbox.writeTextFile({ content: "left behind", path: "left.txt" });
+
+ await provider.endSession({ ...session, state: null });
+ await provider.endSession({ ...session, state: null });
+
+ const fresh = await provider.openSession(session);
+ await expect(fresh.sandbox.readTextFile({ path: "left.txt" })).resolves.toBeNull();
+ });
+
it("supports readFile with line range options", async () => {
const cacheDirectory = await createTemporaryCacheDirectory("file-api");
const handle = await createPrewarmedLocalHandle({
@@ -474,7 +489,7 @@ describe("just-bash provider", () => {
expect(result.stdout.trim().split("\n")).toEqual(["/workspace/skills/weather.md"]);
});
- it("rejects existing session state from a different prepared artifact", async () => {
+ it("keeps a session's files when a later preparation changes the artifact", async () => {
const appRoot = await createTemporaryCacheDirectory("seed-session");
const provider = createJustBashProvider();
@@ -487,6 +502,7 @@ describe("just-bash provider", () => {
appRoot,
sandboxName: "session-seeded-later",
});
+ await initialHandle.sandbox.writeTextFile({ content: "kept", path: "notes.txt" });
await initialHandle.onRuntimeShutdown();
await provider.prepare({
@@ -499,12 +515,12 @@ describe("just-bash provider", () => {
],
});
- await expect(
- provider.openSession({
- existing: initialState,
- appRoot,
- sandboxName: "session-seeded-later",
- }),
- ).rejects.toThrow("session state is incompatible");
+ const resumed = await provider.openSession({
+ existing: initialState,
+ appRoot,
+ sandboxName: "session-seeded-later",
+ });
+ await expect(resumed.sandbox.readTextFile({ path: "notes.txt" })).resolves.toBe("kept");
+ await expect(resumed.sandbox.readTextFile({ path: "skills/weather.md" })).resolves.toBeNull();
});
});
diff --git a/packages/eve/src/execution/sandbox/bindings/just-bash.ts b/packages/eve/src/execution/sandbox/bindings/just-bash.ts
index aaa9e0702..d4f6f85db 100644
--- a/packages/eve/src/execution/sandbox/bindings/just-bash.ts
+++ b/packages/eve/src/execution/sandbox/bindings/just-bash.ts
@@ -44,11 +44,7 @@ export const JUST_BASH_PROVIDER_NAME = "just-bash";
// Holds the template key, not its path: the build and runtime app roots can differ.
type JustBashPreparedArtifact = { readonly templateKey: string };
-type JustBashSessionState = {
- readonly generation: string;
- readonly rootPath: string;
- readonly version: 2;
-};
+type JustBashSessionState = { readonly rootPath: string; readonly version: 2 };
export function createJustBashSandboxProvider(
authoredOptions: JustBashSandboxCreateOptions | undefined = undefined,
@@ -67,9 +63,10 @@ export function createJustBashSandboxProvider(
version: 2,
};
- // `start` reopens the session's root by session id, so keyed tool sessions
- // can reuse it. The roots are local files, so there is nothing to sweep.
const implementation: ReturnType<typeof createJustBashSandboxProvider> = {
+ async onSessionEnd(context, state) {
+ await rm(state?.rootPath ?? sessionRootPath(context), { force: true, recursive: true });
+ },
async prepare(context) {
const templateKey = createSandboxProviderIdentity({
...environmentIdentity,
@@ -122,33 +119,23 @@ export function createJustBashSandboxProvider(
}
return { templateKey };
},
- 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.");
- }
- if (!(await pathExists(state.rootPath))) {
- throw new Error(`just-bash session root "${state.rootPath}" no longer exists.`);
+ async resume(context, _artifact, stateValue) {
+ const { rootPath } = requireJustBashSessionState(stateValue);
+ if (!(await pathExists(rootPath))) {
+ throw new Error(`just-bash session root "${rootPath}" no longer exists.`);
}
- return await openHandle(context, state.rootPath, options);
+ return await openHandle(context, rootPath, options);
},
async start(context, _openOptions, artifactValue) {
const artifact = requirePreparedJustBashArtifact(artifactValue);
- const rootPath = sessionRootPath(context, artifact);
+ const rootPath = sessionRootPath(context);
await ensureSessionRoot(
resolveTemplateRootPath(context.storagePath, artifact.templateKey),
rootPath,
);
return {
handle: await openHandle(context, rootPath, options),
- state: {
- generation: createSandboxProviderIdentity({ artifact, version: 1 }),
- rootPath,
- version: 2,
- },
+ state: { rootPath, version: 2 },
};
},
};
@@ -158,16 +145,14 @@ export function createJustBashSandboxProvider(
});
}
-function sessionRootPath(
- context: SandboxProviderSessionContext,
- artifact: JustBashPreparedArtifact,
-): string {
+/**
+ * The session's root, under the app's storage path. The template applies
+ * only when the root is created, so a session keeps its files across rebuilds.
+ */
+function sessionRootPath(context: SandboxProviderSessionContext): string {
return resolveSessionRootPath(
context.storagePath,
- createSandboxProviderIdentity({ artifact, sessionId: context.session.id, version: 1 }).slice(
- 0,
- 24,
- ),
+ createSandboxProviderIdentity({ sessionId: context.session.id, version: 2 }).slice(0, 24),
);
}
@@ -259,12 +244,11 @@ function requireJustBashSessionState(state: SandboxPreparedArtifact): JustBashSe
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 };
+ return { rootPath: state.rootPath, version: 2 };
}
function resolveTemplateRootPath(storagePath: string, key: string): string {
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.integration.test.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.integration.test.ts
new file mode 100644
index 000000000..3d004d2b7
--- /dev/null
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.integration.test.ts
@@ -0,0 +1,216 @@
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { resolveMicrosandboxOptions } from "#execution/sandbox/bindings/microsandbox-options.js";
+import {
+ writeSessionMetadata,
+ resolveMicrosandboxMetadataPath,
+} from "#execution/sandbox/bindings/microsandbox-metadata.js";
+import { resolveMicrosandboxSessionRootPath } from "#execution/sandbox/bindings/microsandbox-templates.js";
+
+const installed = vi.hoisted(() => ({ module: undefined as unknown }));
+vi.mock("#execution/sandbox/bindings/microsandbox-platform.js", async (original) => ({
+ ...(await original<object>()),
+ assertMicrosandboxPlatformCandidate: async () => {},
+}));
+vi.mock("#internal/application/optional-package-install.js", async (original) => ({
+ ...(await original<object>()),
+ importInstalledEnginePackage: async () => installed.module,
+}));
+
+function nativeProvider() {
+ const vms = new Map<string, ReturnType<typeof vm>>();
+ const snapshots = new Map<string, Map<string, Buffer>>([["template", new Map()]]);
+ let creations = 0;
+ function vm(name: string, files: Map<string, Buffer>) {
+ let running = true;
+ return {
+ name,
+ files,
+ get running() {
+ return running;
+ },
+ async detach() {},
+ async stop() {
+ running = false;
+ },
+ async execWith() {
+ return { code: 0, stderr: () => "" };
+ },
+ fs: () => ({
+ exists: async (path: string) => running && files.has(path),
+ read: async (path: string) => files.get(path),
+ write: async (path: string, content: Uint8Array) => {
+ files.set(path, Buffer.from(content));
+ },
+ }),
+ get status() {
+ return running ? "running" : "stopped";
+ },
+ connectWithTimeout: async () => vms.get(name),
+ async startDetached() {
+ running = true;
+ return this;
+ },
+ async stopWithTimeout() {
+ running = false;
+ },
+ async kill() {
+ running = false;
+ },
+ async remove() {
+ vms.delete(name);
+ },
+ };
+ }
+ const missing = () => new Error("sandbox not found");
+ const module = {
+ isInstalled: () => true,
+ setup() {},
+ MicrosandboxError: Error,
+ Sandbox: {
+ async get(name: string) {
+ const value = vms.get(name);
+ if (!value) throw missing();
+ return value;
+ },
+ builder(name: string) {
+ let replace = false;
+ let snapshot = "template";
+ const builder = new Proxy(
+ {},
+ {
+ get(_target, key) {
+ if (key === "replace")
+ return () => {
+ replace = true;
+ return builder;
+ };
+ if (key === "fromSnapshot")
+ return (value: string) => {
+ snapshot = value;
+ return builder;
+ };
+ if (key === "createWithPullProgress")
+ return async () => {
+ const previous = vms.get(name);
+ if (previous && !replace) throw new Error("sandbox already exists");
+ // microsandbox 0.5.5's replace terminates the old VM before boot.
+ await previous?.stop();
+ const next = vm(name, new Map(snapshots.get(snapshot)));
+ if (++creations === 1)
+ next.files.set("/workspace/alice.txt", Buffer.from("Alice's running work"));
+ vms.set(name, next);
+ return { async *[Symbol.asyncIterator]() {}, awaitSandbox: async () => next };
+ };
+ return () => builder;
+ },
+ },
+ );
+ return builder;
+ },
+ },
+ Snapshot: {
+ async get(name: string) {
+ if (!snapshots.has(name)) throw missing();
+ return {};
+ },
+ async remove(name: string) {
+ snapshots.delete(name);
+ },
+ },
+ };
+ return {
+ module,
+ vms,
+ snapshots,
+ get creations() {
+ return creations;
+ },
+ };
+}
+
+const roots: string[] = [];
+afterEach(async () => {
+ await Promise.all(roots.splice(0).map((path) => rm(path, { force: true, recursive: true })));
+});
+
+describe("microsandbox concurrent lifecycle", () => {
+ it.each(["create", "restore"] as const)(
+ "upserts across independent module instances during %s without replacing running work",
+ async (operation) => {
+ const storagePath = await mkdtemp(join(tmpdir(), "eve-microsandbox-upsert-"));
+ roots.push(storagePath);
+ const native = nativeProvider();
+ installed.module = native.module;
+ const context = {
+ host: {
+ resolveProjectPath: (path: string) => join(storagePath, path),
+ loadOptionalPackage: async <T>() => native.module as T,
+ },
+ session: {
+ id: "session",
+ auth: { current: null, initiator: null },
+ turn: { id: "turn", sequence: 0 },
+ },
+ storagePath,
+ };
+ // Separate module caches model separate framework processes; the native
+ // provider and metadata are shared, not the framework's active-handle map.
+ const firstProcess = await import("#execution/sandbox/bindings/microsandbox-lifecycle.js");
+ vi.resetModules();
+ const secondProcess = await import("#execution/sandbox/bindings/microsandbox-lifecycle.js");
+ const sessionIdentity = firstProcess.microsandboxSessionIdentity(context);
+ const metadataPath = resolveMicrosandboxMetadataPath(
+ resolveMicrosandboxSessionRootPath(storagePath, sessionIdentity),
+ );
+ if (operation === "restore") {
+ native.snapshots.set(
+ "saved-work",
+ new Map([["/workspace/alice.txt", Buffer.from("Alice's running work")]]),
+ );
+ await writeSessionMetadata(metadataPath, {
+ version: 2,
+ optionsHash: "options",
+ sandboxName: "old-vm",
+ stateSnapshotName: "saved-work",
+ });
+ }
+ const input = {
+ artifact: {
+ version: 2 as const,
+ image: null,
+ optionsHash: "options",
+ snapshotName: "template",
+ },
+ context,
+ createIfMissing: true,
+ options: resolveMicrosandboxOptions({ setup: { autoInstall: false } }),
+ optionsHash: "options",
+ providerName: "microsandbox",
+ sessionIdentity,
+ };
+ const [first, second] = await Promise.all([
+ firstProcess.createMicrosandboxHandle(input),
+ secondProcess.createMicrosandboxHandle(input),
+ ]);
+ expect(native.creations).toBe(1);
+ expect(native.vms.size).toBe(1);
+ expect([...native.vms.values()].every((vm) => vm.running)).toBe(true);
+ expect(await first.handle.sandbox.readTextFile({ path: "alice.txt" })).toBe(
+ "Alice's running work",
+ );
+ expect(await second.handle.sandbox.readTextFile({ path: "alice.txt" })).toBe(
+ "Alice's running work",
+ );
+
+ // Cleanup uses the current metadata, not a cached handle from the other process.
+ await firstProcess.deleteMicrosandboxSession({ context, sessionIdentity });
+ await secondProcess.deleteMicrosandboxSession({ context, sessionIdentity });
+ expect(native.vms.size).toBe(0);
+ expect(native.snapshots.has("saved-work")).toBe(false);
+ },
+ );
+});
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.ts
index b68a30335..9f55c6469 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.ts
@@ -4,6 +4,7 @@ type NetworkPolicySandboxSession = SandboxSession & {
setNetworkPolicy(policy: SandboxNetworkPolicy): Promise<void>;
};
import { randomUUID } from "node:crypto";
+import { withMicrosandboxLifecycleLock } from "#execution/sandbox/bindings/microsandbox-lock.js";
import {
hydrateSandboxProviderResources,
@@ -32,6 +33,7 @@ import {
type MicrosandboxTemplateMetadata,
readSessionMetadata,
readTemplateMetadata,
+ writeSessionMetadata,
resolveMicrosandboxMetadataPath,
writeTemplateMetadata,
} from "#execution/sandbox/bindings/microsandbox-metadata.js";
@@ -44,7 +46,10 @@ import {
createStableHash,
doesPathExist,
loadMicrosandboxModule,
+ loadMicrosandboxWithoutInstall,
+ microsandboxRestoredSandboxName,
type MicrosandboxVm,
+ removeSandboxIfExists,
removeSnapshotIfExists,
sandboxExists,
snapshotExists,
@@ -75,11 +80,6 @@ export type MicrosandboxPreparedArtifact = {
readonly version: typeof MICROSANDBOX_METADATA_VERSION;
};
-const activeMicrosandboxSessionHandles = new Map<
- string,
- SandboxProviderHandle<NetworkPolicySandboxSession>
->();
-
export async function prewarmMicrosandboxTemplate(input: {
readonly providerName: string;
readonly options: ResolvedMicrosandboxOptions;
@@ -221,34 +221,45 @@ export async function prewarmMicrosandboxTemplate(input: {
});
}
-export async function createMicrosandboxHandle(input: {
+/**
+ * The session's identity: its metadata directory under the app's storage
+ * path, and the name of its first VM, which every app on the host shares a
+ * namespace for. The template and options apply only when the VM is created.
+ */
+export function microsandboxSessionIdentity(context: SandboxProviderSessionContext): string {
+ return createStableHash(
+ JSON.stringify(["eve.microsandbox.session.v2", context.storagePath, context.session.id]),
+ ).slice(0, 32);
+}
+
+export async function createMicrosandboxHandle(
+ input: Parameters<typeof openMicrosandboxHandle>[0],
+) {
+ return await withMicrosandboxLifecycleLock(input.context.storagePath, input.sessionIdentity, () =>
+ openMicrosandboxHandle(input),
+ );
+}
+
+async function openMicrosandboxHandle(input: {
readonly artifact: MicrosandboxPreparedArtifact;
readonly context: SandboxProviderSessionContext;
- readonly createIfMissing?: boolean;
+ readonly createIfMissing: boolean;
readonly options: ResolvedMicrosandboxOptions;
readonly optionsHash: string;
readonly providerName: string;
readonly runtimeOptions?: MicrosandboxSandboxRuntimeOptions;
- readonly sessionIdentity?: string;
+ readonly sessionIdentity: string;
}): Promise<{
readonly handle: SandboxProviderHandle<NetworkPolicySandboxSession>;
- readonly state: {
- readonly optionsHash: string;
- readonly sessionIdentity: string;
- readonly version: 3;
- };
+ readonly state: { 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 { sessionIdentity } = input;
const sessionRootPath = resolveMicrosandboxSessionRootPath(
input.context.storagePath,
sessionIdentity,
);
const metadataPath = resolveMicrosandboxMetadataPath(sessionRootPath);
+ const preparedTemplate = requirePreparedMicrosandboxTemplate(input.artifact, input.providerName);
const existingState = await readSessionMetadata(metadataPath);
const image = resolveMicrosandboxImage(existingState, preparedTemplate, input.options);
const options: LiveMicrosandboxOptions = {
@@ -257,17 +268,14 @@ export async function createMicrosandboxHandle(input: {
networkPolicy: input.runtimeOptions?.networkPolicy,
};
const module = await loadMicrosandboxModule({ host: input.context.host, options });
- const activeSessionKey = createActiveMicrosandboxSessionKey(sessionRootPath, input.optionsHash);
- const activeHandle = activeMicrosandboxSessionHandles.get(activeSessionKey);
- const state = { optionsHash: input.optionsHash, sessionIdentity, version: 3 as const };
- if (activeHandle !== undefined) return { handle: activeHandle, state };
+ const state = { sessionIdentity, version: 3 as const };
const sessionTags = withDevelopmentSandboxMetadataPathTag(
{ sessionId: input.context.session.id },
metadataPath,
);
if (
- existingState?.optionsHash === input.optionsHash &&
+ existingState !== null &&
((await sandboxExists(module, existingState.sandboxName)) ||
(existingState.stateSnapshotName !== undefined &&
(await snapshotExists(module, existingState.stateSnapshotName))))
@@ -282,21 +290,14 @@ export async function createMicrosandboxHandle(input: {
});
if (connected !== null) {
return {
- handle: cacheHandle(
- activeSessionKey,
- createHandle(connected, input.optionsHash, () => {
- activeMicrosandboxSessionHandles.delete(activeSessionKey);
- }),
- ),
+ handle: createHandle(connected, input.context, sessionIdentity),
state,
};
}
}
- if (input.sessionIdentity !== undefined && input.createIfMissing === false) {
- throw new Error(
- `microsandbox session "${input.sessionIdentity}" is no longer available to resume.`,
- );
+ if (!input.createIfMissing) {
+ throw new Error(`microsandbox session "${sessionIdentity}" is no longer available to resume.`);
}
if (
@@ -309,6 +310,15 @@ export async function createMicrosandboxHandle(input: {
});
}
const sandboxName = createProviderName("eve-sbx-ses", sessionIdentity);
+ // Record the target before boot. If this process dies after creation, the next
+ // opener attaches to the VM instead of rebuilding its writable filesystem.
+ await writeSessionMetadata(metadataPath, {
+ image: options.image,
+ networkPolicy: options.networkPolicy,
+ optionsHash: input.optionsHash,
+ sandboxName,
+ version: MICROSANDBOX_METADATA_VERSION,
+ });
const sandbox = await createPreparedMicrosandbox({
fromSnapshot: preparedTemplate.snapshotName,
module,
@@ -320,15 +330,46 @@ export async function createMicrosandboxHandle(input: {
tags: sessionTags,
});
await sandbox.writeMetadata(metadataPath, input.optionsHash);
- const handle = cacheHandle(
- activeSessionKey,
- createHandle(sandbox, input.optionsHash, () => {
- activeMicrosandboxSessionHandles.delete(activeSessionKey);
- }),
- );
+ const handle = createHandle(sandbox, input.context, sessionIdentity);
return { handle, state };
}
+/** Deletes the session's VM, its saved state, and its metadata, whichever exist. */
+export async function deleteMicrosandboxSession(input: {
+ readonly context: SandboxProviderSessionContext;
+ readonly sessionIdentity: string;
+}): Promise<void> {
+ await withMicrosandboxLifecycleLock(
+ input.context.storagePath,
+ input.sessionIdentity,
+ async () => {
+ const sessionRootPath = resolveMicrosandboxSessionRootPath(
+ input.context.storagePath,
+ input.sessionIdentity,
+ );
+ // Read current metadata under the same lock as create/restore; another process
+ // can have advanced it since this process last used a handle.
+ const module = await loadMicrosandboxWithoutInstall(
+ input.context.host.resolveProjectPath("."),
+ );
+ if (module !== null) {
+ const metadata = await readSessionMetadata(
+ resolveMicrosandboxMetadataPath(sessionRootPath),
+ );
+ await removeSandboxIfExists(
+ module,
+ metadata?.sandboxName ?? createProviderName("eve-sbx-ses", input.sessionIdentity),
+ );
+ if (metadata?.stateSnapshotName !== undefined) {
+ await removeSandboxIfExists(module, microsandboxRestoredSandboxName(metadata));
+ await removeSnapshotIfExists(module, metadata.stateSnapshotName);
+ }
+ }
+ await rm(sessionRootPath, { force: true, recursive: true });
+ },
+ );
+}
+
function resolveMicrosandboxImage(
session: Readonly<MicrosandboxSessionMetadata> | null,
template: MicrosandboxTemplateMetadata | undefined,
@@ -379,29 +420,31 @@ function requirePreparedMicrosandboxTemplate(
function createHandle(
sandbox: MicrosandboxVm,
- _optionsHash: string,
- onShutdown?: () => void,
+ context: SandboxProviderSessionContext,
+ sessionIdentity: string,
): SandboxProviderHandle<NetworkPolicySandboxSession> {
const session = buildSandboxSession(
createMicrosandboxInternalSession(sandbox),
async (policy) => {
- await sandbox.setNetworkPolicy(policy);
+ await withMicrosandboxLifecycleLock(context.storagePath, sessionIdentity, () =>
+ sandbox.setNetworkPolicy(policy),
+ );
},
);
return {
sandbox: session,
async onSandboxDelete() {
- await sandbox.shutdown();
- await sandbox.removePersisted();
- onShutdown?.();
+ await deleteMicrosandboxSession({ context, sessionIdentity });
},
async onSandboxStop() {
- await sandbox.stop();
- onShutdown?.();
+ await withMicrosandboxLifecycleLock(context.storagePath, sessionIdentity, () =>
+ sandbox.stop(),
+ );
},
async onRuntimeShutdown() {
- onShutdown?.();
- await sandbox.shutdown();
+ await withMicrosandboxLifecycleLock(context.storagePath, sessionIdentity, () =>
+ sandbox.shutdown(),
+ );
},
};
}
@@ -409,15 +452,3 @@ function createHandle(
function createMicrosandboxInternalSession(sandbox: MicrosandboxVm): InternalSandboxSession {
return createFileBackedInternalSandboxSession({ sandbox });
}
-
-function createActiveMicrosandboxSessionKey(sessionRootPath: string, optionsHash: string): string {
- return `${sessionRootPath}\0${optionsHash}`;
-}
-
-function cacheHandle(
- key: string,
- handle: SandboxProviderHandle<NetworkPolicySandboxSession>,
-): SandboxProviderHandle<NetworkPolicySandboxSession> {
- activeMicrosandboxSessionHandles.set(key, handle);
- return handle;
-}
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-lock.scenario.test.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-lock.scenario.test.ts
new file mode 100644
index 000000000..ebe162641
--- /dev/null
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-lock.scenario.test.ts
@@ -0,0 +1,93 @@
+import { spawn } from "node:child_process";
+import { once } from "node:events";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { setTimeout } from "node:timers/promises";
+import { describe, expect, it } from "vitest";
+
+import { withMicrosandboxLifecycleLock } from "#execution/sandbox/bindings/microsandbox-lock.js";
+
+// The in-memory lifecycle tests isolate framework caches. This test owns the
+// independent OS-lock contract: another process must not enter while the lock
+// is held, and process death must release the lock.
+describe("microsandbox cross-process lifecycle lock", () => {
+ it.each(["timer", "unresolved"])(
+ "excludes another process and releases the lock when the owner crashes (%s)",
+ async (waiting) => {
+ const storagePath = await mkdtemp(join(tmpdir(), "eve-microsandbox-lock-"));
+ const source = new URL("./microsandbox-lock.ts", import.meta.url).href;
+ const child = spawn(
+ process.execPath,
+ [
+ "--input-type=module",
+ "-e",
+ `
+ import { withMicrosandboxLifecycleLock } from ${JSON.stringify(source)};
+ await withMicrosandboxLifecycleLock(${JSON.stringify(storagePath)}, "session", async () => {
+ process.stdout.write("held\\n");
+ if (${JSON.stringify(waiting)} === "timer") {
+ await new Promise((resolve) => setTimeout(resolve, 60_000));
+ } else {
+ setInterval(() => {}, 1000);
+ await new Promise(() => {});
+ }
+ });
+ `,
+ ],
+ { stdio: ["ignore", "pipe", "pipe"] },
+ );
+ const exited = once(child, "exit");
+ let pending: Promise<void> | undefined;
+ try {
+ const ready = await Promise.race([
+ once(child.stdout, "data").then(([data]) => data.toString()),
+ exited.then(([code, signal]) => {
+ throw new Error(`Lock holder exited: ${code ?? signal}`);
+ }),
+ ]);
+ expect(ready).toBe("held\n");
+ let entered!: () => void;
+ const acquired = new Promise<void>((resolve) => {
+ entered = resolve;
+ });
+ pending = withMicrosandboxLifecycleLock(storagePath, "session", async () => {
+ entered();
+ });
+ expect(
+ await Promise.race([acquired.then(() => "entered"), setTimeout(150, "excluded")]),
+ ).toBe("excluded");
+
+ child.kill("SIGKILL");
+ await exited;
+ await pending;
+ await acquired;
+ } finally {
+ if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
+ await exited;
+ await pending;
+ await rm(storagePath, { force: true, recursive: true });
+ }
+ },
+ );
+
+ it("doesn't make another session wait for a session holding its lock", async () => {
+ const storagePath = await mkdtemp(join(tmpdir(), "eve-microsandbox-lock-"));
+ let release!: () => void;
+ let held!: () => void;
+ const holding = new Promise<void>((resolve) => (held = resolve));
+ const alice = withMicrosandboxLifecycleLock(storagePath, "alice-session", async () => {
+ held();
+ await new Promise<void>((resolve) => (release = resolve));
+ });
+ try {
+ await holding;
+ const bob = withMicrosandboxLifecycleLock(storagePath, "bob-session", async () => "entered");
+ expect(await Promise.race([bob, setTimeout(1000, "waited")])).toBe("entered");
+ } finally {
+ release();
+ await alice;
+ await rm(storagePath, { force: true, recursive: true });
+ }
+ });
+});
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-lock.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-lock.ts
new file mode 100644
index 000000000..7bad71be9
--- /dev/null
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-lock.ts
@@ -0,0 +1,55 @@
+import { mkdir } from "node:fs/promises";
+import { join } from "node:path";
+import { setTimeout } from "node:timers/promises";
+
+import { createSandboxProviderIdentity } from "#execution/sandbox/provider-identity.js";
+
+// A pending promise without an event source does not keep its async frame alive
+// for GC. Keep the native connection alive until the operation settles.
+const activeLocks = new Set<import("node:sqlite").DatabaseSync>();
+
+/**
+ * Serialize one session's native lifecycle transitions across processes,
+ * including cleanup. Sessions share a bounded set of lock files, so unrelated
+ * sessions rarely wait on each other and lock files never accumulate.
+ */
+export async function withMicrosandboxLifecycleLock<T>(
+ storagePath: string,
+ sessionIdentity: string,
+ operation: () => Promise<T>,
+): Promise<T> {
+ // SQLite's OS lock is released on process death. Heartbeat/stale-file locks
+ // can admit two owners when a live process pauses, which would destroy a VM.
+ // Keep the databases outside session directories and never unlink them:
+ // waiters must always lock the same inode, even while cleanup removes a session.
+ const directory = join(storagePath, "microsandbox", "locks");
+ await mkdir(directory, { recursive: true });
+ const stripe = createSandboxProviderIdentity({ sessionIdentity }).slice(0, 2);
+ const { DatabaseSync } = await import("node:sqlite");
+ const database = new DatabaseSync(join(directory, `${stripe}.sqlite`));
+ activeLocks.add(database);
+ const deadline = Date.now() + 10 * 60_000;
+ try {
+ for (;;) {
+ try {
+ database.exec("BEGIN IMMEDIATE");
+ break;
+ } catch (error) {
+ if (database.isTransaction) database.exec("ROLLBACK");
+ if (!(error instanceof Error && "errcode" in error && error.errcode === 5)) throw error;
+ if (Date.now() >= deadline) {
+ throw new Error(
+ "Timed out waiting for another process to finish a microsandbox lifecycle operation.",
+ { cause: error },
+ );
+ }
+ await setTimeout(100);
+ }
+ }
+ return await operation();
+ } finally {
+ // Closing rolls back the empty transaction and releases the OS lock.
+ database.close();
+ activeLocks.delete(database);
+ }
+}
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 3b5522bea..629d7a965 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.test.ts
@@ -193,7 +193,7 @@ describe.skipIf(process.platform === "win32")("connectMicrosandbox", () => {
expect(metadataState.writeSessionMetadata).toHaveBeenLastCalledWith(
"/tmp/eve-microsandbox-session/metadata.json",
expect.objectContaining({
- sandboxName: expect.stringMatching(/^eve-sbx-ses-/u),
+ sandboxName: runtime.createdSandboxName,
stateSnapshotName: "eve-sbx-state-existing",
}),
);
@@ -645,6 +645,7 @@ function createMockMicrosandboxModule(
options: { readonly snapshots?: readonly string[]; readonly status?: string } = {},
) {
let createdFromSnapshot = "";
+ let createdSandboxName = "";
const removedSnapshots: string[] = [];
const oldHandle = {
status: options.status ?? "running",
@@ -663,10 +664,12 @@ function createMockMicrosandboxModule(
const module = {
MicrosandboxError: class extends Error {},
Sandbox: {
- async get() {
+ async get(name: string) {
+ if (name !== "eve-sbx-ses-old") throw new Error(`sandbox ${name} not found`);
return oldHandle;
},
- builder() {
+ builder(name: string) {
+ createdSandboxName = name;
return createMockSandboxBuilder((fromSnapshot) => {
createdFromSnapshot = fromSnapshot;
return createMockMicrosandbox();
@@ -690,6 +693,9 @@ function createMockMicrosandboxModule(
get createdFromSnapshot() {
return createdFromSnapshot;
},
+ get createdSandboxName() {
+ return createdSandboxName;
+ },
module: module as never,
removedSnapshots,
};
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.ts
index d61597970..b79568e66 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.ts
@@ -424,6 +424,13 @@ export async function connectMicrosandbox(input: {
);
}
+export function microsandboxRestoredSandboxName(metadata: MicrosandboxSessionMetadata): string {
+ return createProviderName(
+ "eve-sbx-restore",
+ JSON.stringify([metadata.sandboxName, metadata.stateSnapshotName]),
+ );
+}
+
async function restoreMicrosandboxSessionSnapshot(input: {
readonly metadata: MicrosandboxSessionMetadata;
readonly metadataPath: string;
@@ -439,17 +446,28 @@ async function restoreMicrosandboxSessionSnapshot(input: {
return null;
}
- const sandboxName = createProviderName("eve-sbx-ses", `${input.sessionKey}:${randomUUID()}`);
- const sandbox = await createMicrosandbox({
- fromSnapshot: input.metadata.stateSnapshotName,
- module: input.module,
- name: sandboxName,
- networkPolicy: input.metadata.networkPolicy,
- options: input.options,
- tags: input.tags,
- user: MICROSANDBOX_USER,
- workdir: WORKSPACE_ROOT,
+ const sandboxName = microsandboxRestoredSandboxName(input.metadata);
+ // A previous process may have booted the restore target before publishing
+ // metadata. Reuse that target rather than abandoning its running work.
+ const existing = await input.module.Sandbox.get(sandboxName).catch((error: unknown) => {
+ if (isMicrosandboxNotFoundError(error)) return null;
+ throw error;
});
+ const sandbox =
+ existing === null
+ ? await createMicrosandbox({
+ fromSnapshot: input.metadata.stateSnapshotName,
+ module: input.module,
+ name: sandboxName,
+ networkPolicy: input.metadata.networkPolicy,
+ options: input.options,
+ tags: input.tags,
+ user: MICROSANDBOX_USER,
+ workdir: WORKSPACE_ROOT,
+ })
+ : existing.status === "running" || existing.status === "draining"
+ ? await existing.connectWithTimeout(MICROSANDBOX_CONNECT_TIMEOUT_MS)
+ : await existing.startDetached();
await removeSandboxIfExists(input.module, input.metadata.sandboxName);
const vm = new MicrosandboxVm(
@@ -648,7 +666,6 @@ async function createMicrosandbox(input: {
.labels(resolveMicrosandboxLabels(input.tags))
.memory(input.options.memoryMiB)
.pullPolicy(input.options.pullPolicy)
- .replace()
.workdir(input.workdir);
if (input.fromSnapshot !== undefined) {
@@ -682,7 +699,7 @@ async function createMicrosandbox(input: {
});
}
-async function removeSandboxIfExists(
+export async function removeSandboxIfExists(
module: MicrosandboxModule,
sandboxName: string,
): Promise<void> {
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox.ts
index ec2809618..3a4b5bbc5 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox.ts
@@ -6,6 +6,8 @@ type NetworkPolicySandboxSession = SandboxSession & {
import { enrichMicrosandboxError } from "#execution/sandbox/bindings/microsandbox-create.js";
import {
createMicrosandboxHandle,
+ deleteMicrosandboxSession,
+ microsandboxSessionIdentity,
type MicrosandboxPreparedArtifact,
prewarmMicrosandboxTemplate,
} from "#execution/sandbox/bindings/microsandbox-lifecycle.js";
@@ -32,7 +34,6 @@ export { pruneMicrosandboxTemplates } from "#execution/sandbox/bindings/microsan
export const MICROSANDBOX_PROVIDER_NAME = "microsandbox";
export type MicrosandboxProviderSessionState = {
- readonly optionsHash: string;
readonly sessionIdentity: string;
readonly version: 3;
};
@@ -53,6 +54,12 @@ export function createMicrosandboxSandboxProvider(
);
return {
+ async onSessionEnd(context, state) {
+ await deleteMicrosandboxSession({
+ context,
+ sessionIdentity: state?.sessionIdentity ?? microsandboxSessionIdentity(context),
+ });
+ },
async prepare(context) {
const dockerfile = await materializeSandboxDockerfile({
files: context.files,
@@ -82,14 +89,6 @@ export function createMicrosandboxSandboxProvider(
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,
@@ -103,31 +102,20 @@ export function createMicrosandboxSandboxProvider(
},
async start(context, runtimeOptions, artifactValue) {
const artifact = requireArtifact(artifactValue);
- const result = await createMicrosandboxHandle({
+ return await createMicrosandboxHandle({
artifact,
context,
+ createIfMissing: true,
options,
optionsHash,
providerName: MICROSANDBOX_PROVIDER_NAME,
runtimeOptions,
+ sessionIdentity: microsandboxSessionIdentity(context),
});
- 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) ||
@@ -149,14 +137,9 @@ 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,
- };
+ return { sessionIdentity: state.sessionIdentity, version: 3 };
}
diff --git a/packages/eve/src/execution/sandbox/bindings/vercel-lifecycle.ts b/packages/eve/src/execution/sandbox/bindings/vercel-lifecycle.ts
index 34d72077e..a5ddd4694 100644
--- a/packages/eve/src/execution/sandbox/bindings/vercel-lifecycle.ts
+++ b/packages/eve/src/execution/sandbox/bindings/vercel-lifecycle.ts
@@ -2,6 +2,8 @@ import {
getVercelSandboxFetch,
resolveVercelSandboxCredentials,
} from "#execution/sandbox/bindings/vercel-credentials.js";
+import { isVercelSandboxMissingError } from "#execution/sandbox/bindings/vercel-errors.js";
+import { getNamedVercelSandbox } from "#execution/sandbox/bindings/vercel-lookup.js";
import type {
VercelCreateOptions,
VercelModule,
@@ -18,6 +20,27 @@ export async function deleteVercelSandbox(input: {
await deleteVercelSandboxRecord(input);
}
+/** Deletes the sandbox with this name, if there is one. */
+export async function deleteNamedVercelSandbox(input: {
+ readonly createOptions: VercelCreateOptions;
+ readonly loadDeleteSandboxModule: () => Promise<VercelModule>;
+ readonly sandboxName: string;
+}): Promise<void> {
+ const sandbox = await getNamedVercelSandbox({
+ createOptions: input.createOptions,
+ sandboxModule: await input.loadDeleteSandboxModule(),
+ sandboxName: input.sandboxName,
+ });
+ if (sandbox === null) return;
+ try {
+ await stopVercelSandbox(sandbox);
+ await sandbox.delete({ deleteOrphanSnapshots: true });
+ } catch (error) {
+ // Another cleanup attempt deleted it first.
+ if (!isVercelSandboxMissingError(error)) throw error;
+ }
+}
+
export async function deleteUnusableVercelSandbox(input: {
readonly createOptions: VercelCreateOptions;
readonly loadDeleteSandboxModule: () => Promise<VercelModule>;
diff --git a/packages/eve/src/execution/sandbox/bindings/vercel.test.ts b/packages/eve/src/execution/sandbox/bindings/vercel.test.ts
index 368aaad38..ab8ba0461 100644
--- a/packages/eve/src/execution/sandbox/bindings/vercel.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/vercel.test.ts
@@ -624,6 +624,48 @@ describe("createVercelSandbox", () => {
);
});
+ describe("session identity and cleanup", () => {
+ function session() {
+ const fake = createFakeVercelProvider();
+ const provider = createTestVercelSandbox({
+ loadDeleteSandboxModule: async () => fake.sandboxModule as never,
+ loadSandboxModule: async () => fake.sandboxModule as never,
+ });
+ const start = (
+ input: { readonly networkPolicy?: "deny-all"; readonly snapshotId?: string } = {},
+ ) =>
+ provider.start({
+ appRoot: "/tmp/test-app-root",
+ options: input.networkPolicy === undefined ? {} : { networkPolicy: input.networkPolicy },
+ prepared: { snapshotId: input.snapshotId ?? "snapshot-a" },
+ sandboxName: "session-key",
+ });
+ const end = (state: { readonly sandboxName: string; readonly version: 3 } | null) =>
+ provider.endSession({ appRoot: "/tmp/test-app-root", sandboxName: "session-key", state });
+ return { end, fake, start };
+ }
+
+ it("keeps one sandbox per session key across concurrent starts, open options, and deployments", async () => {
+ const { fake, start } = session();
+
+ const [first, second] = await Promise.all([start(), start()]);
+ const later = await start({ networkPolicy: "deny-all", snapshotId: "snapshot-b" });
+
+ expect(fake.sandboxes.size).toBe(1);
+ expect(second.state).toEqual(first.state);
+ expect(later.state).toEqual(first.state);
+ });
+
+ it("deletes the session's sandbox by key when no state was recorded, and succeeds once it is gone", async () => {
+ const { end, fake, start } = session();
+ await start();
+
+ await end(null);
+ expect(fake.sandboxes.size).toBe(0);
+ await expect(end(null)).resolves.toBeUndefined();
+ });
+ });
+
describe("tool sessions", () => {
const DAY_MS = 24 * 60 * 60 * 1000;
// What the Sandbox API answers a resume whose snapshot expired or was deleted.
@@ -1409,7 +1451,7 @@ describe("createVercelSandbox", () => {
);
});
- it("forwards env with the AI_AGENT default to runCommand when spawning a process", async () => {
+ it("creates with the AI_AGENT default and forwards per-command env when spawning a process", async () => {
const templateSandbox = createMockSandbox({ name: "template" });
const sessionSandbox = createMockSandbox({ name: "session" });
const sandboxModule = {
@@ -1435,6 +1477,9 @@ describe("createVercelSandbox", () => {
vi.mocked(sessionSandbox.runCommand).mockResolvedValue(createMockDetachedCommand() as never);
vi.mocked(sessionSandbox.runCommand).mockClear();
+ expect(sandboxModule.Sandbox.create).toHaveBeenCalledWith(
+ expect.objectContaining({ env: { AI_AGENT: "eve" } }),
+ );
await handle.sandbox.spawn({
command: "printenv DEPLOY_ENV",
env: { DEPLOY_ENV: "staging" },
@@ -1445,51 +1490,84 @@ describe("createVercelSandbox", () => {
expect.objectContaining({
args: ["-lc", "printenv DEPLOY_ENV"],
cmd: "bash",
- env: { AI_AGENT: "eve", DEPLOY_ENV: "staging" },
+ env: { DEPLOY_ENV: "staging" },
}),
);
});
- it("lets environment env override the AI_AGENT default when running a command", async () => {
- const templateSandbox = createMockSandbox({ name: "template" });
- const sessionSandbox = createMockSandbox({ name: "session" });
- const sandboxModule = {
- Sandbox: {
- create: createSandboxesInOrder(templateSandbox, sessionSandbox),
- get: vi.fn().mockResolvedValue(null),
- },
- };
-
+ it("keeps native env, mounts, and network options when reopening a key with changed options", async () => {
+ const fake = createFakeVercelProvider();
const provider = createTestVercelSandbox({
- createOptions: { env: { AI_AGENT: "alice-bot" } },
- loadSandboxModule: async () => sandboxModule as never,
+ loadSandboxModule: async () => fake.sandboxModule as never,
+ });
+ const first = await provider.start({
+ appRoot: "/tmp/test-app-root",
+ sandboxName: "immutable-options",
+ prepared: {},
+ options: {
+ env: { AI_AGENT: "alice-bot", REVIEW_VALUE: "initial" },
+ mounts: { "/workspace/data": { drive: "initial-drive", mode: "read-write" } },
+ networkPolicy: "deny-all",
+ },
});
+ const created = fake.sandboxModule.Sandbox.create.mock.calls[0]![0] as MockCreateOptions & {
+ env: Record<string, string>;
+ mounts: object;
+ };
+ const sandbox = [...fake.sandboxes.values()][0]!;
+ // The native sandbox keeps create-time env. Commands may override individual
+ // variables, but reconnecting does not change those native defaults.
+ sandbox.runCommand.mockImplementation(
+ async (command: { detached?: boolean; env?: Record<string, string> }) =>
+ command.detached
+ ? (createMockDetachedCommand([
+ {
+ data: JSON.stringify({ ...created.env, ...command.env }),
+ stream: "stdout",
+ },
+ ]) as never)
+ : createMockCommandResult(),
+ );
+ const readEnv = async (handle: typeof first.handle) =>
+ JSON.parse((await handle.sandbox.run({ command: "env" })).stdout);
+ expect(await readEnv(first.handle)).toEqual({ AI_AGENT: "alice-bot", REVIEW_VALUE: "initial" });
- await provider.prepare({
+ const reopened = await provider.start({
appRoot: "/tmp/test-app-root",
- seedFiles: [],
+ sandboxName: "immutable-options",
+ prepared: { snapshotId: "new-deployment-template" },
+ options: {
+ env: { AI_AGENT: "bob-bot", REVIEW_VALUE: "changed" },
+ mounts: { "/workspace/data": { drive: "changed-drive", mode: "snapshot" } },
+ networkPolicy: "allow-all",
+ },
});
- const handle = await provider.openSession({
+ const resumed = await provider.openSession({
appRoot: "/tmp/test-app-root",
- sandboxName: "session-key",
+ sandboxName: "immutable-options",
+ prepared: {},
+ existing: first.state,
});
-
- vi.mocked(sessionSandbox.runCommand).mockResolvedValue(createMockDetachedCommand() as never);
- vi.mocked(sessionSandbox.runCommand).mockClear();
-
- await handle.sandbox.run({
- command: "printenv DEPLOY_ENV",
- env: { DEPLOY_ENV: "production" },
+ expect(await readEnv(reopened.handle)).toEqual({
+ AI_AGENT: "alice-bot",
+ REVIEW_VALUE: "initial",
});
-
- expect(sessionSandbox.runCommand).toHaveBeenCalledTimes(1);
- expect(sessionSandbox.runCommand).toHaveBeenCalledWith(
- expect.objectContaining({
- args: ["-lc", "printenv DEPLOY_ENV"],
- cmd: "bash",
- env: { AI_AGENT: "alice-bot", DEPLOY_ENV: "production" },
- }),
- );
+ expect(await readEnv(resumed)).toEqual({ AI_AGENT: "alice-bot", REVIEW_VALUE: "initial" });
+ const overridden = await resumed.sandbox.run({
+ command: "env",
+ env: { REVIEW_VALUE: "per-command" },
+ });
+ expect(JSON.parse(overridden.stdout)).toEqual({
+ AI_AGENT: "alice-bot",
+ REVIEW_VALUE: "per-command",
+ });
+ expect(fake.sandboxModule.Sandbox.create).toHaveBeenCalledTimes(1);
+ expect(created.mounts).toEqual({
+ "/workspace/data": { drive: "initial-drive", mode: "read-write" },
+ });
+ expect(sandbox.update.mock.calls.filter(([update]) => "networkPolicy" in update)).toEqual([
+ [{ networkPolicy: "deny-all" }],
+ ]);
});
it("prepares the base runtime during sandbox init", async () => {
diff --git a/packages/eve/src/execution/sandbox/bindings/vercel.ts b/packages/eve/src/execution/sandbox/bindings/vercel.ts
index dc899f2b5..633bac131 100644
--- a/packages/eve/src/execution/sandbox/bindings/vercel.ts
+++ b/packages/eve/src/execution/sandbox/bindings/vercel.ts
@@ -61,6 +61,7 @@ import {
isVercelSnapshotCreated,
} from "#execution/sandbox/bindings/vercel-lookup.js";
import {
+ deleteNamedVercelSandbox,
deleteUnusableVercelSandbox,
deleteVercelSandbox,
stopVercelSandbox,
@@ -122,6 +123,7 @@ export function createVercelSandbox(
(async () => await import("#compiled/@vercel/sandbox/index.js"));
const createOptions: ResolvedVercelCreateOptions = {
...input.createOptions,
+ env: { ...SANDBOX_AGENT_ENV, ...input.createOptions?.env },
timeout: input.createOptions?.timeout ?? DEFAULT_SANDBOX_TIMEOUT_MS,
};
const createSandbox = input.createSandbox ?? createVercelEveImageSandbox;
@@ -135,7 +137,11 @@ export function createVercelSandbox(
const artifact = requirePreparedVercelTemplate(artifactValue);
const { mounts, ...runtimeOptions } = options ?? {};
const toolSession = isToolSessionId(context.session.id);
- const authoredCreateOptions = { ...createOptions, ...runtimeOptions };
+ const authoredCreateOptions = {
+ ...createOptions,
+ ...runtimeOptions,
+ env: { ...SANDBOX_AGENT_ENV, ...(runtimeOptions.env ?? createOptions.env) },
+ };
const sessionCreateOptions = toolSession
? withToolSessionRetention(authoredCreateOptions)
: authoredCreateOptions;
@@ -207,6 +213,13 @@ export function createVercelSandbox(
}
const implementation: ReturnType<typeof createVercelSandbox> = {
+ async onSessionEnd(context, state) {
+ await deleteNamedVercelSandbox({
+ createOptions,
+ loadDeleteSandboxModule,
+ sandboxName: state?.sandboxName ?? vercelSessionName(context.session.id),
+ });
+ },
async prepare(context) {
const seedFiles = providerResourceTargetFiles(context.resources);
if (
@@ -258,7 +271,7 @@ export function createVercelSandbox(
return createHandle({ createOptions, loadDeleteSandboxModule, sandbox });
},
async start(context, options, artifact) {
- const sandboxName = vercelSessionName(context.session.id, options, artifact, createOptions);
+ const sandboxName = vercelSessionName(context.session.id);
const handle = await openSession(context, options, artifact, sandboxName);
return {
handle,
@@ -266,25 +279,18 @@ export function createVercelSandbox(
};
},
};
- // `start` finds a session's sandbox by name, so keyed tool sessions can reuse it.
+ // Saved filesystems expire, so a keyed tool session's sandbox is bounded.
// A handle is only an SDK client, so a call that ends has nothing to free.
return withToolSessionSandboxes(implementation);
}
-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)}`;
+/**
+ * The session's sandbox name. Sandbox names are unique within a Vercel
+ * project, so the session id alone keeps it stable across deployments and
+ * open options; those apply only when the sandbox is created.
+ */
+function vercelSessionName(sessionId: string): string {
+ return `eve-sbx-vercel-${createSandboxProviderIdentity({ sessionId, version: 2 }).slice(0, 32)}`;
}
function vercelIdentityOptions(options: object | undefined): object | undefined {
@@ -397,7 +403,7 @@ async function prepareTemplateSnapshot(
await applyInitialVercelNetworkPolicy(sandbox, input.createOptions.networkPolicy);
const templateSession = buildSandboxSession(
- createVercelInternalSandboxSession(sandbox, input.createOptions.env),
+ createVercelInternalSandboxSession(sandbox),
createVercelNetworkPolicySetter(sandbox),
);
@@ -600,7 +606,7 @@ function createHandle(input: {
return {
sandbox: {
...buildSandboxSession(
- createVercelInternalSandboxSession(sandbox, input.createOptions.env),
+ createVercelInternalSandboxSession(sandbox),
createVercelNetworkPolicySetter(sandbox),
),
name: sandbox.name,
@@ -626,11 +632,7 @@ function createHandle(input: {
};
}
-function createVercelInternalSandboxSession(
- sandbox: VercelSandbox,
- environmentEnv: Readonly<Record<string, string>> | undefined,
-): InternalSandboxSession {
- const baseEnv = { ...SANDBOX_AGENT_ENV, ...environmentEnv };
+function createVercelInternalSandboxSession(sandbox: VercelSandbox): InternalSandboxSession {
return {
resolvePath: resolveVercelSandboxPath,
async spawn(options: SandboxSpawnOptions): Promise<SandboxProcess> {
@@ -639,7 +641,7 @@ function createVercelInternalSandboxSession(
cmd: "bash",
cwd: options.workingDirectory ?? WORKSPACE_ROOT,
detached: true,
- env: { ...baseEnv, ...options.env },
+ env: options.env,
signal: options.abortSignal,
});
return adaptMultiplexedCommandToSandboxProcess({
diff --git a/packages/eve/src/execution/sandbox/ensure.test.ts b/packages/eve/src/execution/sandbox/ensure.test.ts
index 759c7667c..d4feaa2ae 100644
--- a/packages/eve/src/execution/sandbox/ensure.test.ts
+++ b/packages/eve/src/execution/sandbox/ensure.test.ts
@@ -7,7 +7,10 @@ import { importConversation, readLegacySnapshot } from "#execution/legacy-sessio
import { ensureSandboxAccess } from "#execution/sandbox/ensure.js";
import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";
import { defineParentSandbox, defineSandbox } from "#public/definitions/sandbox.js";
-import { defineSandboxProvider } from "#shared/sandbox-provider.js";
+import {
+ defineSandboxProvider,
+ type SandboxProviderSessionContext,
+} from "#shared/sandbox-provider.js";
import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";
import { loadSandboxPreparedArtifact } from "#runtime/sandbox/prepared-artifacts.js";
@@ -16,8 +19,9 @@ vi.mock("#runtime/sandbox/prepared-artifacts.js", () => ({
loadSandboxPreparedArtifact: vi.fn(async () => null),
}));
-function fixture(setup?: () => void, returnCopy = false, onSessionEnd?: () => Promise<void>) {
+function fixture(setup?: () => void, returnCopy = false) {
const deleteSandbox = vi.fn(async () => {});
+ const onSessionEnd = vi.fn(async () => {});
const stopSandbox = vi.fn(async () => {});
const shutdownSandbox = vi.fn(async () => {});
const create = vi.fn(async () => {
@@ -29,19 +33,13 @@ function fixture(setup?: () => void, returnCopy = false, onSessionEnd?: () => Pr
onSandboxStop: stopSandbox,
};
});
- const start = vi.fn(async () => ({ handle: await create(), state: null }));
+ const start = vi.fn(async (context: SandboxProviderSessionContext) => ({
+ handle: await create(),
+ state: { key: context.session.id },
+ }));
const provider = defineSandboxProvider({
name: "test",
- environment: () => {
- const implementation = {
- prepare: async () => null,
- resume: create,
- start,
- };
- return onSessionEnd === undefined
- ? implementation
- : Object.assign(implementation, { onSessionEnd });
- },
+ environment: () => ({ onSessionEnd, prepare: async () => null, resume: create, start }),
});
const environment = provider.environment();
const selector = defineSandbox(async () => {
@@ -73,6 +71,52 @@ function fixture(setup?: () => void, returnCopy = false, onSessionEnd?: () => Pr
stopSandbox,
};
}
+/** A provider that honors the contract: `start` upserts on the session id, and cleanup deletes by it. */
+function upsertingFixture() {
+ const live = new Map<string, ReturnType<typeof mockSandbox>>();
+ const handle = (sessionId: string) => {
+ let sandbox = live.get(sessionId);
+ if (sandbox === undefined) {
+ sandbox = mockSandbox();
+ live.set(sessionId, sandbox);
+ }
+ return {
+ sandbox: sandbox.session,
+ onRuntimeShutdown: async () => {},
+ onSandboxDelete: async () => void live.delete(sessionId),
+ onSandboxStop: async () => {},
+ };
+ };
+ const environment = defineSandboxProvider({
+ name: "upserting",
+ environment: () => ({
+ onSessionEnd: async (context: SandboxProviderSessionContext) =>
+ void live.delete(context.session.id),
+ prepare: async () => null,
+ resume: async (context: SandboxProviderSessionContext) => handle(context.session.id),
+ start: async (context: SandboxProviderSessionContext) => ({
+ handle: handle(context.session.id),
+ state: null,
+ }),
+ }),
+ }).environment();
+ const registry: RuntimeSandboxRegistry = {
+ sandbox: {
+ definition: {
+ environment,
+ kind: "independent",
+ logicalPath: "sandbox.ts",
+ selector: defineSandbox(() => environment.open()),
+ revisionHash: "hash",
+ sourceId: "sandbox",
+ sourceKind: "module",
+ },
+ workspaceResourceRoot: { logicalPath: "", rootEntries: [] },
+ },
+ };
+ return { live, registry };
+}
+
async function open(
registry: RuntimeSandboxRegistry,
id = "session-1",
@@ -192,12 +236,18 @@ describe("ensureSandboxAccess", () => {
expect(value.start).toHaveBeenCalledOnce();
});
- it("passes empty live options when a child inherits its parent sandbox", async () => {
- const value = fixture();
+ it("runs the parent's selector when a child that inherits its sandbox opens it first", async () => {
+ const setup = vi.fn();
+ const value = fixture(setup);
- await open(inheritingChildRegistry(value.registry));
+ await open(inheritingChildRegistry(value.registry), "parent-session", null, "child");
- expect(value.create).toHaveBeenCalledOnce();
+ expect(setup).toHaveBeenCalledOnce();
+ expect(value.start).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ session: expect.objectContaining({ id: "parent-session" }) }),
+ undefined,
+ null,
+ );
});
it("rejects a fabricated sandbox", async () => {
@@ -232,7 +282,9 @@ describe("ensureSandboxAccess", () => {
const [owner, subagent] = await Promise.all([open(value.registry), open(value.registry)]);
expect(value.start).toHaveBeenCalledOnce();
expect(value.create).toHaveBeenCalledTimes(2);
- expect(await subagent.access.captureState()).toEqual(await owner.access.captureState());
+ expect((await subagent.access.captureState()).session).toEqual(
+ (await owner.access.captureState()).session,
+ );
});
it("shares the parent's start with a subagent that inherits its sandbox", async () => {
@@ -243,7 +295,9 @@ describe("ensureSandboxAccess", () => {
]);
expect(value.start).toHaveBeenCalledOnce();
expect(value.create).toHaveBeenCalledTimes(2);
- expect(await subagent.access.captureState()).toEqual(await owner.access.captureState());
+ expect((await subagent.access.captureState()).session).toEqual(
+ (await owner.access.captureState()).session,
+ );
});
it("lets only one waiter retry after a shared start fails", async () => {
@@ -306,33 +360,48 @@ describe("ensureSandboxAccess", () => {
});
it("passes terminal cleanup to the provider from durable state", async () => {
- const onSessionEnd = vi.fn(async () => {});
- const value = fixture(undefined, false, onSessionEnd);
+ const value = fixture();
const { access } = await open(value.registry);
- await access.end?.("expired");
+ await access.end("expired");
- expect(onSessionEnd).toHaveBeenCalledExactlyOnceWith(
+ expect(value.onSessionEnd).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({ session: expect.objectContaining({ id: "session-1" }) }),
- null,
- null,
+ { key: "session-1" },
{ reason: "expired" },
);
expect(value.deleteSandbox).not.toHaveBeenCalled();
await expect(access.captureState()).resolves.toEqual({ session: null });
});
- it("falls back to resumed handle deletion when the provider has no terminal hook", async () => {
- const value = fixture();
- const { access } = await open(value.registry);
+ it("removes a sandbox a sharing child opened when the parent session ends without opening it", async () => {
+ const value = upsertingFixture();
+ const child = await ensureSandboxAccess({
+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
+ nodeId: "child",
+ ownsSandbox: false,
+ registry: inheritingChildRegistry(value.registry),
+ sessionId: "parent-session",
+ state: null,
+ });
+ await child.get();
+ await child.end("completed");
+ expect([...value.live.keys()]).toEqual(["parent-session"]);
- await access.end?.("completed");
+ // The parent never opened the sandbox and has no checkpointed provider state.
+ const parent = await ensureSandboxAccess({
+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
+ nodeId: "__root__",
+ registry: value.registry,
+ sessionId: "parent-session",
+ state: null,
+ });
+ await parent.end("completed");
- expect(value.deleteSandbox).toHaveBeenCalledOnce();
- await expect(access.captureState()).resolves.toEqual({ session: null });
+ expect(value.live.size).toBe(0);
});
- it("does not start a sandbox just to end a session that never opened one", async () => {
+ it("cleans up an unrecorded key at session end without starting a sandbox", async () => {
const value = fixture();
const access = await ensureSandboxAccess({
compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
@@ -342,15 +411,20 @@ describe("ensureSandboxAccess", () => {
state: null,
});
- await access.end?.("expired");
+ await access.end("expired");
+ expect(value.onSessionEnd).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ session: expect.objectContaining({ id: "unused" }) }),
+ null,
+ { reason: "expired" },
+ );
expect(value.start).not.toHaveBeenCalled();
expect(value.create).not.toHaveBeenCalled();
});
it("does not end a sandbox borrowed from another session", async () => {
- const onSessionEnd = vi.fn(async () => {});
- const value = fixture(undefined, false, onSessionEnd);
+ const value = fixture();
+ const { onSessionEnd } = value;
const access = await ensureSandboxAccess({
compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
nodeId: "__root__",
diff --git a/packages/eve/src/execution/sandbox/ensure.ts b/packages/eve/src/execution/sandbox/ensure.ts
index 53e3db49f..4170f4459 100644
--- a/packages/eve/src/execution/sandbox/ensure.ts
+++ b/packages/eve/src/execution/sandbox/ensure.ts
@@ -40,7 +40,7 @@ import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-err
interface EnsureSandboxAccessInput {
readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
readonly nodeId: string;
- /** `false` when the sandbox outlives this access: it may not delete it, even after a failed start. */
+ /** `false` when the sandbox outlives this access: it may neither delete nor end it. */
readonly ownsSandbox?: boolean;
readonly registry: RuntimeSandboxRegistry;
readonly sessionId: string;
@@ -49,7 +49,11 @@ interface EnsureSandboxAccessInput {
/** The access `ensureSandboxAccess` builds, with what the opener may do beyond the sandbox API. */
export interface EnsuredSandboxAccess extends SandboxAccess {
- /** Permanently releases provider resources when the owning session ends. */
+ /**
+ * Permanently releases what the provider keeps under this access's key
+ * when the owning session ends, even when its last checkpoint recorded no
+ * sandbox. Waits for this access's open still in flight first.
+ */
end(reason: SandboxSessionEndReason): Promise<void>;
/**
* Lets go of the handle this access opened, if any, without stopping or
@@ -68,9 +72,9 @@ interface OpenedSandbox {
}
// Parent and subagent sessions that share a sandbox each build their own
-// access, so concurrent first use in one process would otherwise race to
-// start the same provider sandbox. Late arrivals resume from the winner's
-// state instead.
+// access. `start` is an upsert, so concurrent first use is safe, but in one
+// process late arrivals resume from the winner's state instead of running
+// the selector again.
const pendingSandboxStarts = new Map<string, Promise<SandboxSessionState | null>>();
export async function ensureSandboxAccess(
@@ -86,11 +90,12 @@ export async function ensureSandboxAccess(
let requiring: Promise<SandboxProviderHandle> | undefined;
const appRoot =
getRuntimeCompiledArtifactsSandboxAppRoot(input.compiledArtifactsSource) ?? process.cwd();
+ const captured = (): SandboxState => ({ session: persisted });
const registered = input.registry.sandbox;
if (registered === null) {
return {
async captureState() {
- return { session: persisted };
+ return captured();
},
async detach() {
return undefined;
@@ -103,26 +108,31 @@ export async function ensureSandboxAccess(
};
}
- 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;
+ function providerContext(turnId: string): SandboxProviderSessionContext {
+ const activeSession =
+ contextStorage.getStore() === undefined
+ ? {
+ auth: { current: null, initiator: null },
+ id: input.sessionId,
+ turn: { id: turnId, sequence: 0 },
+ }
+ : buildCallbackContext().session;
+ return {
+ host: createSandboxProviderHost(appRoot),
+ session: { ...activeSession, id: input.sessionId },
+ storagePath: resolveSandboxCacheDirectory(appRoot),
+ };
+ }
+
+ function activeDefinition() {
+ const definition = registered.inheritance?.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.`);
- }
+ return definition;
+ }
- const artifactNodeId = inherited?.nodeId ?? input.nodeId;
+ async function loadArtifact(provider: SandboxProviderRuntime) {
+ const artifactNodeId = registered.inheritance?.nodeId ?? input.nodeId;
const artifact = await loadSandboxPreparedArtifact({
compiledArtifactsSource: input.compiledArtifactsSource,
nodeId: artifactNodeId,
@@ -134,12 +144,26 @@ export async function ensureSandboxAccess(
templateKey: artifactNodeId,
});
}
+ return artifact;
+ }
- const context: SandboxProviderSessionContext = {
- host: createSandboxProviderHost(appRoot),
- session,
- storagePath: resolveSandboxCacheDirectory(appRoot),
- };
+ async function open(
+ provider: SandboxProviderRuntime,
+ options: object | undefined,
+ environment: object,
+ context: SandboxProviderSessionContext,
+ ): Promise<RuntimeSandboxSession> {
+ if (opening !== undefined) throw new Error("A sandbox definition can open only one sandbox.");
+ const definition = activeDefinition();
+ 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 artifact = await loadArtifact(provider);
const createHandle = async () => {
const result = await provider.implementation.start(context, options, artifact);
if (!isSandboxPreparedArtifact(result.state)) {
@@ -176,12 +200,9 @@ export async function ensureSandboxAccess(
return sandbox;
}
- async function resumePersisted(
- definition: Extract<typeof registered.definition, { readonly kind: "independent" }>,
- session: SandboxProviderSessionContext["session"],
- ): Promise<SandboxProviderHandle> {
+ async function resumePersisted(context: SandboxProviderSessionContext) {
if (persisted === null) throw new Error("Sandbox session state is missing.");
- const provider = getSandboxEnvironmentRuntime(definition.environment);
+ const provider = getSandboxEnvironmentRuntime(activeDefinition().environment);
if (persisted.providerName !== provider.providerName) {
throw new Error(
`Sandbox session state belongs to provider "${persisted.providerName}", not "${provider.providerName}".`,
@@ -192,24 +213,7 @@ export async function ensureSandboxAccess(
`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,
- });
- }
- const context: SandboxProviderSessionContext = {
- host: createSandboxProviderHost(appRoot),
- session,
- storagePath: resolveSandboxCacheDirectory(appRoot),
- };
+ const artifact = await loadArtifact(provider);
opening = provider.implementation
.resume(context, artifact, persisted.state)
.catch((error: unknown) => {
@@ -227,43 +231,35 @@ export async function ensureSandboxAccess(
}
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.`);
-
+ const definition = activeDefinition();
if (isEveDevEnvironment() && input.compiledArtifactsSource.kind === "disk") {
await ensureDevelopmentSandboxesPrepared({
compiledArtifactsSource: input.compiledArtifactsSource,
- nodeId: inherited?.nodeId ?? input.nodeId,
+ nodeId: registered.inheritance?.nodeId ?? input.nodeId,
providerName: getSandboxEnvironmentRuntime(definition.environment).providerName,
});
}
- 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 };
-
+ const context = providerContext("sandbox-initialization");
if (persisted !== null) {
- return await resumePersisted(definition, session);
+ return await resumePersisted(context);
}
- const startKey = `${inherited?.nodeId ?? input.nodeId}\0${input.sessionId}`;
+ // Apps hosted in one process can reuse a node id and a tool session id.
+ const startKey = [
+ appRoot,
+ registered.inheritance?.nodeId ?? input.nodeId,
+ input.sessionId,
+ ].join("\0");
// A failed start wakes every waiter at once; re-check so only one retries.
let concurrentStart = pendingSandboxStarts.get(startKey);
while (concurrentStart !== undefined) {
persisted = await concurrentStart;
- if (persisted !== null) return await resumePersisted(definition, session);
+ if (persisted !== null) return await resumePersisted(context);
concurrentStart = pendingSandboxStarts.get(startKey);
}
- const starting = startHandle(definition, session);
+ const starting = startHandle(context);
const sharedStart = starting.then(
() => persisted,
() => null,
@@ -278,54 +274,32 @@ export async function ensureSandboxAccess(
}
}
- async function startHandle(
- definition: Extract<typeof registered.definition, { readonly kind: "independent" }>,
- session: SandboxProviderSessionContext["session"],
- ): Promise<SandboxProviderHandle> {
- const inherited = registered.inheritance;
- if (inherited !== undefined) {
- await open(
- getSandboxEnvironmentRuntime(definition.environment),
- undefined,
- definition.environment,
- session,
+ /**
+ * Runs the owning sandbox definition, which for a subagent that shares its
+ * parent's sandbox is the parent's: whichever session opens the sandbox
+ * first creates it with the same options and initialization.
+ */
+ async function startHandle(context: SandboxProviderSessionContext) {
+ const definition = activeDefinition();
+ try {
+ const selected = await runWithSandboxConstructorRuntime(
+ {
+ open: ({ environment, options, provider }) =>
+ open(provider, options, environment, context),
+ },
+ async () => definition.selector({ session: context.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;
- // `start` may have found a sandbox an owner, or another call with the
- // same tool-session key, is using; only an owning access discards it.
- if (failed !== undefined && input.ownsSandbox !== false) {
- try {
- await failed.onSandboxDelete();
- } catch (cleanupError) {
- throw new AggregateError(
- [error, cleanupError],
- `Sandbox "${definition.logicalPath}" initialization and cleanup both failed.`,
- { cause: error },
- );
- }
- }
- throw error;
+ if (opened === undefined || selected !== opened.sandbox) {
+ throw new Error(`Sandbox "${definition.logicalPath}" must return the sandbox it opens.`);
}
+ } catch (error) {
+ // The sandbox stays: another session or call may share it, and the
+ // next access runs the selector again on it. Session end removes it.
+ opened = undefined;
+ opening = undefined;
+ persisted = null;
+ throw error;
}
-
- if (opened === undefined)
- throw new Error(`Sandbox "${definition.logicalPath}" did not open a provider handle.`);
trackActiveSandboxHandle({
handle: opened.handle,
providerName: opened.providerName,
@@ -343,102 +317,60 @@ export async function ensureSandboxAccess(
return requiring;
}
- const activeDefinition = registered.inheritance?.definition ?? registered.definition;
+ function forgetHandle() {
+ const current = opened;
+ if (current !== undefined) {
+ untrackActiveSandboxHandle({
+ handle: current.handle,
+ providerName: current.providerName,
+ sessionId: input.sessionId,
+ });
+ }
+ opened = undefined;
+ opening = undefined;
+ requiring = undefined;
+ return current;
+ }
+
+ const definition = registered.inheritance?.definition ?? registered.definition;
return {
- environment: activeDefinition.kind === "independent" ? activeDefinition.environment : undefined,
+ environment: definition.kind === "independent" ? definition.environment : undefined,
async captureState() {
if (opening !== undefined) await opening;
- return { session: persisted };
+ return captured();
},
async delete(deleteOptions) {
if (input.ownsSandbox === false)
throw new Error("Only the owning session can delete this sandbox.");
const current = await requireHandle();
- const providerName = opened?.providerName;
await current.onSandboxDelete(deleteOptions);
- if (providerName !== undefined) {
- untrackActiveSandboxHandle({ handle: current, providerName, sessionId: input.sessionId });
- }
- opened = undefined;
- opening = undefined;
+ forgetHandle();
persisted = null;
- requiring = undefined;
},
async detach() {
// A failed open left nothing to let go of.
if (requiring !== undefined) await requiring.catch(() => undefined);
- const current = opened;
- if (current === undefined) return undefined;
- untrackActiveSandboxHandle({
- handle: current.handle,
- providerName: current.providerName,
- sessionId: input.sessionId,
- });
- opened = undefined;
- opening = undefined;
- requiring = undefined;
- return current.handle;
+ return forgetHandle()?.handle;
},
async end(reason: SandboxSessionEndReason) {
- if (input.ownsSandbox === false || persisted === null) return;
- const inherited = registered.inheritance;
- const definition = inherited?.definition ?? registered.definition;
- if (definition.kind !== "independent")
- throw new Error(`Sandbox "${definition.logicalPath}" has no environment.`);
- const provider = getSandboxEnvironmentRuntime(definition.environment);
- if (
- persisted.providerName !== provider.providerName ||
- persisted.stateProtocolVersion !== provider.stateProtocolVersion
- ) {
- throw new Error(
- `Sandbox session state is incompatible with provider "${provider.providerName}".`,
- );
- }
- const artifact = await loadSandboxPreparedArtifact({
- compiledArtifactsSource: input.compiledArtifactsSource,
- nodeId: inherited?.nodeId ?? input.nodeId,
- providerName: provider.providerName,
+ if (input.ownsSandbox === false) return;
+ if (requiring !== undefined) await requiring.catch(() => undefined);
+ // A failed step or process loss can create a sandbox without committing
+ // any state. The previous checkpoint cannot prove that the key is unused.
+ const provider = getSandboxEnvironmentRuntime(activeDefinition().environment);
+ // State another provider or protocol recorded is no use here; the key still finds
+ // what this provider keeps.
+ const state =
+ persisted?.providerName === provider.providerName &&
+ persisted.stateProtocolVersion === provider.stateProtocolVersion
+ ? persisted.state
+ : null;
+ await provider.implementation.onSessionEnd(providerContext("sandbox-cleanup"), state, {
+ reason,
});
- if (artifact === undefined) {
- throw new SandboxTemplateNotProvisionedError({
- providerName: provider.providerName,
- templateKey: inherited?.nodeId ?? input.nodeId,
- });
- }
- const activeSession =
- contextStorage.getStore() === undefined
- ? {
- auth: { current: null, initiator: null },
- id: input.sessionId,
- turn: { id: "sandbox-cleanup", sequence: 0 },
- }
- : buildCallbackContext().session;
- const context: SandboxProviderSessionContext = {
- host: createSandboxProviderHost(appRoot),
- session: { ...activeSession, id: input.sessionId },
- storagePath: resolveSandboxCacheDirectory(appRoot),
- };
- const current = opened;
- if (provider.implementation.onSessionEnd !== undefined) {
- await provider.implementation.onSessionEnd(context, artifact, persisted.state, { reason });
- } else if (current !== undefined) {
- await current.handle.onSandboxDelete();
- } else {
- const resumed = await provider.implementation.resume(context, artifact, persisted.state);
- await resumed.onSandboxDelete();
- }
- if (current !== undefined) {
- untrackActiveSandboxHandle({
- handle: current.handle,
- providerName: current.providerName,
- sessionId: input.sessionId,
- });
- }
- opened = undefined;
- opening = undefined;
+ forgetHandle();
persisted = null;
- requiring = undefined;
},
async get() {
await requireHandle();
diff --git a/packages/eve/src/execution/sandbox/prewarm.test.ts b/packages/eve/src/execution/sandbox/prewarm.test.ts
index fb6613a7e..fca748a1e 100644
--- a/packages/eve/src/execution/sandbox/prewarm.test.ts
+++ b/packages/eve/src/execution/sandbox/prewarm.test.ts
@@ -167,6 +167,7 @@ function createGraph(
const provider = defineSandboxProvider({
name: input.providerName ?? "test",
environment: () => ({
+ async onSessionEnd() {},
async prepare() {
return null;
},
diff --git a/packages/eve/src/execution/session-reset.integration.test.ts b/packages/eve/src/execution/session-reset.integration.test.ts
index be38650a1..377a295c7 100644
--- a/packages/eve/src/execution/session-reset.integration.test.ts
+++ b/packages/eve/src/execution/session-reset.integration.test.ts
@@ -79,6 +79,7 @@ function createSessionSandboxHarness() {
const provider = defineSandboxProvider({
name: "session-reset-test",
environment: () => ({
+ async onSessionEnd() {},
async resume(context) {
return createHandle(context.session.id);
},
diff --git a/packages/eve/src/execution/tool-session/sandbox.ts b/packages/eve/src/execution/tool-session/sandbox.ts
index 5b90ae96c..91ea1bea1 100644
--- a/packages/eve/src/execution/tool-session/sandbox.ts
+++ b/packages/eve/src/execution/tool-session/sandbox.ts
@@ -3,9 +3,10 @@ import { getSandboxEnvironmentRuntime } from "#shared/sandbox-environment.js";
import type { SandboxProviderHandle, SandboxProviderRuntime } from "#shared/sandbox-provider.js";
/*
- * Keyed tool sessions reuse a provider's own `start`, which must find the
- * session's sandbox again from the session id alone. Only eve's bindings that
- * do so opt in, and the marker stays internal so the public provider API is
+ * A keyed tool session has no end, so nothing ever runs its sandbox's
+ * session-end cleanup. Only eve's bindings whose kept sandboxes stay bounded
+ * opt in: Vercel's saved filesystems expire, and just-bash keeps only files on
+ * the local disk. The marker stays internal so the public provider API is
* unchanged.
*/
@@ -22,7 +23,7 @@ export interface ToolSessionSandboxSupport {
const supported = new WeakMap<object, ToolSessionSandboxSupport>();
-/** Marks a binding whose `start` reopens a session's sandbox by session id. */
+/** Marks a binding that can keep a tool-session sandbox between calls. */
export function withToolSessionSandboxes<Implementation extends object>(
implementation: Implementation,
support: ToolSessionSandboxSupport = {},
diff --git a/packages/eve/src/internal/testing/app-harness.ts b/packages/eve/src/internal/testing/app-harness.ts
index 4fb385af3..95ca68c7f 100644
--- a/packages/eve/src/internal/testing/app-harness.ts
+++ b/packages/eve/src/internal/testing/app-harness.ts
@@ -115,6 +115,8 @@ export interface TestRuntime {
tool: string | Pick<ResolvedToolDefinition, "name">,
input: unknown,
): Promise<unknown>;
+ /** Session ids whose sandbox cleanup ran when the session ended, in order. */
+ readonly sandboxCleanups: readonly string[];
/**
* Clears the compiled-artifact snapshot, bundle cache, and sessions' sandboxes.
* Tests that re-use a runtime across multiple assertions can call this to
@@ -140,10 +142,12 @@ const TEST_SANDBOX_PROVIDER_NAME = "eve-test-memory";
/**
* An in-memory sandbox provider that keeps each session's sandbox, so a step
* that resumes it sees what earlier steps wrote, as with a real provider. A
- * staged attachment, say, is read back on the next model call.
+ * staged attachment, say, is read back on the next model call. `start` is an
+ * upsert on the session id, and session-end cleanup deletes by it.
*/
function createTestSandboxProvider() {
const sessionSandboxes = new Map<string, MockSandbox>();
+ const endedSessionIds: string[] = [];
function createHandle(sessionId: string) {
let sandbox = sessionSandboxes.get(sessionId);
@@ -166,6 +170,12 @@ function createTestSandboxProvider() {
const provider = defineSandboxProvider({
name: TEST_SANDBOX_PROVIDER_NAME,
environment: () => ({
+ async onSessionEnd(context) {
+ endedSessionIds.push(context.session.id);
+ const sandbox = sessionSandboxes.get(context.session.id);
+ sessionSandboxes.delete(context.session.id);
+ await sandbox?.access.delete?.();
+ },
async prepare() {
return null;
},
@@ -177,7 +187,14 @@ function createTestSandboxProvider() {
},
}),
});
- return { clear: () => sessionSandboxes.clear(), provider };
+ return {
+ clear: () => {
+ sessionSandboxes.clear();
+ endedSessionIds.length = 0;
+ },
+ endedSessionIds,
+ provider,
+ };
}
export async function createTestRuntime(descriptor: TestAppDescriptor = {}): Promise<TestRuntime> {
@@ -284,6 +301,7 @@ export async function createTestRuntime(descriptor: TestAppDescriptor = {}): Pro
reset,
run,
runAsSession,
+ sandboxCleanups: sandboxes.endedSessionIds,
session,
tools,
};
diff --git a/packages/eve/src/internal/testing/sandbox-provider-harness.ts b/packages/eve/src/internal/testing/sandbox-provider-harness.ts
index 511b98b02..b7a87c484 100644
--- a/packages/eve/src/internal/testing/sandbox-provider-harness.ts
+++ b/packages/eve/src/internal/testing/sandbox-provider-harness.ts
@@ -33,7 +33,30 @@ export function createSandboxProviderHarness<
);
}
+ function sessionContext(appRoot: string, sandboxName: string) {
+ return {
+ host: createSandboxProviderHost(appRoot),
+ session: {
+ auth: { current: null, initiator: null },
+ id: sandboxName,
+ turn: { id: "test-turn", sequence: 0 },
+ },
+ storagePath: appRoot,
+ } as const;
+ }
+
const harness = {
+ async endSession(input: {
+ readonly appRoot: string;
+ readonly sandboxName: string;
+ readonly state: SessionState | null;
+ }): Promise<void> {
+ await implementation.onSessionEnd(
+ sessionContext(input.appRoot, input.sandboxName),
+ input.state,
+ { reason: "completed" },
+ );
+ },
async prepare(input: {
readonly appRoot: string;
readonly log?: (message: string) => void;
@@ -70,15 +93,7 @@ export function createSandboxProviderHarness<
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;
+ const context = sessionContext(input.appRoot, input.sandboxName);
if (input.existing === undefined) {
return (await implementation.start(context, options, artifact)).handle;
}
@@ -86,21 +101,14 @@ export function createSandboxProviderHarness<
},
async start(input: {
readonly appRoot: string;
+ readonly options?: Options;
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,
+ sessionContext(input.appRoot, input.sandboxName),
+ input.options ?? options,
artifact,
);
},
diff --git a/packages/eve/src/sandbox/providers/docker.ts b/packages/eve/src/sandbox/providers/docker.ts
index bad50add4..bc603c4e3 100644
--- a/packages/eve/src/sandbox/providers/docker.ts
+++ b/packages/eve/src/sandbox/providers/docker.ts
@@ -18,7 +18,7 @@ const provider = defineSandboxProvider<
DockerSandboxEnvironmentOptions,
DockerSandboxRuntimeOptions,
{ readonly imageReference: string },
- { readonly containerName: string; readonly generation: string; readonly version: 2 },
+ { readonly containerName: string; readonly version: 2 },
DockerSandboxSession
>({
name: "docker",
diff --git a/packages/eve/src/sandbox/providers/just-bash.ts b/packages/eve/src/sandbox/providers/just-bash.ts
index 635aaf098..cd82deece 100644
--- a/packages/eve/src/sandbox/providers/just-bash.ts
+++ b/packages/eve/src/sandbox/providers/just-bash.ts
@@ -9,7 +9,7 @@ export const JustBashSandbox = defineSandboxProvider<
JustBashEnvironmentOptions,
undefined,
{ readonly templateKey: string },
- { readonly generation: string; readonly rootPath: string; readonly version: 2 },
+ { readonly rootPath: string; readonly version: 2 },
SandboxSession
>({
name: "just-bash",
diff --git a/packages/eve/src/shared/sandbox-provider.test.ts b/packages/eve/src/shared/sandbox-provider.test.ts
index d01a9f691..3eb347b66 100644
--- a/packages/eve/src/shared/sandbox-provider.test.ts
+++ b/packages/eve/src/shared/sandbox-provider.test.ts
@@ -12,6 +12,7 @@ const provider = defineSandboxProvider<
name: "test-provider",
stateProtocolVersion: 4,
environment: (environmentOptions) => ({
+ async onSessionEnd() {},
async prepare() {
return { templateId: environmentOptions?.image ?? "default" };
},
diff --git a/packages/eve/src/shared/sandbox-provider.ts b/packages/eve/src/shared/sandbox-provider.ts
index f5d6b3407..768090226 100644
--- a/packages/eve/src/shared/sandbox-provider.ts
+++ b/packages/eve/src/shared/sandbox-provider.ts
@@ -135,13 +135,15 @@ export interface SandboxProviderImplementation<
Session extends SandboxSession = SandboxSession,
> {
/**
- * Permanently releases resources owned by a durable session after its terminal outcome.
- * Implementations must be idempotent because the cleanup step may retry.
+ * Permanently deletes the sandbox for `context.session.id` after the session's terminal
+ * outcome. `state` is what `start()` returned when the session recorded it, or `null` when
+ * the session never did, for example because a subagent that shares the sandbox opened it.
+ * Find the sandbox from the key when `state` is `null`. Must succeed when no sandbox exists
+ * and be idempotent, because the cleanup step may retry.
*/
- onSessionEnd?(
+ onSessionEnd(
context: SandboxProviderSessionContext,
- artifact: Readonly<PreparedArtifact>,
- state: Readonly<SessionState>,
+ state: Readonly<SessionState> | null,
options: { readonly reason: "completed" | "expired" | "failed" },
): Promise<void>;
prepare(context: SandboxProviderPrepareContext): Promise<PreparedArtifact>;
@@ -150,6 +152,13 @@ export interface SandboxProviderImplementation<
artifact: Readonly<PreparedArtifact>,
state: Readonly<SessionState>,
): Promise<SandboxProviderHandle<Session>>;
+ /**
+ * Returns the live sandbox for `context.session.id`, creating it when none exists. This
+ * must be an idempotent upsert on that key: repeated and concurrent calls, from any process
+ * or deployment, return the same sandbox while it exists. Derive the sandbox's identity
+ * from the key and a provider-level namespace only, never from `options` or `artifact`,
+ * which apply only when this call creates the sandbox.
+ */
start(
context: SandboxProviderSessionContext,
options: Readonly<OpenOptions> | undefined,
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 67e8cc3b4..c9ca1c6d6 100644
--- a/packages/eve/test/scenarios/public-api-portability.scenario.test.ts
+++ b/packages/eve/test/scenarios/public-api-portability.scenario.test.ts
@@ -76,6 +76,7 @@ const custom = defineSandboxProvider({
name: "custom",
environment() {
return {
+ async onSessionEnd() {},
async prepare() { return null; },
async resume() { throw new Error("unused"); },
async start() { throw new Error("unused"); },