The Open Framework for Building Agents
feat(eve): delete session sandboxes (#2398)
vercel-gh-bot-5[bot]52e89efc1267
diff --git a/.changeset/delete-sandbox.md b/.changeset/delete-sandbox.mdnew file mode 100644index 000000000..7369cef86--- /dev/null+++ b/.changeset/delete-sandbox.md@@ -0,0 +1,5 @@+---+"eve": minor+---++Add `delete()` to the runtime sandbox handle for permanently deleting the current session sandbox and reprovisioning it on the next access. Docker handles stay bound to one physical container, and sandbox `onSession` callbacks now receive session metadata through `ctx` while using `use()` for sandbox access.diff --git a/docs/guides/session-context.md b/docs/guides/session-context.mdindex d39fc94e9..0c9ebc5b8 100644--- a/docs/guides/session-context.md+++ b/docs/guides/session-context.md@@ -59,7 +59,7 @@ const sandbox = await ctx.getSandbox();const result = await sandbox.run({ command: "npm test" });```-The accessor is asynchronous because eve may need to bind or restore the sandbox. A subagent sees its own sandbox, not its parent's. The returned runtime handle can also stop compute while preserving the durable sandbox state. See [Sandbox](../sandbox#using-the-sandbox) for the I/O API and lifecycle.+The accessor is asynchronous because eve may need to bind or restore the sandbox. A subagent sees its own sandbox, not its parent's. The returned handle also exposes `stop()` and `delete()`; see [Sandbox lifecycle](../sandbox#lifecycle) for their behavior.## `ctx.getSkill(identifier)`@@ -82,7 +82,7 @@ Runtime context is available:- inside `defineTool(...).execute(input, ctx)`;- inside connection `auth` and `headers` resolvers;-- inside channel and hook callbacks that receive `ctx`;+- inside channel and agent hook callbacks that receive the full runtime `ctx`;- after asynchronous boundaries within the same authored execution chain.Runtime context is not available during top-level module evaluation, build scripts, or discovery. Declare reusable definitions and state handles at module scope, but call their context-dependent methods only from an eve-managed callback.diff --git a/docs/sandbox.mdx b/docs/sandbox.mdxindex bd07944c5..7e344e3fd 100644--- a/docs/sandbox.mdx+++ b/docs/sandbox.mdx@@ -202,14 +202,14 @@ export default defineSandbox({Custom commands are registered on live and reopened sessions, not during template prewarming. They run trusted host application code and create an explicit bridge from the sandbox to that code. Adapters can use this extension point to expose application APIs such as a Capable App's CLI; the outer eve `bash` tool does not automatically provide per-command Capable approvals.-You can also write your own backend. A `SandboxBackend` is an adapter object with a `name`, a `create`, and an optional `prewarm`. It can point at your own container runner, VM pool, internal sandbox service, or another isolation layer, as long as it returns the `SandboxSession` operations eve needs. Handles returned by `create` implement `shutdown()`, which stops the underlying compute at server shutdown. See the `SandboxBackend*` types on `eve/sandbox`.+You can also write your own backend. A `SandboxBackend` is an adapter object with a `name`, a `create`, and an optional `prewarm`. It can point at your own container runner, VM pool, internal sandbox service, or another isolation layer, as long as it returns the `SandboxSession` operations eve needs. Handles returned by `create` implement `delete()`, `stop()`, and `shutdown()`. See the `SandboxBackend*` types on `eve/sandbox`.## LifecycleThere are two hooks, scoped differently:- **`bootstrap({ use })`** is template-scoped and runs once when the template is built. Put reusable setup here that every later session inherits, such as cloning a baseline repo, installing dependencies, or seeding files. Call `use()` to get a `SandboxSession`. Only template filesystem state and supported backend metadata carry into later sessions; config like network policy does not. If external inputs affect what bootstrap produces, set `revalidationKey: () => string` so eve knows when to rebuild the template (authored sandbox source and seed contents are already tracked for you).-- **`onSession({ use, ctx })`** is durable-session-scoped and runs once per session (and again if a sandbox definition change replaces the session's sandbox). Put per-session setup here, including network policy, resources, timeout, per-user credentials, and one-time markers. Because it runs inside the active runtime context, it can read `ctx.session` and derive the current principal without baking credentials into the template. Call `use(opts?)` to get a `SandboxSession`; `opts` flow to the backend's update path after create.+- **`onSession({ use, ctx })`** is durable-session-scoped and runs once per session (and again if a sandbox definition change replaces the session's sandbox). Put per-session setup here, including network policy, resources, timeout, per-user credentials, and one-time markers. `ctx` contains only the active session metadata, so it can identify the current principal without exposing runtime lifecycle operations while the sandbox is initializing. Call `use(opts?)` to get a `SandboxSession`; `opts` flow to the backend's update path after create.If you require a network policy or other configuration for every session, configure it on the backend factory or in `onSession`; do not rely on bootstrap-only configuration.@@ -248,6 +248,29 @@ stop-specific state is needed. Lifecycle `use()` calls return the I/O-only`SandboxSession` because bootstrap and session initialization do not own runtimeteardown.+### Delete a sandbox++Permanently delete the current session sandbox from an authored runtime callback:++```ts+const sandbox = await ctx.getSandbox();+await sandbox.delete();+```++eve stops compute first, deletes the physical sandbox and its disposable backend state, and clears the saved reconnect state. It preserves reusable template state that contains `bootstrap` and seeded workspace files.++The durable eve session remains active. The next call to `ctx.getSandbox()` provisions a fresh workspace from the current sandbox definition and runs `onSession` again. Files and other workspace changes from the deleted sandbox are not restored.++Backend behavior differs:++- **Vercel Sandbox**: stops the persistent sandbox, deletes its record, and asks Vercel to delete snapshots that no other sandbox uses. Snapshot cleanup runs asynchronously.+- **microsandbox**: stops and removes the session VM and its persisted state snapshot+- **Docker and just-bash**: stop compute and discard their session runtime state++Only the session that owns a shared sandbox can delete it. Deleting the owner's sandbox affects every parent or child currently using it. If the backend rejects deletion, eve preserves the current reconnect state so you can retry.++Custom backend handles implement the same boundary in `delete()`: remove the session runtime and disposable persisted state without deleting reusable templates.+Session sandboxes are keyed per durable session, not per deployment, so redeploying your app does not by itself discard them. A definition change to the authored sandbox source, workspace seed content, or `revalidationKey` replaces the sandbox on the next turn and runs `onSession` again.Reattachment still depends on the backend retaining its physical sandbox state. If a persisted Vercel sandbox is no longer available, eve creates a replacement, using the current template when one is configured. Files and other changes made after the original sandbox was created are not restored automatically. Because the durable session still has the same sandbox key, `onSession` does not run again for this replacement. Persist important artifacts outside the sandbox, and do not rely on `onSession` as the only place that applies security-critical configuration.diff --git a/packages/eve/extension-contracts/compatibility/channel/v10.ts b/packages/eve/extension-contracts/compatibility/channel/v10.tsnew file mode 100644index 000000000..67e58f0bb--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/channel/v10.ts@@ -0,0 +1,3 @@+import { disableRoute } from "#public/channels/index.js";++export default disableRoute();diff --git a/packages/eve/extension-contracts/compatibility/connection/v7.ts b/packages/eve/extension-contracts/compatibility/connection/v7.tsnew file mode 100644index 000000000..d0b61542e--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/connection/v7.ts@@ -0,0 +1,11 @@+import { defineMcpClientConnection } from "#public/connections/index.js";++export default defineMcpClientConnection({+ description: "Call-aware MCP service",+ toolCall: {+ providedArguments: {+ requestId: ({ callId, session, toolName }) => `${session.id}:${toolName}:${callId}`,+ },+ },+ url: "https://example.com/mcp",+});diff --git a/packages/eve/extension-contracts/compatibility/dynamicTool/v20.ts b/packages/eve/extension-contracts/compatibility/dynamicTool/v20.tsnew file mode 100644index 000000000..6252c112c--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/dynamicTool/v20.ts@@ -0,0 +1,19 @@+import { z } from "zod";++import { defineDynamic, defineTool } from "#public/tools/index.js";++export default defineDynamic({+ events: {+ "turn.started": (_event, ctx) =>+ defineTool({+ description: "Echo the tool call identifiers.",+ inputSchema: z.object({ note: z.string() }),+ execute: ({ note }, toolCtx) => ({+ callId: toolCtx.callId,+ note,+ sessionId: ctx.session.id,+ toolName: toolCtx.toolName,+ }),+ }),+ },+});diff --git a/packages/eve/extension-contracts/compatibility/hook/v15.ts b/packages/eve/extension-contracts/compatibility/hook/v15.tsnew file mode 100644index 000000000..38ecc7e06--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/hook/v15.ts@@ -0,0 +1,13 @@+import { defineHook } from "#public/hooks/index.js";++export default defineHook({+ events: {+ "subagent.completed"(event, ctx) {+ console.info("subagent completed", {+ output: event.data.output,+ sessionId: ctx.session.id,+ subagentName: event.data.subagentName,+ });+ },+ },+});diff --git a/packages/eve/extension-contracts/compatibility/state/v3.ts b/packages/eve/extension-contracts/compatibility/state/v3.tsnew file mode 100644index 000000000..ce8917780--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/state/v3.ts@@ -0,0 +1,10 @@+import { defineState } from "#public/context/index.js";++export const budget = defineState("compatibility.budget", () => ({+ count: 0,+ limit: 10,+}));++export function recordUsage(): void {+ budget.update((current) => ({ ...current, count: current.count + 1 }));+}diff --git a/packages/eve/extension-contracts/compatibility/tool/v20.ts b/packages/eve/extension-contracts/compatibility/tool/v20.tsnew file mode 100644index 000000000..128129619--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/tool/v20.ts@@ -0,0 +1,3 @@+import { defaultWebSearch } from "#public/tools/web-search.js";++export default defaultWebSearch;diff --git a/packages/eve/extension-contracts/reports/channel/v11.json b/packages/eve/extension-contracts/reports/channel/v11.jsonnew file mode 100644index 000000000..2c3cefe6f--- /dev/null+++ b/packages/eve/extension-contracts/reports/channel/v11.json@@ -0,0 +1,21 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "channel",+ "epoch": 11,+ "sha256": "79977ede71f56ba73960caab072192a2e24de6f0117142ad28c74ae81609817f",+ "exports": [+ "DELETE",+ "GET",+ "HEAD",+ "OPTIONS",+ "PATCH",+ "POST",+ "PUT",+ "WS",+ "createWebSocketUpgradeServer",+ "defineChannel",+ "disableRoute",+ "isChannel",+ "isDisabledRouteSentinel"+ ]+}diff --git a/packages/eve/extension-contracts/reports/connection/v8.json b/packages/eve/extension-contracts/reports/connection/v8.jsonnew file mode 100644index 000000000..3f344ff5a--- /dev/null+++ b/packages/eve/extension-contracts/reports/connection/v8.json@@ -0,0 +1,15 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "connection",+ "epoch": 8,+ "sha256": "61fcb494fce64590fb7dd9bcc548e4579f20d29c642a6b681ef051caa7a25eec",+ "exports": [+ "ConnectionAuthorizationFailedError",+ "ConnectionAuthorizationRequiredError",+ "defineInteractiveAuthorization",+ "defineMcpClientConnection",+ "defineOpenAPIConnection",+ "isConnectionAuthorizationFailedError",+ "isConnectionAuthorizationRequiredError"+ ]+}diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v21.json b/packages/eve/extension-contracts/reports/dynamicTool/v21.jsonnew file mode 100644index 000000000..523ca74fd--- /dev/null+++ b/packages/eve/extension-contracts/reports/dynamicTool/v21.json@@ -0,0 +1,13 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "dynamicTool",+ "epoch": 21,+ "sha256": "4abc39846c139d3f218087de1305665d6fbd06af8809bdc0a6930dc206fabfd7",+ "exports": [+ "DynamicToolEntry",+ "DynamicToolEvents",+ "DynamicToolResult",+ "DynamicToolSet",+ "defineDynamic"+ ]+}diff --git a/packages/eve/extension-contracts/reports/hook/v16.json b/packages/eve/extension-contracts/reports/hook/v16.jsonnew file mode 100644index 000000000..1e9820c79--- /dev/null+++ b/packages/eve/extension-contracts/reports/hook/v16.json@@ -0,0 +1,7 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "hook",+ "epoch": 16,+ "sha256": "9c0b9aa82a2eb9c6b047a0ac6930195cd6d913cda39f54286fe4fdb3d8528259",+ "exports": ["defineHook"]+}diff --git a/packages/eve/extension-contracts/reports/state/v4.json b/packages/eve/extension-contracts/reports/state/v4.jsonnew file mode 100644index 000000000..8c1fdbb2f--- /dev/null+++ b/packages/eve/extension-contracts/reports/state/v4.json@@ -0,0 +1,15 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "state",+ "epoch": 4,+ "sha256": "a2324746f385525a568281f9aa907faf9b752f3a3f1378101f33226fb894d115",+ "exports": [+ "Session",+ "SessionAuth",+ "SessionAuthContext",+ "SessionContext",+ "SessionParent",+ "SessionTurn",+ "defineState"+ ]+}diff --git a/packages/eve/extension-contracts/reports/tool/v21.json b/packages/eve/extension-contracts/reports/tool/v21.jsonnew file mode 100644index 000000000..7ffd7e466--- /dev/null+++ b/packages/eve/extension-contracts/reports/tool/v21.json@@ -0,0 +1,19 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "tool",+ "epoch": 21,+ "sha256": "f61977f4b5b3bec122f07d2413dd101ba91aaf1fb803a349b36f04cfeff5427f",+ "exports": [+ "defaultWebSearch",+ "defineTool",+ "disableTool",+ "experimental_workflow",+ "isDisabledToolSentinel",+ "isExperimentalWorkflowToolDefinition",+ "isWebSearchToolDefinition",+ "toolOutput",+ "toolOutputPart",+ "toolResultFrom",+ "webSearch"+ ]+}diff --git a/packages/eve/package.json b/packages/eve/package.jsonindex bdbaae16c..a719173ca 100644--- a/packages/eve/package.json+++ b/packages/eve/package.json@@ -429,6 +429,7 @@"@vercel/oidc": "3.8.0","@vercel/otel": "catalog:","@vercel/sandbox": "catalog:",+ "@vercel/sandbox-delete": "catalog:","@vercel/sandbox-drives": "catalog:","@vercel/sdk": "1.28.8","@workflow/core": "5.0.0-beta.43",diff --git a/packages/eve/scripts/vendor-compiled/@vercel/sandbox-delete.mjs b/packages/eve/scripts/vendor-compiled/@vercel/sandbox-delete.mjsnew file mode 100644index 000000000..eb7e9a13d--- /dev/null+++ b/packages/eve/scripts/vendor-compiled/@vercel/sandbox-delete.mjs@@ -0,0 +1,8 @@+import vercelSandbox from "./sandbox.mjs";++/** Vendor the stable SDK version that owns orphan-snapshot deletion. */+export default {+ ...vercelSandbox,+ packageName: "@vercel/sandbox-delete",+ compiledPath: "@vercel/sandbox-delete",+};diff --git a/packages/eve/scripts/vendor-compiled/index.mjs b/packages/eve/scripts/vendor-compiled/index.mjsindex e8eb26050..0c1e16cc8 100644--- a/packages/eve/scripts/vendor-compiled/index.mjs+++ b/packages/eve/scripts/vendor-compiled/index.mjs@@ -27,6 +27,7 @@ import vercelDetectAgent from "./@vercel/detect-agent.mjs";import vercelOidc from "./@vercel/oidc.mjs";import vercelOtel from "./@vercel/otel.mjs";import vercelSandbox from "./@vercel/sandbox.mjs";+import vercelSandboxDelete from "./@vercel/sandbox-delete.mjs";import vercelSandboxStable from "./@vercel/sandbox-stable.mjs";import workflowCore from "./@workflow/core.mjs";import workflowErrors from "./@workflow/errors.mjs";@@ -91,6 +92,7 @@ export const MODULES = [vercelOidc,vercelOtel,vercelSandbox,+ vercelSandboxDelete,vercelSandboxStable,workflowCore,workflowErrors,diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex 46d17265c..baf1c4c69 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -22,16 +22,16 @@ interface ExtensionCapabilityContract {const EXTENSION_CAPABILITY_CONTRACTS = {extension: { current: 1, supported: [1], dropped: {} },tool: {- current: 20,- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20],+ current: 21,+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21],dropped: { 15: "TaskExec replaces stageEffect with send" },},dynamicTool: {- current: 20,- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],+ current: 21,+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],dropped: {},},- channel: { current: 10, supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dropped: {} },+ channel: { current: 11, supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], dropped: {} },schedule: { current: 4, supported: [1, 2, 3, 4], dropped: {} },subagent: {current: 5,@@ -42,13 +42,13 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},},connection: {- current: 7,- supported: [1, 2, 3, 4, 5, 6, 7],+ current: 8,+ supported: [1, 2, 3, 4, 5, 6, 7, 8],dropped: {},},hook: {- current: 15,- supported: [10, 11, 12, 13, 14, 15],+ current: 16,+ supported: [10, 11, 12, 13, 14, 15, 16],dropped: {1: "Model identity moved from session.started runtime metadata to step.started call attribution.",2: "Model identity moved from session.started runtime metadata to step.started call attribution.",@@ -74,7 +74,7 @@ const EXTENSION_CAPABILITY_CONTRACTS = {dropped: {},},config: { current: 1, supported: [1], dropped: {} },- state: { current: 3, supported: [1, 2, 3], dropped: {} },+ state: { current: 4, supported: [1, 2, 3, 4], dropped: {} },} as const satisfies Record<string, ExtensionCapabilityContract>;/** One independently versioned extension-facing contract. */diff --git a/packages/eve/src/context/accessors.integration.test.ts b/packages/eve/src/context/accessors.integration.test.tsindex 4c2cf9233..1e260849f 100644--- a/packages/eve/src/context/accessors.integration.test.ts+++ b/packages/eve/src/context/accessors.integration.test.ts@@ -139,6 +139,23 @@ describe("buildCallbackContext – getSandbox", () => {expect(stops).toBe(1);});++ it("deletes the active sandbox through the runtime session", async () => {+ let deletions = 0;+ const sandbox = mockSandbox({+ delete: () => {+ deletions += 1;+ },+ });+ const runtime = await createTestRuntime();++ await runtime.runAsSession({ sandbox }, async () => {+ const live: RuntimeSandboxSession = await buildCallbackContext().getSandbox();+ await live.delete();+ });++ expect(deletions).toBe(1);+ });});describe("buildCallbackContext – getSkill", () => {diff --git a/packages/eve/src/context/build-callback-context.ts b/packages/eve/src/context/build-callback-context.tsindex abe7bb2ab..99abe4e66 100644--- a/packages/eve/src/context/build-callback-context.ts+++ b/packages/eve/src/context/build-callback-context.ts@@ -35,7 +35,16 @@ export function buildCallbackContext(): SessionContext {if (sandbox === null) {throw new Error("The sandbox is not available in the current authored runtime context.");}- return withRuntimeSandboxStop(sandbox, async () => await access.stop());+ return withRuntimeSandboxLifecycle(+ sandbox,+ async (options) => {+ if (access.delete === undefined) {+ throw new Error("The active sandbox runtime does not support deletion.");+ }+ await access.delete(options);+ },+ async () => await access.stop(),+ );});},@@ -52,11 +61,13 @@ export function buildCallbackContext(): SessionContext {};}-function withRuntimeSandboxStop(+function withRuntimeSandboxLifecycle(sandbox: SandboxSession,+ deleteSandbox: RuntimeSandboxSession["delete"],stop: () => Promise<void>,): RuntimeSandboxSession {return {+ delete: deleteSandbox,id: sandbox.id,readBinaryFile: (options) => sandbox.readBinaryFile(options),readFile: (options) => sandbox.readFile(options),diff --git a/packages/eve/src/context/hook-lifecycle.integration.test.ts b/packages/eve/src/context/hook-lifecycle.integration.test.tsindex b02a0a595..cea998520 100644--- a/packages/eve/src/context/hook-lifecycle.integration.test.ts+++ b/packages/eve/src/context/hook-lifecycle.integration.test.ts@@ -4,6 +4,7 @@ import { createRuntimeHookRegistry } from "#runtime/hooks/registry.js";import type { ResolvedHookDefinition } from "#runtime/types.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";import { stampTestEvent } from "#internal/testing/events.js";+import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";import { ContextContainer, contextStorage } from "./container.js";import { dispatchStreamEventHooks } from "./hook-lifecycle.js";import {@@ -11,7 +12,7 @@ import {ChannelKey,type CompiledBundle,} from "#runtime/sessions/runtime-context-keys.js";-import { ContinuationTokenKey, SessionIdKey, SessionKey } from "./keys.js";+import { ContinuationTokenKey, SandboxKey, SessionIdKey, SessionKey } from "./keys.js";function createMockBundle(): CompiledBundle {return {@@ -109,4 +110,35 @@ describe("dispatchStreamEventHooks", () => {),).rejects.toThrow(/event hook boom/);});++ it("can delete the runtime sandbox from a session.completed hook", async () => {+ let deletions = 0;+ const sandbox = mockSandbox({+ delete: () => {+ deletions += 1;+ },+ });+ const registry = createRuntimeHookRegistry([+ hook("cleanup", {+ events: {+ "session.completed": async (_event, hookContext) => {+ const live = await hookContext.getSandbox();+ await live.delete();+ },+ },+ }),+ ]);+ const ctx = buildCtx();+ ctx.set(SandboxKey, sandbox.access);++ await contextStorage.run(ctx, () =>+ dispatchStreamEventHooks({+ ctx,+ registry,+ event: stampTestEvent({ type: "session.completed" }),+ }),+ );++ expect(deletions).toBe(1);+ });});diff --git a/packages/eve/src/context/providers/sandbox.test.ts b/packages/eve/src/context/providers/sandbox.test.tsindex e1a77bcd0..e5449e90e 100644--- a/packages/eve/src/context/providers/sandbox.test.ts+++ b/packages/eve/src/context/providers/sandbox.test.ts@@ -80,6 +80,7 @@ describe("sandboxProvider", () => {expect(ensureSandboxAccess).toHaveBeenCalledWith(expect.objectContaining({+ ownsSandbox: false,sessionId: "root-sandbox-session",state: parentSandboxState,}),@@ -98,6 +99,7 @@ describe("sandboxProvider", () => {expect(ensureSandboxAccess).toHaveBeenCalledWith(expect.objectContaining({+ ownsSandbox: true,tags: {agent: "weather-agent",channel: "slack",diff --git a/packages/eve/src/context/providers/sandbox.ts b/packages/eve/src/context/providers/sandbox.tsindex 22ab89366..c1f7ad81b 100644--- a/packages/eve/src/context/providers/sandbox.ts+++ b/packages/eve/src/context/providers/sandbox.ts@@ -34,6 +34,7 @@ export const sandboxProvider: FrameworkContextProvider<SandboxAccess> = {value: await ensureSandboxAccess({compiledArtifactsSource: bundle.compiledArtifactsSource,nodeId: node.nodeId,+ ownsSandbox: !sharesSandbox,registry,runOnSession: async (callback) => await contextStorage.run(ctx, callback),sessionId: sandboxSessionId,diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.tsindex 8e24a3cba..bb52b4756 100644--- a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts@@ -1320,6 +1320,7 @@ function createSandboxBackend() {metadata: {},sessionKey: input.sessionKey,}),+ delete: async () => {},session: sandbox.session,shutdown: async () => {},stop: async () => {},diff --git a/packages/eve/src/execution/sandbox/bindings/docker-session.ts b/packages/eve/src/execution/sandbox/bindings/docker-session.tsindex 8c56292d6..5f2769a5a 100644--- a/packages/eve/src/execution/sandbox/bindings/docker-session.ts+++ b/packages/eve/src/execution/sandbox/bindings/docker-session.ts@@ -50,10 +50,10 @@ const DOCKER_KILL_TREE_SCRIPT = [export function createDockerInternalSession(input: {readonly cli: DockerCli;- readonly containerName: string;+ readonly containerIdentity: string;readonly id: string;}): InternalSandboxSession {- const { cli, containerName } = input;+ const { cli, containerIdentity } = input;async function killSpawnTree(pidFilePath: string): Promise<void> {// Best-effort: the container may already be stopped or the process@@ -61,7 +61,7 @@ export function createDockerInternalSession(input: {await cli.run(["exec",- containerName,+ containerIdentity,"bash","-c",DOCKER_KILL_TREE_SCRIPT,@@ -91,7 +91,7 @@ export function createDockerInternalSession(input: {`echo "$$" > ${shellQuote(pidFilePath)}; ` +`bash -lc ${shellQuote(options.command)}; ` +`status=$?; rm -f ${shellQuote(pidFilePath)}; exit $status`;- args.push(containerName, "bash", "-c", wrapped);+ args.push(containerIdentity, "bash", "-c", wrapped);const child = cli.stream(args, { signal: options.abortSignal });options.abortSignal?.addEventListener("abort", () => void killSpawnTree(pidFilePath), {@@ -115,7 +115,7 @@ export function createDockerInternalSession(input: {const result = await cli.run(["exec",- containerName,+ containerIdentity,"bash","-lc",// A sentinel exit code distinguishes "missing" from real read@@ -134,7 +134,7 @@ export function createDockerInternalSession(input: {const flags = `${options.recursive === true ? "r" : ""}${options.force === true ? "f" : ""}`;const args = ["exec",- containerName,+ containerIdentity,"rm",...(flags.length > 0 ? [`-${flags}`] : []),"--",@@ -149,7 +149,7 @@ export function createDockerInternalSession(input: {["exec","-i",- containerName,+ containerIdentity,"bash","-lc",`mkdir -p ${shellQuote(posixDirname(options.path))} && cat > ${shellQuote(options.path)}`,diff --git a/packages/eve/src/execution/sandbox/bindings/docker.integration.test.ts b/packages/eve/src/execution/sandbox/bindings/docker.integration.test.tsindex 1f5486ae8..c37f13c80 100644--- a/packages/eve/src/execution/sandbox/bindings/docker.integration.test.ts+++ b/packages/eve/src/execution/sandbox/bindings/docker.integration.test.ts@@ -41,17 +41,30 @@ function createFakeDockerCli(respond: (args: readonly string[]) => FakeResponse | undefined = () => undefined,): { calls: FakeDockerCall[]; cli: DockerCli; killedStreams: (readonly string[])[] } {const calls: FakeDockerCall[] = [];+ const createdContainerNames = new Set<string>();const killedStreams: (readonly string[])[] = [];function resolve(args: readonly string[]): DockerCommandResult {- const partial = respond(args) ?? {};+ let partial = respond(args) ?? {};+ if (args[0] === "container" && args[1] === "inspect" && args[3] === "{{.Id}}") {+ const containerName = args.at(-1) ?? "unknown";+ if (createdContainerNames.has(containerName) || (partial.exitCode ?? 0) === 0) {+ partial = { ...partial, exitCode: 0, stdout: fakeDockerContainerIdentity(containerName) };+ }+ }const stdout = partial.stdout ?? "";- return {+ const result = {exitCode: partial.exitCode ?? 0,stderr: partial.stderr ?? "",stdout,stdoutBytes: partial.stdoutBytes ?? Buffer.from(stdout, "utf8"),};+ if (args[0] === "run" && result.exitCode === 0) {+ const nameIndex = args.indexOf("--name");+ const containerName = nameIndex === -1 ? undefined : args[nameIndex + 1];+ if (containerName !== undefined) createdContainerNames.add(containerName);+ }+ return result;}return {@@ -108,6 +121,10 @@ function isContainerInspect(args: readonly string[]): boolean {return args[0] === "container" && args[1] === "inspect";}+function fakeDockerContainerIdentity(containerName: string): string {+ return `sha256:${containerName}`;+}+const TEMPLATE_KEY = "eve-sbx-tpl-local-abc123";const DEFAULT_DOCKER_OPTIONS_HASH = createDockerSandboxOptionsHash(resolveDockerSandboxOptions());const TEMPLATE_IMAGE = dockerTemplateImageReference({@@ -211,10 +228,15 @@ describe("createDockerSandboxBackend prewarm", () => {expect(seedWrite?.stdin?.toString("utf8")).toBe("# Weather skill\n");const stop = findCall(calls, (args) => args[0] === "stop");- expect(stop?.args).toEqual(["stop", "-t", "0", buildContainerName]);+ expect(stop?.args).toEqual([+ "stop",+ "-t",+ "0",+ fakeDockerContainerIdentity(buildContainerName!),+ ]);const commit = findCall(calls, (args) => args[0] === "commit");- expect(commit?.args.at(-2)).toBe(buildContainerName);+ expect(commit?.args.at(-2)).toBe(fakeDockerContainerIdentity(buildContainerName!));expect(commit?.args.at(-1)).toBe(TEMPLATE_IMAGE);const cleanup = findCall(calls, (args) => args[0] === "rm" && args[1] === "-f");@@ -386,7 +408,7 @@ describe("createDockerSandboxBackend create", () => {"stop","-t","0",- SESSION_KEY,+ fakeDockerContainerIdentity(SESSION_KEY),]);} finally {if (previousRunId === undefined) {@@ -504,7 +526,7 @@ describe("docker session primitives", () => {"/workspace","-e","DEPLOY_ENV=staging",- SESSION_KEY,+ fakeDockerContainerIdentity(SESSION_KEY),"bash","-c",]);@@ -529,7 +551,7 @@ describe("docker session primitives", () => {await spawned.kill();const treeKill = findCall(calls, (args) => args.includes("eve-kill-tree"));- expect(treeKill?.args.slice(0, 2)).toEqual(["exec", SESSION_KEY]);+ expect(treeKill?.args.slice(0, 2)).toEqual(["exec", fakeDockerContainerIdentity(SESSION_KEY)]);expect(treeKill?.args.at(-1)).toBe(pidFilePath);expect(String(treeKill?.args.at(-3))).toContain("kill_tree");// The local docker exec client is killed after the in-container@@ -593,7 +615,7 @@ describe("docker session primitives", () => {const remove = findCall(calls, (args) => args[0] === "exec" && args.includes("rm"));expect(remove?.args).toEqual(["exec",- SESSION_KEY,+ fakeDockerContainerIdentity(SESSION_KEY),"rm","-rf","--",@@ -615,7 +637,13 @@ describe("docker session primitives", () => {expect(findCall(calls, (args) => args[0] === "network" && args[1] === "disconnect")?.args,- ).toEqual(["network", "disconnect", "--force", "bridge", SESSION_KEY]);+ ).toEqual([+ "network",+ "disconnect",+ "--force",+ "bridge",+ fakeDockerContainerIdentity(SESSION_KEY),+ ]);});it("applies allow-all to a deny-all-created container by detaching none before bridge", async () => {@@ -636,8 +664,8 @@ describe("docker session primitives", () => {.filter((call) => call.args[0] === "network").map((call) => call.args);expect(networkCalls).toEqual([- ["network", "disconnect", "--force", "none", SESSION_KEY],- ["network", "connect", "bridge", SESSION_KEY],+ ["network", "disconnect", "--force", "none", fakeDockerContainerIdentity(SESSION_KEY)],+ ["network", "connect", "bridge", fakeDockerContainerIdentity(SESSION_KEY)],]);});diff --git a/packages/eve/src/execution/sandbox/bindings/docker.test.ts b/packages/eve/src/execution/sandbox/bindings/docker.test.tsnew file mode 100644index 000000000..a03532993--- /dev/null+++ b/packages/eve/src/execution/sandbox/bindings/docker.test.ts@@ -0,0 +1,84 @@+import { describe, expect, it, vi } from "vitest";++import { createDockerSandboxBackend } from "#execution/sandbox/bindings/docker.js";+import type { DockerCli } from "#execution/sandbox/bindings/docker-cli.js";++describe("Docker sandbox deletion", () => {+ it("stops and removes the session container", async () => {+ const run: DockerCli["run"] = vi.fn(async (args: readonly string[]) => ({+ exitCode: 0,+ stderr: "",+ 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 backend = createDockerSandboxBackend({ dockerCli });+ const handle = await backend.create({+ runtimeContext: { appRoot: "/tmp/eve-app" },+ sessionKey: "session-key",+ templateKey: null,+ });+ vi.mocked(run).mockClear();++ await handle.delete();++ expect(run).toHaveBeenNthCalledWith(1, ["stop", "-t", "0", "container-id-1"]);+ expect(run).toHaveBeenNthCalledWith(2, ["rm", "-f", "container-id-1"]);+ });++ it("keeps an old handle bound to the deleted container identity", async () => {+ let containerId = "container-id-1";+ const run: DockerCli["run"] = vi.fn(async (args: readonly string[]) => ({+ exitCode: 0,+ stderr: "",+ stdout:+ args[0] === "container" && args[3] === "{{.State.Running}}"+ ? "true\n"+ : args[0] === "container" && args[3] === "{{.Id}}"+ ? `${containerId}\n`+ : "",+ stdoutBytes: Buffer.alloc(0),+ }));+ const dockerCli: DockerCli = {+ run,+ stream() {+ throw new Error("stream is not used by this test");+ },+ };+ const backend = createDockerSandboxBackend({ dockerCli });+ const oldHandle = await backend.create({+ runtimeContext: { appRoot: "/tmp/eve-app" },+ sessionKey: "session-key",+ templateKey: null,+ });+ await oldHandle.delete();+ containerId = "container-id-2";+ await backend.create({+ runtimeContext: { appRoot: "/tmp/eve-app" },+ sessionKey: "session-key",+ templateKey: null,+ });+ vi.mocked(run).mockClear();++ await oldHandle.session.writeTextFile({ content: "stale", path: "/workspace/stale.txt" });++ expect(run).toHaveBeenCalledWith(+ expect.arrayContaining(["container-id-1"]),+ expect.objectContaining({ stdin: expect.any(Uint8Array) }),+ );+ expect(run).not.toHaveBeenCalledWith(+ expect.arrayContaining(["container-id-2"]),+ expect.anything(),+ );+ });+});diff --git a/packages/eve/src/execution/sandbox/bindings/docker.ts b/packages/eve/src/execution/sandbox/bindings/docker.tsindex d76359504..35275b27a 100644--- a/packages/eve/src/execution/sandbox/bindings/docker.ts+++ b/packages/eve/src/execution/sandbox/bindings/docker.ts@@ -126,20 +126,21 @@ export function createDockerSandboxBackend(});try {+ const buildContainerIdentity = await resolveDockerHandleIdentity(cli, buildContainerName);prewarmInput.log?.("preparing base runtime inside container");- await runDockerBaseSetup(cli, buildContainerName);+ await runDockerBaseSetup(cli, buildContainerIdentity);if (options.networkPolicy !== "allow-all") {prewarmInput.log?.("applying network policy");- await setDockerNetworkPolicy(cli, buildContainerName, options.networkPolicy);+ await setDockerNetworkPolicy(cli, buildContainerIdentity, options.networkPolicy);}const templateSession = buildSandboxSession(createDockerInternalSession({cli,- containerName: buildContainerName,+ containerIdentity: buildContainerIdentity,id: prewarmInput.templateKey,}),- (policy) => setDockerNetworkPolicy(cli, buildContainerName, policy),+ (policy) => setDockerNetworkPolicy(cli, buildContainerIdentity, policy),);if (prewarmInput.seedFiles.length > 0) {@@ -161,7 +162,7 @@ export function createDockerSandboxBackend(// Quiesce before commit so the captured filesystem is stable.prewarmInput.log?.("stopping template build container");expectDockerSuccess(- await cli.run(["stop", "-t", "0", buildContainerName]),+ await cli.run(["stop", "-t", "0", buildContainerIdentity]),`stop template build container "${buildContainerName}"`,);prewarmInput.log?.(`committing template image "${imageReference}"`);@@ -174,7 +175,7 @@ export function createDockerSandboxBackend(`LABEL ${DOCKER_SANDBOX_LABEL}.role=template`,"--change",`LABEL ${DOCKER_SANDBOX_LABEL}.template-key=${prewarmInput.templateKey}`,- buildContainerName,+ buildContainerIdentity,imageReference,]),`commit sandbox template image "${imageReference}"`,@@ -261,9 +262,10 @@ export function createDockerSandboxBackend(}}+ const containerIdentity = await resolveDockerHandleIdentity(cli, containerName);const session = buildSandboxSession(- createDockerInternalSession({ cli, containerName, id: createInput.sessionKey }),- (policy) => setDockerNetworkPolicy(cli, containerName, policy),+ createDockerInternalSession({ cli, containerIdentity, id: createInput.sessionKey }),+ (policy) => setDockerNetworkPolicy(cli, containerIdentity, policy),);return {@@ -276,13 +278,20 @@ export function createDockerSandboxBackend(sessionKey: createInput.sessionKey,};},+ async delete() {+ await stopDockerContainerIfRunning(cli, containerIdentity);+ expectDockerSuccess(+ await cli.run(["rm", "-f", containerIdentity]),+ `delete sandbox session container "${containerName}"`,+ );+ },async stop() {- await stopDockerContainerIfRunning(cli, containerName);+ await stopDockerContainerIfRunning(cli, containerIdentity);},// Session state lives in the container filesystem, so a stopped// container restarts with state intact on the next `create`.async shutdown() {- await stopDockerContainerIfRunning(cli, containerName);+ await stopDockerContainerIfRunning(cli, containerIdentity);},};},@@ -293,3 +302,13 @@ function getDockerContainerName(metadata: Record<string, unknown> | undefined):const containerName = metadata?.containerName;return typeof containerName === "string" ? containerName : undefined;}++async function resolveDockerHandleIdentity(cli: DockerCli, containerName: string): Promise<string> {+ const result = await cli.run(["container", "inspect", "--format", "{{.Id}}", containerName]);+ expectDockerSuccess(result, `resolve sandbox container identity for "${containerName}"`);+ const identity = result.stdout.trim();+ if (identity.length === 0) {+ throw new Error(`Docker returned an empty identity for sandbox container "${containerName}".`);+ }+ return identity;+}diff --git a/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.integration.test.ts b/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.integration.test.tsnew file mode 100644index 000000000..af8166e41--- /dev/null+++ b/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.integration.test.ts@@ -0,0 +1,36 @@+import { access, mkdtemp, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { describe, expect, it, vi } from "vitest";++import {+ createJustBashHandle,+ type BashSandbox,+} from "#execution/sandbox/bindings/just-bash-runtime.js";++describe("just-bash sandbox deletion", () => {+ it("disposes the interpreter and removes the session root", async () => {+ const rootPath = await mkdtemp(join(tmpdir(), "eve-just-bash-delete-"));+ await writeFile(join(rootPath, "state.txt"), "persisted");+ const dispose = vi.fn(async () => {});+ const sandbox = {+ captureState: vi.fn(async () => null),+ dispose,+ readFileBytes: vi.fn(async () => null),+ removePath: vi.fn(async () => {}),+ rootPath,+ sessionKey: "session-key",+ async spawn() {+ throw new Error("spawn is not used by this test");+ },+ writeFiles: vi.fn(async () => {}),+ } satisfies BashSandbox;+ const handle = createJustBashHandle(sandbox, "just-bash");++ await handle.delete();++ expect(dispose).toHaveBeenCalledTimes(1);+ await expect(access(rootPath)).rejects.toMatchObject({ code: "ENOENT" });+ });+});diff --git a/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.ts b/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.tsindex 0d4e5aed0..459d85161 100644--- a/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.ts+++ b/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.ts@@ -1,4 +1,4 @@-import { mkdir, readFile, writeFile } from "node:fs/promises";+import { mkdir, readFile, rm, writeFile } from "node:fs/promises";import { dirname } from "node:path";import type { IFileSystem } from "just-bash";@@ -223,6 +223,10 @@ export function createJustBashHandle(sessionKey: sandbox.sessionKey,};},+ async delete() {+ await sandbox.dispose();+ await rm(sandbox.rootPath, { force: true, recursive: true });+ },async stop() {await sandbox.dispose();},diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.test.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.test.tsindex 82923d712..c7bd18e12 100644--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.test.ts+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.test.ts@@ -208,6 +208,37 @@ describe("createMicrosandboxHandle", () => {expect(runtimeMocks.createPreparedMicrosandbox).toHaveBeenCalledTimes(2);});+ it("deletes persisted state and evicts the active-session cache", async () => {+ const vm = createFakeMicrosandboxVm("session-key");+ runtimeMocks.createPreparedMicrosandbox.mockResolvedValue(vm);+ const options = resolveMicrosandboxOptions({ image: MICROSANDBOX_DEFAULT_IMAGE });+ const createInput = {+ runtimeContext: { appRoot: "/tmp/eve-app" },+ sessionKey: "session-key",+ templateKey: "template-key",+ };++ const handle = await createMicrosandboxHandle({+ backendName: "microsandbox",+ createInput,+ options,+ optionsHash: "options-hash",+ });+ await handle.delete();++ expect(vm.shutdown).toHaveBeenCalledTimes(1);+ expect(vm.removePersisted).toHaveBeenCalledTimes(1);++ const nextHandle = await createMicrosandboxHandle({+ backendName: "microsandbox",+ createInput,+ options,+ optionsHash: "options-hash",+ });+ expect(nextHandle).not.toBe(handle);+ expect(runtimeMocks.createPreparedMicrosandbox).toHaveBeenCalledTimes(2);+ });+it("reports a missing template snapshot race as not provisioned", async () => {runtimeMocks.createPreparedMicrosandbox.mockRejectedValueOnce(new Error("snapshot template-snapshot not found"),@@ -330,7 +361,7 @@ function createFakeMicrosandboxVm(sessionKey: string) {async removePath({ path }: { readonly path: string }) {files.delete(path);},- async removePersisted() {},+ removePersisted: vi.fn(async () => {}),async setNetworkPolicy() {},async spawn() {throw new Error("spawn is not used by this test.");diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.tsindex 7095b2225..1a4c05b03 100644--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.ts+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-lifecycle.ts@@ -308,6 +308,11 @@ function createHandle(sessionKey: sandbox.id,};},+ async delete() {+ await sandbox.shutdown();+ await sandbox.removePersisted();+ onShutdown?.();+ },async stop() {await sandbox.stop();onShutdown?.();diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.tsindex f0bcfcc3b..f697452fa 100644--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.ts+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.ts@@ -181,9 +181,12 @@ export class MicrosandboxVm {async removePersisted(): Promise<void> {await removeSandboxIfExists(this.#input.module, this.#sandboxName);- if (this.#stateSnapshotName !== undefined) {- await removeSnapshotIfExists(this.#input.module, this.#stateSnapshotName);+ const stateSnapshotName = this.#stateSnapshotName;+ if (stateSnapshotName === undefined) {+ return;}+ await removeSnapshotIfExists(this.#input.module, stateSnapshotName);+ this.#stateSnapshotName = undefined;}async setNetworkPolicy(policy: SandboxNetworkPolicy): Promise<void> {diff --git a/packages/eve/src/execution/sandbox/bindings/vercel-base-runtime.ts b/packages/eve/src/execution/sandbox/bindings/vercel-base-runtime.tsindex 9853865a9..d2c912a27 100644--- a/packages/eve/src/execution/sandbox/bindings/vercel-base-runtime.ts+++ b/packages/eve/src/execution/sandbox/bindings/vercel-base-runtime.ts@@ -1,8 +1,10 @@import { buildDockerBaseSetupScript } from "#execution/sandbox/bindings/docker-base-setup.js";+import type { VercelSandboxCreateParams } from "#execution/sandbox/bindings/vercel-create-sdk.js";import type {VercelCreateOptions,VercelSandbox,} from "#execution/sandbox/bindings/vercel-sdk-types.js";+import type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";/*** Prepares a fresh Vercel sandbox for use by the framework.@@ -23,6 +25,20 @@ export async function applyInitialVercelNetworkPolicy(}}+export function withBaseSetupNetworkPolicy(+ createOptions: VercelSandboxCreateParams,+): VercelSandboxCreateParams {+ return { ...createOptions, networkPolicy: "allow-all" };+}++export function createVercelNetworkPolicySetter(+ sandbox: VercelSandbox,+): (policy: SandboxNetworkPolicy) => Promise<void> {+ return async (policy) => {+ await sandbox.update({ networkPolicy: policy });+ };+}+async function runSandboxBootstrapStep(sandbox: VercelSandbox,input: { readonly failureMessage: string; readonly script: string },diff --git a/packages/eve/src/execution/sandbox/bindings/vercel-lifecycle.ts b/packages/eve/src/execution/sandbox/bindings/vercel-lifecycle.tsnew file mode 100644index 000000000..7f71ac97f--- /dev/null+++ b/packages/eve/src/execution/sandbox/bindings/vercel-lifecycle.ts@@ -0,0 +1,50 @@+import {+ getVercelSandboxCredentials,+ getVercelSandboxFetch,+ type VercelSandboxCredentials,+} from "#execution/sandbox/bindings/vercel-credentials.js";+import type {+ VercelCreateOptions,+ VercelDeleteGetOptions,+ VercelDeleteModule,+ VercelSandbox,+} from "#execution/sandbox/bindings/vercel-sdk-types.js";++export async function deleteVercelSandbox(input: {+ readonly createOptions: VercelCreateOptions;+ readonly loadDeleteSandboxModule: () => Promise<VercelDeleteModule>;+ readonly sandbox: VercelSandbox;+ readonly signal?: AbortSignal;+}): Promise<void> {+ await stopVercelSandbox(input.sandbox);+ const credentials = await resolveVercelSandboxCredentials(input.createOptions);+ const sandboxModule = await input.loadDeleteSandboxModule();+ const sandbox = await sandboxModule.Sandbox.get({+ ...credentials,+ fetch: getVercelSandboxFetch(input.createOptions),+ name: input.sandbox.name,+ resume: false,+ signal: input.signal,+ } as VercelDeleteGetOptions);+ await sandbox.delete({+ deleteOrphanSnapshots: true,+ signal: input.signal,+ });+}++export async function stopVercelSandbox(sandbox: VercelSandbox): Promise<void> {+ if (sandbox.status !== "running" && sandbox.status !== "pending") {+ return;+ }+ await sandbox.stop();+}++async function resolveVercelSandboxCredentials(+ createOptions: VercelCreateOptions,+): Promise<VercelSandboxCredentials | Record<string, never>> {+ try {+ return await getVercelSandboxCredentials(createOptions);+ } catch {+ return {};+ }+}diff --git a/packages/eve/src/execution/sandbox/bindings/vercel-sdk-types.ts b/packages/eve/src/execution/sandbox/bindings/vercel-sdk-types.tsindex b5f67d252..17882ab4e 100644--- a/packages/eve/src/execution/sandbox/bindings/vercel-sdk-types.ts+++ b/packages/eve/src/execution/sandbox/bindings/vercel-sdk-types.ts@@ -1,4 +1,5 @@import type * as Vercel from "#compiled/@vercel/sandbox/index.js";+import type * as VercelDelete from "#compiled/@vercel/sandbox-delete/index.js";export type VercelCreateOptions = NonNullable<Parameters<typeof Vercel.Sandbox.create>[0]>;@@ -7,3 +8,7 @@ export type VercelGetOptions = Parameters<typeof Vercel.Sandbox.get>[0];export type VercelModule = typeof Vercel;export type VercelSandbox = Vercel.Sandbox;++export type VercelDeleteGetOptions = Parameters<typeof VercelDelete.Sandbox.get>[0];++export type VercelDeleteModule = typeof VercelDelete;diff --git a/packages/eve/src/execution/sandbox/bindings/vercel.test.ts b/packages/eve/src/execution/sandbox/bindings/vercel.test.tsindex cab2e0fe4..1d0efe4ea 100644--- a/packages/eve/src/execution/sandbox/bindings/vercel.test.ts+++ b/packages/eve/src/execution/sandbox/bindings/vercel.test.ts@@ -1097,6 +1097,60 @@ describe("createVercelSandbox", () => {);});+ it("asks Vercel to delete orphan snapshots when deleting the sandbox", async () => {+ const templateSandbox = createMockSandbox({ name: "template" });+ const sessionSandbox = createMockSandbox({ name: "session" });+ const order: string[] = [];+ sessionSandbox.stop.mockImplementation(async () => {+ order.push("stop");+ });+ const stableDelete = vi.fn(async () => {+ order.push("sandbox-delete");+ });+ const stableGet = vi.fn(async () => {+ order.push("sandbox-get");+ return { delete: stableDelete };+ });+ const sandboxModule = {+ Sandbox: {+ create: vi+ .fn()+ .mockResolvedValueOnce(templateSandbox)+ .mockResolvedValueOnce(sessionSandbox),+ get: vi.fn().mockResolvedValue(null),+ },+ };+ const backend = createTestVercelSandbox({+ loadDeleteSandboxModule: async () => ({ Sandbox: { get: stableGet } }) as never,+ loadSandboxModule: async () => sandboxModule as never,+ });+ await backend.prewarm({+ runtimeContext: { appRoot: "/tmp/test-app-root" },+ seedFiles: [],+ templateKey: "template-key",+ });+ const handle = await backend.create({+ runtimeContext: { appRoot: "/tmp/test-app-root" },+ sessionKey: "session-key",+ templateKey: "template-key",+ });+ const abortSignal = new AbortController().signal;++ await expect(handle.delete({ abortSignal })).resolves.toBeUndefined();++ expect(order).toEqual(["stop", "sandbox-get", "sandbox-delete"]);+ expect(stableGet).toHaveBeenCalledWith({+ fetch: expect.any(Function),+ name: "session",+ resume: false,+ signal: abortSignal,+ });+ expect(stableDelete).toHaveBeenCalledWith({+ deleteOrphanSnapshots: true,+ signal: abortSignal,+ });+ });+it("skips the stop call on shutdown when the sandbox is not running", async () => {const templateSandbox = createMockSandbox({ name: "template" });const sessionSandbox = createMockSandbox({ name: "session", status: "stopped" });diff --git a/packages/eve/src/execution/sandbox/bindings/vercel.ts b/packages/eve/src/execution/sandbox/bindings/vercel.tsindex 2ce7c5e65..1314062f8 100644--- a/packages/eve/src/execution/sandbox/bindings/vercel.ts+++ b/packages/eve/src/execution/sandbox/bindings/vercel.ts@@ -1,9 +1,10 @@import {applyInitialVercelNetworkPolicy,+ createVercelNetworkPolicySetter,ensureVercelSandboxBaseRuntime,+ withBaseSetupNetworkPolicy,} from "#execution/sandbox/bindings/vercel-base-runtime.js";import type { SandboxBootstrapContext } from "#public/definitions/sandbox.js";-import type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";import type {InternalSandboxSession,SandboxProcess,@@ -44,10 +45,15 @@ import {isVercelSnapshotUnavailableError,} from "#execution/sandbox/bindings/vercel-errors.js";import { getNamedVercelSandbox } from "#execution/sandbox/bindings/vercel-lookup.js";+import {+ deleteVercelSandbox,+ stopVercelSandbox,+} from "#execution/sandbox/bindings/vercel-lifecycle.js";import { normalizeVercelReadStream } from "#execution/sandbox/bindings/vercel-read-stream.js";import { resolveSandboxModelPath } from "#shared/skill-paths.js";import type {VercelCreateOptions,+ VercelDeleteModule,VercelModule,VercelSandbox,} from "#execution/sandbox/bindings/vercel-sdk-types.js";@@ -55,6 +61,7 @@ import type {export interface CreateVercelSandboxInput {readonly createSandbox?: CreateVercelSandbox;readonly createOptions?: VercelCreateOptions;+ readonly loadDeleteSandboxModule?: () => Promise<VercelDeleteModule>;readonly loadSandboxModule?: () => Promise<VercelModule>;readonly resolveSessionCreateOptions?: (context: VercelSandboxSessionCreateContext,@@ -73,6 +80,9 @@ export function createVercelSandbox(): SandboxBackend<VercelSandboxBootstrapUseOptions, VercelSandboxSessionUseOptions> {const loadSandboxModule =input.loadSandboxModule ?? (async () => await import("#compiled/@vercel/sandbox/index.js"));+ const loadDeleteSandboxModule =+ input.loadDeleteSandboxModule ??+ (async () => await import("#compiled/@vercel/sandbox-delete/index.js"));const createOptions: VercelCreateOptions = {timeout: DEFAULT_SANDBOX_TIMEOUT_MS,...input.createOptions,@@ -141,7 +151,12 @@ export function createVercelSandbox(await applyInitialVercelNetworkPolicy(session.sandbox, createOptions.networkPolicy);}- return createHandle(session.sandbox, createInput.sessionKey);+ return createHandle({+ createOptions,+ loadDeleteSandboxModule,+ sandbox: session.sandbox,+ sessionKey: createInput.sessionKey,+ });},async prewarm(prewarmInput: SandboxBackendPrewarmInput<VercelSandboxBootstrapUseOptions>,@@ -443,16 +458,13 @@ function createSessionCreateParams(};}-function withBaseSetupNetworkPolicy(- createOptions: VercelSandboxCreateParams,-): VercelSandboxCreateParams {- return { ...createOptions, networkPolicy: "allow-all" };-}--function createHandle(- sandbox: VercelSandbox,- sessionKey: string,-): SandboxBackendHandle<VercelSandboxSessionUseOptions> {+function createHandle(input: {+ readonly createOptions: VercelCreateOptions;+ readonly loadDeleteSandboxModule: () => Promise<VercelDeleteModule>;+ readonly sandbox: VercelSandbox;+ readonly sessionKey: string;+}): SandboxBackendHandle<VercelSandboxSessionUseOptions> {+ const { sandbox, sessionKey } = input;return {session: buildSandboxSession(createVercelInternalSandboxSession(sandbox, sessionKey),@@ -474,6 +486,14 @@ function createHandle(sessionKey,};},+ async delete(options) {+ await deleteVercelSandbox({+ createOptions: input.createOptions,+ loadDeleteSandboxModule: input.loadDeleteSandboxModule,+ sandbox,+ signal: options?.abortSignal,+ });+ },async stop() {await stopVercelSandbox(sandbox);},@@ -487,21 +507,6 @@ function createHandle(};}-async function stopVercelSandbox(sandbox: VercelSandbox): Promise<void> {- if (sandbox.status !== "running" && sandbox.status !== "pending") {- return;- }- await sandbox.stop();-}--function createVercelNetworkPolicySetter(- sandbox: VercelSandbox,-): (policy: SandboxNetworkPolicy) => Promise<void> {- return async (policy) => {- await sandbox.update({ networkPolicy: policy });- };-}-function createVercelInternalSandboxSession(sandbox: VercelSandbox,id: string,diff --git a/packages/eve/src/execution/sandbox/ensure.test.ts b/packages/eve/src/execution/sandbox/ensure.test.tsindex 78987a02f..1bf663732 100644--- a/packages/eve/src/execution/sandbox/ensure.test.ts+++ b/packages/eve/src/execution/sandbox/ensure.test.ts@@ -61,7 +61,7 @@ function createTestRegistry(};}-function createBackend(): SandboxBackend {+function createBackend(options?: { readonly delete?: () => Promise<void> }): SandboxBackend {const sandbox = mockSandbox({ id: "sbx_session_auth" });const create = vi.fn(async (input: SandboxBackendCreateInput) => {return {@@ -70,6 +70,7 @@ function createBackend(): SandboxBackend {metadata: {},sessionKey: input.sessionKey,}),+ delete: vi.fn(options?.delete ?? (async () => {})),stop: vi.fn(async () => {}),useSessionFn: async () => sandbox.session,shutdown: async () => {},@@ -82,6 +83,7 @@ function createBackend(): SandboxBackend {async function ensure(input: {readonly compiledArtifactsSource?: RuntimeCompiledArtifactsSource;+ readonly ownsSandbox?: boolean;readonly runOnSession?: (callback: () => Promise<void>) => Promise<void>;readonly registry: RuntimeSandboxRegistry;readonly state?: SandboxState;@@ -91,6 +93,7 @@ async function ensure(input: {compiledArtifactsSource:input.compiledArtifactsSource ?? createBundledRuntimeCompiledArtifactsSource(),nodeId: "__root__",+ ownsSandbox: input.ownsSandbox,registry: input.registry,runOnSession: input.runOnSession,sessionId: "session_1",@@ -246,9 +249,11 @@ describe("ensureSandboxAccess", () => {let observedSession: Session | undefined;let observedSessionId: string | undefined;+ let observedContextKeys: string[] | undefined;const onSession = vi.fn((input) => {observedSession = loadContext().require(SessionKey);observedSessionId = input.ctx.session.id;+ observedContextKeys = Object.keys(input.ctx);});const backend = createBackend();const registry = createTestRegistry({ onSession }, backend);@@ -261,6 +266,7 @@ describe("ensureSandboxAccess", () => {expect(observedSession).toBe(session);expect(observedSessionId).toBe("session_1");+ expect(observedContextKeys).toEqual(["session"]);expect(onSession).toHaveBeenCalledWith({ctx: expect.objectContaining({session: expect.objectContaining({ id: "session_1" }),@@ -427,6 +433,55 @@ describe("ensureSandboxAccess", () => {const handle = await vi.mocked(backend.create).mock.results[0]?.value;expect(handle?.stop).toHaveBeenCalledTimes(1);});++ it("deletes the sandbox and reprovisions a fresh handle on the next access", async () => {+ const ctx = new ContextContainer();+ ctx.set(SessionKey, createSession());+ const onSession = vi.fn();+ const backend = createBackend();+ const access = await ensure({+ registry: createTestRegistry({ onSession }, backend),+ runOnSession: async (callback) => await contextStorage.run(ctx, callback),+ });++ await expect(access.delete!()).resolves.toBeUndefined();+ await expect(access.captureState()).resolves.toEqual({ initialized: false, session: null });+ await access.get();++ expect(backend.create).toHaveBeenCalledTimes(2);+ expect(onSession).toHaveBeenCalledTimes(2);+ const firstHandle = await vi.mocked(backend.create).mock.results[0]!.value;+ expect(firstHandle.delete).toHaveBeenCalledTimes(1);+ });++ it("preserves the current handle and state when deletion fails", async () => {+ const backend = createBackend({+ delete: async () => {+ throw new Error("provider unreachable");+ },+ });+ const access = await ensure({ registry: createTestRegistry({}, backend) });++ await expect(access.delete!()).rejects.toThrow("provider unreachable");+ await access.get();++ expect(backend.create).toHaveBeenCalledTimes(1);+ await expect(access.captureState()).resolves.toMatchObject({+ initialized: true,+ session: { backendName: "test" },+ });+ });++ it("rejects deletion from a session that does not own the shared sandbox", async () => {+ const backend = createBackend();+ const access = await ensure({ ownsSandbox: false, registry: createTestRegistry({}, backend) });++ await expect(access.delete!()).rejects.toThrow(+ "Only the owning session can delete a shared sandbox",+ );++ expect(backend.create).not.toHaveBeenCalled();+ });});function createDeferred<T>() {diff --git a/packages/eve/src/execution/sandbox/ensure.ts b/packages/eve/src/execution/sandbox/ensure.tsindex 51e6a5e1c..cc925f695 100644--- a/packages/eve/src/execution/sandbox/ensure.ts+++ b/packages/eve/src/execution/sandbox/ensure.ts@@ -27,6 +27,8 @@ import type { SandboxAccess, SandboxSessionState, SandboxState } from "#sandbox/export interface EnsureSandboxAccessInput {readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;readonly nodeId: string;+ /** Whether this durable session owns the sandbox lifecycle. */+ readonly ownsSandbox?: boolean;readonly registry: RuntimeSandboxRegistry;readonly sessionId: string;readonly runOnSession?: (callback: () => Promise<void>) => Promise<void>;@@ -147,7 +149,10 @@ export async function ensureSandboxAccess(input: EnsureSandboxAccessInput): Promif (!initialized) {await runOnSession(async () => {- await definition.onSession?.({ ctx: buildCallbackContext(), use: handle.useSessionFn });+ await definition.onSession?.({+ ctx: { session: buildCallbackContext().session },+ use: handle.useSessionFn,+ });});initialized = true;}@@ -177,6 +182,21 @@ export async function ensureSandboxAccess(input: EnsureSandboxAccessInput): Promsession: persistedSession,};},+ async delete(options) {+ if (input.ownsSandbox === false) {+ throw new Error(+ "Only the owning session can delete a shared sandbox. Delete it from the parent session instead.",+ );+ }+ const handle = await getHandle();+ if (handle === null) {+ throw new Error("The sandbox is not available in the current authored runtime context.");+ }+ await handle.delete(options);+ handlePromise = undefined;+ initialized = false;+ persistedSession = null;+ },async get(): Promise<SandboxSession | null> {const handle = await getHandle();if (handle === null) return null;diff --git a/packages/eve/src/execution/session-reset.integration.test.ts b/packages/eve/src/execution/session-reset.integration.test.tsindex 6f8371f80..0a47d74c2 100644--- a/packages/eve/src/execution/session-reset.integration.test.ts+++ b/packages/eve/src/execution/session-reset.integration.test.ts@@ -76,6 +76,7 @@ function createSessionSandboxHarness() {metadata: {},sessionKey: input.sessionKey,}),+ delete: async () => {},session: sandbox.session,stop: async () => {},shutdown: async () => {},diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts b/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.tsindex b6362c4d0..eb0bd136f 100644--- a/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts+++ b/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts@@ -102,6 +102,7 @@ describe("background subagent tool execution", () => {metadata: {},sessionKey: input.sessionKey,}),+ delete: async () => {},session: sandbox.session,shutdown: async () => {},stop: async () => {},diff --git a/packages/eve/src/execution/workflow-entry.integration.test.ts b/packages/eve/src/execution/workflow-entry.integration.test.tsindex 7bcf031d8..d6b6d5fe8 100644--- a/packages/eve/src/execution/workflow-entry.integration.test.ts+++ b/packages/eve/src/execution/workflow-entry.integration.test.ts@@ -27,6 +27,7 @@ import type {} from "#shared/connection-types.js";import type { ResolvedToolDefinition } from "#runtime/types.js";import { toInputSchema } from "#tools/schema.js";+import { defineHook } from "#public/definitions/hook.js";function buildSerializedContext(overrides: {audience?: "public" | "private" | "unknown";@@ -1120,6 +1121,47 @@ describe("workflowEntry integration", () => {});});+ it("can delete the sandbox from a session.completed hook", async () => {+ let deletions = 0;+ const runtime = await createTestRuntime({+ agent: { name: "workflow-entry-task-delete-sandbox" },+ modules: [+ {+ logicalPath: "hooks/delete-sandbox.ts",+ loadNamespace: async () => ({+ default: defineHook({+ events: {+ async "session.completed"(_event, ctx) {+ const sandbox = await ctx.getSandbox();+ await sandbox.delete();+ deletions += 1;+ },+ },+ }),+ }),+ },+ ],+ });++ await runtime.run(async () => {+ const run = await start(workflowEntry, [+ {+ input: { message: "hello there" },+ serializedContext: buildSerializedContext({+ channelKind: "http",+ continuationToken: "http:workflow-entry-task-delete-sandbox",+ mode: "task",+ }),+ },+ ]);++ await expect(run.returnValue).resolves.toEqual({+ output: expect.stringContaining("hello there"),+ });+ expect(deletions).toBe(1);+ });+ });+it("returns agent-declared structured output in task mode", async () => {const outputSchema = {properties: {diff --git a/packages/eve/src/internal/testing/app-harness.ts b/packages/eve/src/internal/testing/app-harness.tsindex b42aa93be..d265f3ed9 100644--- a/packages/eve/src/internal/testing/app-harness.ts+++ b/packages/eve/src/internal/testing/app-harness.ts@@ -155,6 +155,7 @@ const TEST_SANDBOX_BACKEND: SandboxBackend = {metadata: {},sessionKey: input.sessionKey,}),+ delete: async (options) => await sandbox.access.delete?.(options),shutdown: async () => undefined,stop: async () => undefined,};diff --git a/packages/eve/src/internal/testing/mocks/mock-sandbox.ts b/packages/eve/src/internal/testing/mocks/mock-sandbox.tsindex 2f6ff4c9b..28628d336 100644--- a/packages/eve/src/internal/testing/mocks/mock-sandbox.ts+++ b/packages/eve/src/internal/testing/mocks/mock-sandbox.ts@@ -27,6 +27,8 @@ import { bufferToStream, streamToBuffer } from "#execution/sandbox/stream-utils.* or file contents without touching disk or spawning processes.*/export interface MockSandboxInput {+ /** Callback invoked when authored runtime code deletes this sandbox. */+ readonly delete?: () => Promise<void> | void;/*** Stable sandbox identifier. Defaults to `"sbx_mock"`.*/@@ -252,6 +254,9 @@ export function mockSandbox(input: MockSandboxInput = {}): MockSandbox {session: null,};},+ async delete(): Promise<void> {+ await input.delete?.();+ },async get(): Promise<SandboxSession> {return session;},diff --git a/packages/eve/src/public/definitions/exact.test.ts b/packages/eve/src/public/definitions/exact.test.tsindex aa43a4e87..902fa0d3b 100644--- a/packages/eve/src/public/definitions/exact.test.ts+++ b/packages/eve/src/public/definitions/exact.test.ts@@ -452,7 +452,13 @@ function typeOnlyFixtures(): void {defineSandbox({async onSession({ ctx, use }) {const sessionId: string = ctx.session.id;+ // @ts-expect-error Sandbox lifecycle access is unavailable during session initialization.+ void ctx.getSandbox;+ // @ts-expect-error Skill access is unavailable during session initialization.+ void ctx.getSkill;const sandbox = await use();+ // @ts-expect-error Runtime lifecycle access is unavailable during session initialization.+ void sandbox.delete;void sandbox;void sessionId;},diff --git a/packages/eve/src/public/definitions/sandbox-backend.ts b/packages/eve/src/public/definitions/sandbox-backend.tsindex 34b870420..418131433 100644--- a/packages/eve/src/public/definitions/sandbox-backend.ts+++ b/packages/eve/src/public/definitions/sandbox-backend.ts@@ -1,6 +1,7 @@export type {SandboxBackendHandle,SandboxBackendSessionState,+ SandboxDeleteOptions,SandboxSeedFile,SandboxBackendTags,SandboxBackendRuntimeContext,diff --git a/packages/eve/src/public/sandbox/index.ts b/packages/eve/src/public/sandbox/index.tsindex 800769694..5b7e67de6 100644--- a/packages/eve/src/public/sandbox/index.ts+++ b/packages/eve/src/public/sandbox/index.ts@@ -34,6 +34,7 @@ export type {SandboxBackendPrewarmInput,SandboxBackendRuntimeContext,SandboxBackendSessionState,+ SandboxDeleteOptions,SandboxSeedFile,} from "#public/definitions/sandbox-backend.js";export type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";diff --git a/packages/eve/src/sandbox/state.ts b/packages/eve/src/sandbox/state.tsindex 3d64152fa..5d3cb7e16 100644--- a/packages/eve/src/sandbox/state.ts+++ b/packages/eve/src/sandbox/state.ts@@ -1,5 +1,6 @@import type { SandboxSession } from "#public/definitions/sandbox.js";import type { SandboxBackendSessionState } from "#public/definitions/sandbox-backend.js";+import type { SandboxDeleteOptions } from "#public/definitions/sandbox-backend.js";/*** Serializable sandbox reconnect record stored on the harness session.@@ -31,6 +32,7 @@ export interface SandboxState {*/export interface SandboxAccess {captureState(): Promise<SandboxState>;+ delete?(options?: SandboxDeleteOptions): Promise<void>;get(): Promise<SandboxSession | null>;stop(): Promise<void>;}diff --git a/packages/eve/src/shared/sandbox-backend.ts b/packages/eve/src/shared/sandbox-backend.tsindex a727d86f1..4c9110eb4 100644--- a/packages/eve/src/shared/sandbox-backend.ts+++ b/packages/eve/src/shared/sandbox-backend.ts@@ -12,6 +12,11 @@ export interface SandboxBackendHandle<SO = Record<string, never>> {readonly session: SandboxSession;readonly useSessionFn: SandboxSessionUseFn<SO>;captureState(): Promise<SandboxBackendSessionState>;+ /**+ * Permanently deletes this sandbox and its disposable backend state.+ * Reusable or shared template state must not be deleted.+ */+ delete(options?: SandboxDeleteOptions): Promise<void>;/*** Stops the underlying compute at an authored runtime boundary while* preserving any backend state needed to reopen the durable session.@@ -27,6 +32,11 @@ export interface SandboxBackendHandle<SO = Record<string, never>> {shutdown(): Promise<void>;}+/** Options for permanently deleting one sandbox. */+export interface SandboxDeleteOptions {+ readonly abortSignal?: AbortSignal;+}+/*** Serializable per-sandbox reconnect record stored on the harness session.*diff --git a/packages/eve/src/shared/sandbox-definition.ts b/packages/eve/src/shared/sandbox-definition.tsindex e431db009..1351fba34 100644--- a/packages/eve/src/shared/sandbox-definition.ts+++ b/packages/eve/src/shared/sandbox-definition.ts@@ -34,12 +34,13 @@ export interface SandboxBootstrapContext<O = Record<string, never>> {/*** Argument passed to a sandbox `onSession` hook, invoked once per live- * session. `ctx` is the runtime {@link SessionContext} (session id, auth,- * turn). `use(options?)` opens the live session, applying backend-specific- * `options` (typed by the backend's session-use options `SO`).+ * session. `ctx` contains the active session metadata; sandbox access during+ * initialization goes through `use(options?)`, which opens the live session+ * and applies backend-specific `options` (typed by the backend's session-use+ * options `SO`).*/export interface SandboxSessionContext<O = Record<string, never>> {- readonly ctx: SessionContext;+ readonly ctx: Pick<SessionContext, "session">;readonly use: SandboxSessionUseFn<O>;}diff --git a/packages/eve/src/shared/sandbox-session.ts b/packages/eve/src/shared/sandbox-session.tsindex 6194ddc92..855d30cc6 100644--- a/packages/eve/src/shared/sandbox-session.ts+++ b/packages/eve/src/shared/sandbox-session.ts@@ -1,5 +1,6 @@import type { Experimental_SandboxSession as AiSdkSandbox } from "ai";+import type { SandboxDeleteOptions } from "#shared/sandbox-backend.js";import type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";/**@@ -148,9 +149,11 @@ export interface SandboxSession extends Pick<* `ctx.getSandbox()`.** Unlike the I/O-only session used during sandbox initialization, this handle- * always exposes a provider-backed `stop()` method.+ * exposes provider-backed lifecycle operations.*/export interface RuntimeSandboxSession extends SandboxSession {+ /** Permanently deletes this sandbox and its disposable backend state. */+ delete(options?: SandboxDeleteOptions): Promise<void>;/*** Stops the backing sandbox compute while preserving the durable session.* A later runtime callback reopens the session through its configureddiff --git a/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts b/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.tsindex eb8f6cf9c..a19a5bee3 100644--- a/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts+++ b/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts@@ -249,7 +249,7 @@ describe("mounted extension installed under node_modules", () => {);expect(JSON.parse(extensionFiles[`node_modules/${PACKAGE_NAME}/dist/extension/_manifest.json`]!),- ).toMatchObject({ requires: { channel: 10, schedule: 4, subagent: 5 } });+ ).toMatchObject({ requires: { channel: 11, schedule: 4, subagent: 5 } });const app = await scenarioApp({name: "mounted-extension-installed",installDependencies: true,diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex c41d3d714..4f0eb8462 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -54,6 +54,9 @@ catalogs:'@vercel/sandbox':specifier: 2.8.0version: 2.8.0+ '@vercel/sandbox-delete':+ specifier: npm:@vercel/[email protected]+ version: 3.2.0'@vercel/sandbox-drives':specifier: npm:@vercel/[email protected]version: 2.10.0-beta.0@@ -247,7 +250,7 @@ importers:devDependencies:'@agent-browser/eve':specifier: ^0.33.0- version: 0.33.0(@vercel/[email protected])(eve@packages+eve)+ version: 0.33.0(@vercel/[email protected])(eve@packages+eve)'@agentphone/chat-sdk-adapter':specifier: 0.1.0version: 0.1.0([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected])@@ -1376,6 +1379,9 @@ importers:'@vercel/sandbox':specifier: 'catalog:'version: 2.8.0+ '@vercel/sandbox-delete':+ specifier: 'catalog:'+ version: '@vercel/[email protected]''@vercel/sandbox-drives':specifier: 'catalog:'version: '@vercel/[email protected]'@@ -8149,6 +8155,9 @@ packages:'@vercel/[email protected]':resolution: {integrity: sha512-1pF3id7LIG2GfjkEAZW+ZngMDdywJw7aFLOyIlry/lj8v3b4GMn3WCuBbvG4N4wTmYUfFzHaVHfdwVpqALEFkw==}+ '@vercel/[email protected]':+ resolution: {integrity: sha512-aIOd8Z+NgpdS8k4Y1EEvVoEml4+mtBmJVtfw4rJpL5j5K2gS70YfR6LbnT7/bfHbsRsFZhp/JSTB3TeOw/pgsw==}+'@vercel/[email protected]':resolution: {integrity: sha512-uAl+pEZZnFYRFzE/43ihP3aYTJ+4v0+coiMYobYMqtaERWknYKuRZWEj9Dk9r87yWXfxclsQugXkN42kaOcySw==}@@ -15896,17 +15905,17 @@ ignoredOptionalDependencies:snapshots:- '@agent-browser/[email protected](@vercel/[email protected])(eve@packages+eve)':+ '@agent-browser/[email protected](@vercel/[email protected])(eve@packages+eve)':dependencies:- '@agent-browser/sandbox': 0.33.0(@vercel/[email protected])+ '@agent-browser/sandbox': 0.33.0(@vercel/[email protected])eve: link:packages/evezod: 4.4.3transitivePeerDependencies:- '@vercel/sandbox'- '@agent-browser/[email protected](@vercel/[email protected])':+ '@agent-browser/[email protected](@vercel/[email protected])':optionalDependencies:- '@vercel/sandbox': 2.8.0+ '@vercel/sandbox': 3.2.0'@agentclientprotocol/[email protected]([email protected])':dependencies:@@ -22896,6 +22905,24 @@ snapshots:- bare-abort-controller- react-native-b4a+ '@vercel/[email protected]':+ dependencies:+ '@vercel/oidc': 3.2.0+ '@workflow/serde': 4.1.0-beta.2+ async-retry: 1.3.3+ jose: 6.2.3+ jsonlines: 0.1.1+ lru-cache: 10.4.3+ ms: 2.1.3+ picocolors: 1.1.1+ tar-stream: 3.1.7+ undici: 7.29.0+ xdg-app-paths: 5.1.0+ zod: 4.4.3+ transitivePeerDependencies:+ - bare-abort-controller+ - react-native-b4a+'@vercel/[email protected]':dependencies:zod: 4.4.3diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex c82efe342..89ded6f7b 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -41,6 +41,7 @@ catalog:"@vercel/connect": "1.0.0""@vercel/otel": "2.1.3""@vercel/sandbox": "2.8.0"+ "@vercel/sandbox-delete": "npm:@vercel/[email protected]""@vercel/sandbox-drives": "npm:@vercel/[email protected]""@workflow/world-postgres": "5.0.0-beta.35"ai: "^7.0.58"