Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): clean up sandboxes when sessions end (#4511)

Casey Gowrie33a95cffaf7d
diff --git a/.changeset/terminal-sandbox-cleanup.md b/.changeset/terminal-sandbox-cleanup.md
new file mode 100644
index 000000000..66867bbbc
--- /dev/null
+++ b/.changeset/terminal-sandbox-cleanup.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Invoke sandbox provider cleanup when a durable session completes, expires, or fails. Custom providers can implement `onSessionEnd()` to release session-owned resources directly from persisted state.
diff --git a/docs/sandbox/index.mdx b/docs/sandbox/index.mdx
index 377859c6b..fb61fb1a6 100644
--- a/docs/sandbox/index.mdx
+++ b/docs/sandbox/index.mdx
@@ -182,6 +182,10 @@ export const AcmeSandbox = defineSandboxProvider<
const client = createAcmeClient(options);
return {
+ async onSessionEnd(_ctx, _artifact, state, { reason }) {
+ await client.delete({ id: state.remoteId, reason });
+ },
+
async prepare(ctx) {
const temporary = await client.createTemporary({
files: await ctx.files.list(),
@@ -213,7 +217,11 @@ 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. Provider handles implement `onSessionStop()`, `onRuntimeShutdown()`, and `onSessionDelete()`.
+`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.
+
+`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.
+
+Provider handles implement `onSessionStop()`, `onRuntimeShutdown()`, and `onSessionDelete()`. 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.
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()`.
@@ -231,7 +239,7 @@ 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.
+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.
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.
diff --git a/packages/eve/extension-contracts/compatibility/channel/v52.ts b/packages/eve/extension-contracts/compatibility/channel/v52.ts
new file mode 100644
index 000000000..4a15cbd69
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/channel/v52.ts
@@ -0,0 +1,12 @@
+import { defineChannel, POST } from "#public/channels/index.js";
+
+export default defineChannel({
+ routes: [POST("/report", async () => new Response("ok"))],
+ state: { reply: "" },
+ context: (state) => state,
+ events: {
+ "message.completed"({ message }, channel, ctx) {
+ channel.reply = `${ctx.session.id}: ${message}`;
+ },
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/connection/v41.ts b/packages/eve/extension-contracts/compatibility/connection/v41.ts
new file mode 100644
index 000000000..3728132ac
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/connection/v41.ts
@@ -0,0 +1,8 @@
+import { defineMcpClientConnection } from "#public/connections/index.js";
+
+export default defineMcpClientConnection({
+ description: "Specialist tools.",
+ url: "https://specialist.example.test/eve/v1/mcp",
+ protocolVersionDiscovery: false,
+ approval: ({ session }) => (session.auth.current === null ? "denied" : "user-approval"),
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicTool/v73.ts b/packages/eve/extension-contracts/compatibility/dynamicTool/v73.ts
new file mode 100644
index 000000000..0afec7680
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicTool/v73.ts
@@ -0,0 +1,12 @@
+import { defineDynamic, defineTool } from "#public/tools/index.js";
+
+export default defineDynamic({
+ events: {
+ "turn.started": (_event, ctx) =>
+ defineTool({
+ description: "Report the current session.",
+ inputSchema: { type: "object", properties: {} },
+ execute: () => ({ sessionId: ctx.session.id }),
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/hook/v39.ts b/packages/eve/extension-contracts/compatibility/hook/v39.ts
new file mode 100644
index 000000000..a224fb6ee
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/hook/v39.ts
@@ -0,0 +1,9 @@
+import { defineHook } from "#public/hooks/index.js";
+
+export default defineHook({
+ events: {
+ "authorization.required": (event, ctx) => {
+ console.info("Sign-in required", { name: event.data.name, sessionId: ctx.session.id });
+ },
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/state/v10.ts b/packages/eve/extension-contracts/compatibility/state/v10.ts
new file mode 100644
index 000000000..5c774760c
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/state/v10.ts
@@ -0,0 +1,7 @@
+import { defineState } from "#public/context/index.js";
+
+export const visits = defineState("compatibility.visits", () => ({ count: 0 }));
+export function recordVisit(): number {
+ visits.update((current) => ({ count: current.count + 1 }));
+ return visits.get().count;
+}
diff --git a/packages/eve/extension-contracts/compatibility/tool/v78.ts b/packages/eve/extension-contracts/compatibility/tool/v78.ts
new file mode 100644
index 000000000..fae115795
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/tool/v78.ts
@@ -0,0 +1,9 @@
+import { z } from "zod";
+import { defineTool } from "#public/tools/index.js";
+
+export default defineTool({
+ description: "Report the authenticated caller.",
+ inputSchema: z.object({}),
+ outputSchema: z.object({ principalId: z.string().nullable() }),
+ execute: (_input, ctx) => ({ principalId: ctx.session.auth.current?.principalId ?? null }),
+});
diff --git a/packages/eve/extension-contracts/reports/channel/v53.json b/packages/eve/extension-contracts/reports/channel/v53.json
new file mode 100644
index 000000000..9a7c65e0d
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/channel/v53.json
@@ -0,0 +1,21 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "channel",
+ "epoch": 53,
+ "sha256": "5f5793bad122121a5649392620cd1c9784b15479ed2e822516458206885c75f0",
+ "exports": [
+ "DELETE",
+ "GET",
+ "HEAD",
+ "OPTIONS",
+ "PATCH",
+ "POST",
+ "PUT",
+ "WS",
+ "createWebSocketUpgradeServer",
+ "defineChannel",
+ "disableRoute",
+ "isChannel",
+ "isDisabledRouteSentinel"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/connection/v42.json b/packages/eve/extension-contracts/reports/connection/v42.json
new file mode 100644
index 000000000..b6d58a027
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/connection/v42.json
@@ -0,0 +1,16 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "connection",
+ "epoch": 42,
+ "sha256": "b36043267e36b5b1209bf5ae220bfd3cefc98a24cc236c8c4f39e3cc821191dc",
+ "exports": [
+ "ConnectionAuthorizationFailedError",
+ "ConnectionAuthorizationRequiredError",
+ "defineDynamic",
+ "defineInteractiveAuthorization",
+ "defineMcpClientConnection",
+ "defineOpenAPIConnection",
+ "isConnectionAuthorizationFailedError",
+ "isConnectionAuthorizationRequiredError"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v74.json b/packages/eve/extension-contracts/reports/dynamicTool/v74.json
new file mode 100644
index 000000000..4c4e1334d
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicTool/v74.json
@@ -0,0 +1,16 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicTool",
+ "epoch": 74,
+ "sha256": "5c5a79089d9dd6bd14d198857da5f4e684bad9cce3fb03afbbb86ef1823278b6",
+ "exports": [
+ "DynamicToolEntry",
+ "DynamicToolEvents",
+ "DynamicToolResult",
+ "DynamicToolSet",
+ "auto",
+ "defineDurableCallback",
+ "defineDurableSchema",
+ "defineDynamic"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/hook/v40.json b/packages/eve/extension-contracts/reports/hook/v40.json
new file mode 100644
index 000000000..9f3d279d5
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/hook/v40.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "hook",
+ "epoch": 40,
+ "sha256": "86872f3e9cab38942f3523fc3e01309a9208606ec200020ae74f1ee28effc4ef",
+ "exports": ["defineHook"]
+}
diff --git a/packages/eve/extension-contracts/reports/state/v11.json b/packages/eve/extension-contracts/reports/state/v11.json
new file mode 100644
index 000000000..d38b3e806
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/state/v11.json
@@ -0,0 +1,15 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "state",
+ "epoch": 11,
+ "sha256": "f0a623750c1088976a18e068a7cc42f5dded5d4911f0393305672e664d494de6",
+ "exports": [
+ "Session",
+ "SessionAuth",
+ "SessionAuthContext",
+ "SessionContext",
+ "SessionParent",
+ "SessionTurn",
+ "defineState"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/tool/v79.json b/packages/eve/extension-contracts/reports/tool/v79.json
new file mode 100644
index 000000000..0fb07e3a5
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/tool/v79.json
@@ -0,0 +1,29 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "tool",
+ "epoch": 79,
+ "sha256": "3198ebe43299f84f4893859e95f1c4570aa029e2af60d5de0a67bcaf8ad2c616",
+ "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 3ef2df526..453129351 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -22,8 +22,8 @@ interface ExtensionCapabilityContract {
const EXTENSION_CAPABILITY_CONTRACTS = {
extension: { current: 1, supported: [1], dropped: {} },
tool: {
- current: 78,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 76, 77, 78],
+ current: 79,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 76, 77, 78, 79],
dropped: {
14: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
15: "TaskExec replaces stageEffect with send",
@@ -84,10 +84,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
dynamicTool: {
- current: 73,
+ current: 74,
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,
+ 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 72, 73, 74,
],
dropped: {
21: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
@@ -127,10 +127,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
channel: {
- current: 52,
+ current: 53,
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,
+ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
],
dropped: {
12: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
@@ -179,10 +179,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
connection: {
- current: 41,
+ current: 42,
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,
+ 35, 36, 37, 38, 39, 40, 41, 42,
],
dropped: {
9: "Dynamic connection resolvers no longer receive conversation or channel continuation data",
@@ -197,8 +197,8 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
hook: {
- current: 39,
- supported: [20, 21, 22, 23, 25, 27, 31, 32, 33, 34, 35, 36, 37, 38, 39],
+ current: 40,
+ supported: [20, 21, 22, 23, 25, 27, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
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.",
@@ -256,8 +256,8 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
config: { current: 1, supported: [1], dropped: {} },
state: {
- current: 10,
- supported: [1, 2, 3, 4, 5, 7, 9, 10],
+ current: 11,
+ supported: [1, 2, 3, 4, 5, 7, 9, 10, 11],
dropped: {
6: "Sandbox sessions no longer expose core identity and mutable networking is provider-specific.",
8: "SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities",
diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.ts
index 01e8d47b0..c2101807c 100644
--- a/packages/eve/src/context/keys.ts
+++ b/packages/eve/src/context/keys.ts
@@ -30,7 +30,7 @@ import type { HandleEventFn } from "#harness/types.js";
import type { PersistedDynamicToolMetadata } from "#context/dynamic-tool-metadata.js";
import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";
import type { DynamicRemoteAgentConfig } from "#runtime/subagents/dynamic-remote-agent-config.js";
-import type { SandboxAccess } from "#sandbox/state.js";
+import type { SandboxAccess, SandboxSessionEndReason } from "#sandbox/state.js";
import type { HistoryViewProjector } from "#shared/history-view.js";
import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";
import type { PreparedRuntimeDelegationTool } from "#runtime/sessions/turn.js";
@@ -169,6 +169,9 @@ export const LegacyRemoteAgentCallerKey = new ContextKey<LegacyRemoteAgentCaller
export const SessionKey = new ContextKey<Session>("eve.session");
export const SandboxKey = new ContextKey<SandboxAccess>("eve.sandbox");
+export const SandboxTerminalCleanupKey = new ContextKey<
+ (reason: SandboxSessionEndReason) => Promise<void>
+>("eve.internal.sandboxTerminalCleanup");
export const HandleEventKey = new ContextKey<HandleEventFn>("eve.internal.handleEvent");
// ---------------------------------------------------------------------------
diff --git a/packages/eve/src/context/providers/sandbox.test.ts b/packages/eve/src/context/providers/sandbox.test.ts
index 675601338..9930f5d9f 100644
--- a/packages/eve/src/context/providers/sandbox.test.ts
+++ b/packages/eve/src/context/providers/sandbox.test.ts
@@ -4,7 +4,7 @@ import { ensureSandboxAccess } from "#execution/sandbox/ensure.js";
import type { HarnessSession } from "#harness/types.js";
import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";
-import { SessionIdKey } from "#context/keys.js";
+import { SandboxTerminalCleanupKey, SessionIdKey } from "#context/keys.js";
import {
BundleKey,
ChannelKey,
@@ -60,6 +60,7 @@ describe("sandboxProvider", () => {
vi.mocked(ensureSandboxAccess).mockResolvedValue({
captureState: vi.fn().mockResolvedValue({ initialized: false, session: null }),
detach: vi.fn().mockResolvedValue(undefined),
+ end: vi.fn().mockResolvedValue(undefined),
get: vi.fn().mockResolvedValue(null),
stop: vi.fn().mockResolvedValue(undefined),
});
@@ -88,6 +89,27 @@ describe("sandboxProvider", () => {
);
});
+ it("exposes terminal cleanup through a framework-only context key", async () => {
+ const ctx = new ContextContainer();
+ const registry: RuntimeSandboxRegistry = createStubSandboxRegistry();
+ const end = vi.fn().mockResolvedValue(undefined);
+ vi.mocked(ensureSandboxAccess).mockResolvedValueOnce({
+ captureState: vi.fn().mockResolvedValue({ session: null }),
+ detach: vi.fn().mockResolvedValue(undefined),
+ end,
+ get: vi.fn().mockResolvedValue(null),
+ stop: vi.fn().mockResolvedValue(undefined),
+ });
+ ctx.set(BundleKey, createBundle({ agentName: "weather-agent", registry }));
+ ctx.set(ChannelKey, { kind: "slack" });
+ ctx.set(SessionIdKey, "session_1");
+
+ await sandboxProvider.create(ctx, createHarnessSession());
+ await ctx.require(SandboxTerminalCleanupKey)("expired");
+
+ expect(end).toHaveBeenCalledExactlyOnceWith("expired");
+ });
+
it("passes the owning session identity to sandbox access", async () => {
const ctx = new ContextContainer();
const registry: RuntimeSandboxRegistry = createStubSandboxRegistry();
diff --git a/packages/eve/src/context/providers/sandbox.ts b/packages/eve/src/context/providers/sandbox.ts
index 45cc047d7..65a5c8928 100644
--- a/packages/eve/src/context/providers/sandbox.ts
+++ b/packages/eve/src/context/providers/sandbox.ts
@@ -2,7 +2,7 @@ import { ensureSandboxAccess } from "#execution/sandbox/ensure.js";
import type { HarnessSessionBase } from "#harness/types.js";
import type { SandboxAccess, SandboxState } from "#sandbox/state.js";
import type { ContextContainer } from "#context/container.js";
-import { SandboxKey, SessionIdKey } from "#context/keys.js";
+import { SandboxKey, SandboxTerminalCleanupKey, SessionIdKey } from "#context/keys.js";
import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
import { getActiveRuntimeNode } from "#context/node.js";
import type { FrameworkContextProvider } from "#context/provider.js";
@@ -24,17 +24,16 @@ export const sandboxProvider: FrameworkContextProvider<SandboxAccess> = {
const reusesOwnerSandbox = inheritsParent || ownerSandboxSessionId !== undefined;
const sandboxSessionId = reusesOwnerSandbox ? (ownerSandboxSessionId ?? sessionId) : sessionId;
- return {
- value: await ensureSandboxAccess({
- compiledArtifactsSource: bundle.compiledArtifactsSource,
- nodeId: node.nodeId,
- ownsSandbox: !reusesOwnerSandbox,
- registry,
- sessionId: sandboxSessionId,
- state:
- session.sandboxState ?? (reusesOwnerSandbox ? parentSandboxState : undefined) ?? null,
- }),
- };
+ const access = await ensureSandboxAccess({
+ compiledArtifactsSource: bundle.compiledArtifactsSource,
+ nodeId: node.nodeId,
+ ownsSandbox: !reusesOwnerSandbox,
+ registry,
+ sessionId: sandboxSessionId,
+ state: session.sandboxState ?? (reusesOwnerSandbox ? parentSandboxState : undefined) ?? null,
+ });
+ ctx.setVirtualContext(SandboxTerminalCleanupKey, (reason) => access.end(reason));
+ return { value: access };
},
async commit(access, session) {
diff --git a/packages/eve/src/execution/sandbox/ensure.test.ts b/packages/eve/src/execution/sandbox/ensure.test.ts
index d4e23e729..bdea4a172 100644
--- a/packages/eve/src/execution/sandbox/ensure.test.ts
+++ b/packages/eve/src/execution/sandbox/ensure.test.ts
@@ -16,7 +16,7 @@ vi.mock("#runtime/sandbox/prepared-artifacts.js", () => ({
loadSandboxPreparedArtifact: vi.fn(async () => null),
}));
-function fixture(setup?: () => void, returnCopy = false) {
+function fixture(setup?: () => void, returnCopy = false, onSessionEnd?: () => Promise<void>) {
const deleteSandbox = vi.fn(async () => {});
const stopSandbox = vi.fn(async () => {});
const shutdownSandbox = vi.fn(async () => {});
@@ -32,11 +32,16 @@ function fixture(setup?: () => void, returnCopy = false) {
const start = vi.fn(async () => ({ handle: await create(), state: null }));
const provider = defineSandboxProvider({
name: "test",
- environment: () => ({
- prepare: async () => null,
- resume: create,
- start,
- }),
+ environment: () => {
+ const implementation = {
+ prepare: async () => null,
+ resume: create,
+ start,
+ };
+ return onSessionEnd === undefined
+ ? implementation
+ : Object.assign(implementation, { onSessionEnd });
+ },
});
const environment = provider.environment();
const selector = defineSandbox(async () => {
@@ -58,7 +63,15 @@ function fixture(setup?: () => void, returnCopy = false) {
workspaceResourceRoot: { logicalPath: "", rootEntries: [] },
},
};
- return { create, deleteSandbox, registry, shutdownSandbox, start, stopSandbox };
+ return {
+ create,
+ deleteSandbox,
+ onSessionEnd,
+ registry,
+ shutdownSandbox,
+ start,
+ stopSandbox,
+ };
}
async function open(
registry: RuntimeSandboxRegistry,
@@ -291,4 +304,67 @@ describe("ensureSandboxAccess", () => {
expect(value.deleteSandbox).toHaveBeenCalledOnce();
expect(value.create).toHaveBeenCalledTimes(2);
});
+
+ it("passes terminal cleanup to the provider from durable state", async () => {
+ const onSessionEnd = vi.fn(async () => {});
+ const value = fixture(undefined, false, onSessionEnd);
+ const { access } = await open(value.registry);
+
+ await access.end?.("expired");
+
+ expect(onSessionEnd).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ session: expect.objectContaining({ id: "session-1" }) }),
+ null,
+ null,
+ { 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);
+
+ await access.end?.("completed");
+
+ expect(value.deleteSandbox).toHaveBeenCalledOnce();
+ await expect(access.captureState()).resolves.toEqual({ session: null });
+ });
+
+ it("does not start a sandbox just to end a session that never opened one", async () => {
+ const value = fixture();
+ const access = await ensureSandboxAccess({
+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
+ nodeId: "__root__",
+ registry: value.registry,
+ sessionId: "unused",
+ state: null,
+ });
+
+ await access.end?.("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 access = await ensureSandboxAccess({
+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
+ nodeId: "__root__",
+ ownsSandbox: false,
+ registry: value.registry,
+ sessionId: "child",
+ state: {
+ session: { providerName: "test", state: null, stateProtocolVersion: 1 },
+ },
+ });
+
+ await access.end?.("completed");
+
+ expect(onSessionEnd).not.toHaveBeenCalled();
+ expect(value.create).not.toHaveBeenCalled();
+ });
});
diff --git a/packages/eve/src/execution/sandbox/ensure.ts b/packages/eve/src/execution/sandbox/ensure.ts
index aacfc91d7..925bd3506 100644
--- a/packages/eve/src/execution/sandbox/ensure.ts
+++ b/packages/eve/src/execution/sandbox/ensure.ts
@@ -17,7 +17,12 @@ import {
} from "#runtime/compiled-artifacts-source.js";
import { loadSandboxPreparedArtifact } from "#runtime/sandbox/prepared-artifacts.js";
import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";
-import type { SandboxAccess, SandboxSessionState, SandboxState } from "#sandbox/state.js";
+import type {
+ SandboxAccess,
+ SandboxSessionEndReason,
+ SandboxSessionState,
+ SandboxState,
+} from "#sandbox/state.js";
import {
getSandboxEnvironmentRuntime,
runWithSandboxConstructorRuntime,
@@ -44,6 +49,8 @@ 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. */
+ end(reason: SandboxSessionEndReason): Promise<void>;
/**
* Lets go of the handle this access opened, if any, without stopping or
* deleting the sandbox, and returns it so the caller can free what it
@@ -88,6 +95,7 @@ export async function ensureSandboxAccess(
async detach() {
return undefined;
},
+ async end() {},
async get() {
return null;
},
@@ -372,6 +380,66 @@ export async function ensureSandboxAccess(
requiring = undefined;
return current.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 (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.onSessionDelete();
+ } else {
+ const resumed = await provider.implementation.resume(context, artifact, persisted.state);
+ await resumed.onSessionDelete();
+ }
+ if (current !== undefined) {
+ untrackActiveSandboxHandle({
+ handle: current.handle,
+ providerName: current.providerName,
+ sessionId: input.sessionId,
+ });
+ }
+ opened = undefined;
+ opening = undefined;
+ persisted = null;
+ requiring = undefined;
+ },
async get() {
await requireHandle();
return opened?.sandbox ?? null;
diff --git a/packages/eve/src/execution/session/end-sandbox-step.ts b/packages/eve/src/execution/session/end-sandbox-step.ts
new file mode 100644
index 000000000..4de4cfb03
--- /dev/null
+++ b/packages/eve/src/execution/session/end-sandbox-step.ts
@@ -0,0 +1,45 @@
+import { SandboxTerminalCleanupKey } from "#context/keys.js";
+import { withContextScope } from "#context/run-step.js";
+import { deserializeContext } from "#context/serialize.js";
+import { readDurableSession, type DurableSessionState } from "#execution/durable-session-store.js";
+import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
+import { hydrateDurableSession } from "#execution/session.js";
+import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
+import { createLogger, logError } from "#internal/logging.js";
+import type { SandboxSessionEndReason } from "#sandbox/state.js";
+
+const log = createLogger("execution.session.finalization");
+
+export async function reportSessionSandboxCleanupFailureStep(input: {
+ readonly error: unknown;
+ readonly outcome: string;
+ readonly sessionId: string;
+}): Promise<void> {
+ "use step";
+
+ logError(log, "failed to clean up terminal session sandbox", input.error, {
+ outcome: input.outcome,
+ sessionId: input.sessionId,
+ });
+}
+
+export async function endSessionSandboxStep(input: {
+ readonly reason: SandboxSessionEndReason;
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+}): Promise<void> {
+ "use step";
+
+ const ctx = await deserializeContext(input.serializedContext);
+ const durable = readDurableSession(input.sessionState);
+ const effectiveAgent = resolveEffectiveAgentRuntime(ctx.require(BundleKey), ctx);
+ const session = hydrateDurableSession({
+ compactionOverrides: { thresholdPercent: effectiveAgent.thresholdPercent },
+ durable,
+ turnAgent: effectiveAgent.turnAgent,
+ });
+ await withContextScope(ctx, session, async (enrichedSession) => {
+ await ctx.get(SandboxTerminalCleanupKey)?.(input.reason);
+ return { result: undefined, session: enrichedSession };
+ });
+}
diff --git a/packages/eve/src/execution/session/finalization.test.ts b/packages/eve/src/execution/session/finalization.test.ts
index 604bef6e6..58b02ab26 100644
--- a/packages/eve/src/execution/session/finalization.test.ts
+++ b/packages/eve/src/execution/session/finalization.test.ts
@@ -8,10 +8,18 @@ import type { HarnessSession } from "#harness/types.js";
import { emitTerminalSessionCompletionStep } from "#execution/terminal-session-completion-step.js";
import { emitTerminalSessionFailureStep } from "#execution/terminal-session-failure-step.js";
import { notifyTurnCallerStep } from "#subagents/parent-notification.js";
+import {
+ endSessionSandboxStep,
+ reportSessionSandboxCleanupFailureStep,
+} from "#execution/session/end-sandbox-step.js";
vi.mock("#execution/terminate-child-sessions-step.js", () => ({
terminateChildSessionsStep: vi.fn(),
}));
+vi.mock("#execution/session/end-sandbox-step.js", () => ({
+ endSessionSandboxStep: vi.fn(),
+ reportSessionSandboxCleanupFailureStep: vi.fn(async () => {}),
+}));
vi.mock("#execution/terminal-session-completion-step.js", () => ({
emitTerminalSessionCompletionStep: vi.fn(),
}));
@@ -70,6 +78,50 @@ function sessionWithTaskRun() {
beforeEach(() => vi.clearAllMocks());
+describe("session finalization", () => {
+ it.each([
+ { outcome: { kind: "expired" as const }, reason: "expired" },
+ { outcome: { kind: "failed" as const, error: new Error("failed") }, reason: "failed" },
+ {
+ outcome: {
+ kind: "done" as const,
+ action: { kind: "done" as const, output: "done" },
+ },
+ reason: "completed",
+ },
+ ])("ends the sandbox when the session is $reason", async ({ outcome, reason }) => {
+ const sessionState = sessionWithUnreportedUsage();
+ await finalizeSession(outcome, {
+ caller: undefined,
+ cursor: { serializedContext: { key: "value" }, sessionState },
+ sessionWritable: new WritableStream(),
+ });
+
+ expect(endSessionSandboxStep).toHaveBeenCalledExactlyOnceWith({
+ reason,
+ serializedContext: { key: "value" },
+ sessionState,
+ });
+ });
+
+ it("preserves the terminal outcome when sandbox cleanup fails", async () => {
+ vi.mocked(endSessionSandboxStep).mockRejectedValueOnce(new Error("cleanup failed"));
+
+ await expect(
+ finalizeSession(
+ { kind: "expired" },
+ {
+ caller: undefined,
+ cursor: { serializedContext: {}, sessionState: sessionWithUnreportedUsage() },
+ sessionWritable: new WritableStream(),
+ },
+ ),
+ ).resolves.toMatchObject({ isError: false });
+ expect(reportSessionSandboxCleanupFailureStep).toHaveBeenCalledOnce();
+ expect(emitTerminalSessionCompletionStep).toHaveBeenCalledOnce();
+ });
+});
+
describe("session finalization with an unsettled caller", () => {
it.each([
{ kind: "expired" as const },
diff --git a/packages/eve/src/execution/session/finalization.ts b/packages/eve/src/execution/session/finalization.ts
index ca5b56726..eb19009ba 100644
--- a/packages/eve/src/execution/session/finalization.ts
+++ b/packages/eve/src/execution/session/finalization.ts
@@ -1,6 +1,10 @@
import type { TurnCaller } from "#channel/types.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
import { emitTerminalSessionCompletionStep } from "#execution/terminal-session-completion-step.js";
+import {
+ endSessionSandboxStep,
+ reportSessionSandboxCleanupFailureStep,
+} from "#execution/session/end-sandbox-step.js";
import { emitTerminalSessionFailureStep } from "#execution/terminal-session-failure-step.js";
import { terminateChildSessionsStep } from "#execution/terminate-child-sessions-step.js";
import { liveTaskRuns, readTaskTable } from "#execution/tasks/table.js";
@@ -43,6 +47,21 @@ export async function finalizeSession(
) {
await terminateChildSessionsStep({ sessionState });
}
+ if (sessionState !== undefined) {
+ try {
+ await endSessionSandboxStep({
+ reason: outcome.kind === "done" ? "completed" : outcome.kind,
+ serializedContext,
+ sessionState,
+ });
+ } catch (error) {
+ await reportSessionSandboxCleanupFailureStep({
+ error: normalizeSerializableError(error),
+ outcome: outcome.kind,
+ sessionId: sessionState.sessionId,
+ }).catch(() => undefined);
+ }
+ }
const session = sessionState?.snapshot.session;
const usage = session === undefined ? undefined : getSessionUsage(session);
if (outcome.kind === "expired") {
diff --git a/packages/eve/src/sandbox/state.ts b/packages/eve/src/sandbox/state.ts
index db9af96ef..a4226a0f5 100644
--- a/packages/eve/src/sandbox/state.ts
+++ b/packages/eve/src/sandbox/state.ts
@@ -2,6 +2,8 @@ import type { SandboxSession } from "#public/definitions/sandbox.js";
import type { SandboxEnvironmentIdentity } from "#shared/sandbox-environment.js";
import type { SandboxDeleteOptions, SandboxPreparedArtifact } from "#shared/sandbox-provider.js";
+export type SandboxSessionEndReason = "completed" | "expired" | "failed";
+
export interface SandboxSessionState {
readonly providerName: string;
readonly state: SandboxPreparedArtifact;
diff --git a/packages/eve/src/shared/sandbox-provider.ts b/packages/eve/src/shared/sandbox-provider.ts
index 20a5d77e1..403346cb3 100644
--- a/packages/eve/src/shared/sandbox-provider.ts
+++ b/packages/eve/src/shared/sandbox-provider.ts
@@ -134,6 +134,16 @@ export interface SandboxProviderImplementation<
SessionState,
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.
+ */
+ onSessionEnd?(
+ context: SandboxProviderSessionContext,
+ artifact: Readonly<PreparedArtifact>,
+ state: Readonly<SessionState>,
+ options: { readonly reason: "completed" | "expired" | "failed" },
+ ): Promise<void>;
prepare(context: SandboxProviderPrepareContext): Promise<PreparedArtifact>;
resume(
context: SandboxProviderSessionContext,