Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

refactor(sandbox)!: build the Vercel provider on the public provider API (#5274)

Andrew Barba950409f68769
diff --git a/.changeset/vercel-sandbox-public-provider.md b/.changeset/vercel-sandbox-public-provider.md
new file mode 100644
index 000000000..54350ad0d
--- /dev/null
+++ b/.changeset/vercel-sandbox-public-provider.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+`VercelSandbox` now runs on the public `defineSandboxProvider()` API, keeping existing sandbox names, session state, and snapshots. Breaking: a relative `workingDirectory` now resolves from `/workspace`, and `eve/sandbox/vercel` no longer re-exports `Drive`, so import it from `@vercel/sandbox` instead.
diff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.md
index cd1959f8f..826475ffb 100644
--- a/docs/reference/typescript-api.md
+++ b/docs/reference/typescript-api.md
@@ -145,7 +145,7 @@ Tool definitions accept `availableInSubagents: false` to restrict the tool to to
| `eve/sandbox` | `defineSandbox`, `defineParentSandbox`, `DefaultSandbox`, and sandbox session and network policy types |
| [`eve/sandbox/provider`](../sandbox/custom-providers) | `defineSandboxProvider`, provider errors, `SANDBOX_AGENT_ENV`, and connection and lifecycle types |
| [`eve/sandbox/docker`](../sandbox/docker) | `DockerSandbox` and Docker environment and session types |
-| [`eve/sandbox/vercel`](../sandbox/vercel) | `VercelSandbox`, `Drive`, and Vercel environment, session, and mount types |
+| [`eve/sandbox/vercel`](../sandbox/vercel) | `VercelSandbox` and Vercel environment, session, and mount types |
| [`eve/sandbox/just-bash`](../sandbox/just-bash) | `JustBashSandbox` and just-bash environment types |
| `eve/instrumentation` | `defineInstrumentation`, `disableInstrumentation`, `isChannel`, lifecycle provider types |
| `eve/instrumentation/otel` | `otel`, `otelIntegration`, `localTraces`, `agentRuns`, OpenTelemetry policy types |
diff --git a/docs/sandbox/custom-providers.mdx b/docs/sandbox/custom-providers.mdx
index e2bfd13c2..2c4e1370c 100644
--- a/docs/sandbox/custom-providers.mdx
+++ b/docs/sandbox/custom-providers.mdx
@@ -143,7 +143,7 @@ eve calls the lifecycle methods at these points:
| The eve server shuts down | `connection.stop()`, then `connection.close()`, on every open session connection; eve logs failures and does not throw them |
| The owning session reaches a terminal outcome | `connection.close()` on this process's connections for the session, then `onSessionEnd(ctx, state, { reason })` with `"completed"`, `"expired"`, or `"failed"` |
-eve calls `stop()` and `close()` at most once per connection, retrying only after a failure. A failed `close()` never prevents `onSessionEnd()` from deleting the sandbox.
+eve calls `close()` at most once per connection, retrying only after a failure. `stop()` can run again after the session uses a stopped connection, so make it a no-op when the sandbox is already stopped. A failed `close()` never prevents `onSessionEnd()` from deleting the sandbox.
### `prepare()`
diff --git a/docs/sandbox/vercel.mdx b/docs/sandbox/vercel.mdx
index e1d443a4e..45f696d18 100644
--- a/docs/sandbox/vercel.mdx
+++ b/docs/sandbox/vercel.mdx
@@ -53,7 +53,7 @@ Outside Vercel and without a linked project, such as in CI or on a self-hosted s
## Snapshot preparation
-eve creates a temporary persistent Vercel Sandbox during build, installs the base runtime, writes managed workspace and skill files, runs the authored `prepare` callback, and captures a snapshot. The build artifact records the snapshot ID.
+eve creates a temporary, non-persistent Vercel Sandbox during build, installs the base runtime, writes managed workspace and skill files, runs the authored `prepare` callback, and captures a snapshot. The build artifact records the snapshot ID.
When a live session sandbox does not exist, eve creates it directly from that snapshot ID. Runtime does not need to look up the temporary template Sandbox.
@@ -93,6 +93,8 @@ export default defineSandbox(async () => {
});
```
+Relative paths, including a relative `workingDirectory` passed to `run()` or `spawn()`, resolve from `/workspace`.
+
Use the environment's `prepare` callback for immutable setup that every new session should inherit. Use post-open initialization for state that belongs only to one durable session.
## Network policy
@@ -132,11 +134,16 @@ const sandboxName = sandbox.name;
## Mount a Drive
-A [Vercel Sandbox Drive](https://vercel.com/docs/sandbox/concepts/drives) stores files independently of a sandbox. Create or retrieve the Drive before calling `open()`, then pass it in `mounts` under an absolute path:
+A [Vercel Sandbox Drive](https://vercel.com/docs/sandbox/concepts/drives) stores files independently of a sandbox. Install `@vercel/sandbox` in your app, create or retrieve the Drive before calling `open()`, then pass it in `mounts` under an absolute path:
+
+```bash
+pnpm add @vercel/sandbox
+```
```ts
+import { Drive } from "@vercel/sandbox";
import { defineSandbox } from "eve/sandbox";
-import { Drive, VercelSandbox } from "eve/sandbox/vercel";
+import { VercelSandbox } from "eve/sandbox/vercel";
const REGION = "iad1";
@@ -156,6 +163,8 @@ export default defineSandbox(async () => {
});
```
+`Drive.getOrCreate()` comes from your app's own `@vercel/sandbox`, so it resolves credentials through the SDK, not eve: it reads `token`, `teamId`, and `projectId` passed to it, or a Vercel OIDC token, which the SDK refreshes from your Vercel CLI login and linked project. It does not read `VERCEL_TOKEN`, `VERCEL_TEAM_ID`, `VERCEL_PROJECT_ID`, or the credentials passed to `VercelSandbox.environment()`, so outside Vercel without a linked project, pass them to `Drive.getOrCreate()` too.
+
This example mounts the Drive read-write at `/data`. Files written there remain on the Drive after the sandbox stops. Keep Drive mounts separate from eve's managed `/workspace` directory.
Set the same region on the environment and the Drive. The environment region places the prepared snapshot and each session sandbox together with the Drive.
@@ -174,6 +183,8 @@ return environment.open({
Before mounting `drive.snapshot()`, seed a new Drive by mounting it read-write and writing at least one file. An uninitialized Drive cannot be mounted as a snapshot.
+Each `mounts` entry is a `Drive`, which mounts read-write, or a `{ drive, mode }` reference to an existing Drive by name, where `mode` is `"read-write"` or `"snapshot"`. `drive.snapshot()` returns such a reference.
+
Vercel allows up to four non-overlapping, absolute Drive mount paths per sandbox. See the Vercel documentation for [Drive lifecycle, limits, and pricing](https://vercel.com/docs/sandbox/concepts/drives).
## Live sandbox options
diff --git a/packages/eve/src/execution/sandbox/bindings/vercel-errors.ts b/packages/eve/src/execution/sandbox/bindings/vercel-errors.ts
index 1175fb0f9..18448bcc4 100644
--- a/packages/eve/src/execution/sandbox/bindings/vercel-errors.ts
+++ b/packages/eve/src/execution/sandbox/bindings/vercel-errors.ts
@@ -1,3 +1,5 @@
+import { isObject } from "#shared/guards.js";
+
export function isVercelSnapshotUnavailableError(error: unknown): boolean {
return errorChainContainsStatus(error, 410);
}
@@ -8,9 +10,9 @@ export function isVercelSnapshotUnavailableError(error: unknown): boolean {
*/
export function isVercelSnapshotNotFoundError(error: unknown): boolean {
for (const candidate of walkErrorChain(error)) {
- if (readErrorStatus(candidate) !== 410 || !isRecord(candidate)) continue;
+ if (readErrorStatus(candidate) !== 410 || !isObject(candidate)) continue;
const body =
- isRecord(candidate.json) && isRecord(candidate.json.error) ? candidate.json.error : undefined;
+ isObject(candidate.json) && isObject(candidate.json.error) ? candidate.json.error : undefined;
if (body?.code === "snapshot_not_found") return true;
}
return false;
@@ -37,11 +39,11 @@ export function isVercelSandboxNameConflictError(error: unknown): boolean {
// The API error's message, falling back to its parsed JSON body.
function readErrorText(value: unknown): string {
- if (!isRecord(value)) return "";
+ if (!isObject(value)) return "";
const parts: string[] = [];
if (typeof value.message === "string") parts.push(value.message);
if (typeof value.text === "string") parts.push(value.text);
- const body = isRecord(value.json) && isRecord(value.json.error) ? value.json.error : undefined;
+ const body = isObject(value.json) && isObject(value.json.error) ? value.json.error : undefined;
if (body !== undefined && typeof body.message === "string") parts.push(body.message);
return parts.join("\n");
}
@@ -58,10 +60,10 @@ function errorChainContainsStatus(error: unknown, expectedStatus: number): boole
}
function readErrorStatus(value: unknown): number | undefined {
- if (!isRecord(value)) return undefined;
+ if (!isObject(value)) return undefined;
if (typeof value.status === "number") return value.status;
if (typeof value.statusCode === "number") return value.statusCode;
- return isRecord(value.response) && typeof value.response.status === "number"
+ return isObject(value.response) && typeof value.response.status === "number"
? value.response.status
: undefined;
}
@@ -72,10 +74,6 @@ function* walkErrorChain(error: unknown): Generator<unknown> {
while (current !== undefined && current !== null && !seen.has(current)) {
seen.add(current);
yield current;
- current = isRecord(current) ? current.cause : undefined;
+ current = isObject(current) ? current.cause : undefined;
}
}
-
-function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
- return typeof value === "object" && value !== null;
-}
diff --git a/packages/eve/src/execution/sandbox/bindings/vercel-lifecycle.ts b/packages/eve/src/execution/sandbox/bindings/vercel-lifecycle.ts
index a5ddd4694..f93cb4cb9 100644
--- a/packages/eve/src/execution/sandbox/bindings/vercel-lifecycle.ts
+++ b/packages/eve/src/execution/sandbox/bindings/vercel-lifecycle.ts
@@ -10,64 +10,44 @@ import type {
VercelSandbox,
} from "#execution/sandbox/bindings/vercel-sdk-types.js";
-export async function deleteVercelSandbox(input: {
- readonly createOptions: VercelCreateOptions;
- readonly loadDeleteSandboxModule: () => Promise<VercelModule>;
- readonly sandbox: VercelSandbox;
- readonly signal?: AbortSignal;
-}): Promise<void> {
- await stopVercelSandbox(input.sandbox);
- await deleteVercelSandboxRecord(input);
-}
-
/** Deletes the sandbox with this name, if there is one. */
export async function deleteNamedVercelSandbox(input: {
readonly createOptions: VercelCreateOptions;
- readonly loadDeleteSandboxModule: () => Promise<VercelModule>;
+ readonly sandboxModule: VercelModule;
readonly sandboxName: string;
+ readonly signal?: AbortSignal;
}): Promise<void> {
const sandbox = await getNamedVercelSandbox({
- createOptions: input.createOptions,
- sandboxModule: await input.loadDeleteSandboxModule(),
+ createOptions:
+ input.signal === undefined
+ ? input.createOptions
+ : { ...input.createOptions, signal: input.signal },
+ sandboxModule: input.sandboxModule,
sandboxName: input.sandboxName,
});
if (sandbox === null) return;
try {
await stopVercelSandbox(sandbox);
- await sandbox.delete({ deleteOrphanSnapshots: true });
+ await sandbox.delete({ deleteOrphanSnapshots: true, signal: input.signal });
} catch (error) {
// Another cleanup attempt deleted it first.
if (!isVercelSandboxMissingError(error)) throw error;
}
}
+/** Deletes a sandbox that can no longer resume, without stopping it first. */
export async function deleteUnusableVercelSandbox(input: {
readonly createOptions: VercelCreateOptions;
- readonly loadDeleteSandboxModule: () => Promise<VercelModule>;
- readonly sandbox: VercelSandbox;
-}): Promise<void> {
- await deleteVercelSandboxRecord(input);
-}
-
-async function deleteVercelSandboxRecord(input: {
- readonly createOptions: VercelCreateOptions;
- readonly loadDeleteSandboxModule: () => Promise<VercelModule>;
- readonly sandbox: VercelSandbox;
- readonly signal?: AbortSignal;
+ readonly sandboxModule: VercelModule;
+ readonly sandboxName: string;
}): Promise<void> {
- const credentials = await resolveVercelSandboxCredentials(input.createOptions);
- const sandboxModule = await input.loadDeleteSandboxModule();
- const sandbox = await sandboxModule.Sandbox.get({
- ...credentials,
+ const sandbox = await input.sandboxModule.Sandbox.get({
+ ...(await resolveVercelSandboxCredentials(input.createOptions)),
fetch: getVercelSandboxFetch(input.createOptions),
- name: input.sandbox.name,
+ name: input.sandboxName,
resume: false,
- signal: input.signal,
- });
- await sandbox.delete({
- deleteOrphanSnapshots: true,
- signal: input.signal,
});
+ await sandbox.delete({ deleteOrphanSnapshots: true });
}
export async function stopVercelSandbox(sandbox: VercelSandbox): Promise<void> {
diff --git a/packages/eve/src/execution/sandbox/bindings/vercel.test.ts b/packages/eve/src/execution/sandbox/bindings/vercel.test.ts
index b9503c573..c93433c6f 100644
--- a/packages/eve/src/execution/sandbox/bindings/vercel.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/vercel.test.ts
@@ -4,8 +4,19 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";
import { VERCEL_EVE_SANDBOX_IMAGE } from "#execution/sandbox/bindings/eve-image.js";
-import { createVercelSandbox as createVercelImplementation } from "#execution/sandbox/bindings/vercel.js";
+import {
+ createVercelSandbox as createVercelImplementation,
+ type VercelSandboxPreparedArtifact,
+ type VercelSandboxSessionState,
+} from "#execution/sandbox/bindings/vercel.js";
import { createSandboxProviderHarness } from "#internal/testing/sandbox-provider-harness.js";
+import { defineSandboxProvider } from "#public/sandbox/provider.js";
+import type { VercelSandboxSession } from "#public/sandbox/vercel.js";
+import type { VercelSandboxRuntimeOptions } from "#public/sandbox/vercel-sandbox.js";
+import type { LegacySandboxProviderImplementation } from "#shared/sandbox-provider.js";
+import { VercelSandbox } from "#sandbox/providers/vercel.js";
+import { getSandboxEnvironmentRuntime } from "#shared/sandbox-environment.js";
+import { DefaultSandbox } from "#sandbox/providers/default.js";
// The credential fallback consults the developer's Vercel CLI auth and the
// repo's `.vercel` project link; on a linked, logged-in machine it would
@@ -16,6 +27,26 @@ vi.mock("#compiled/@vercel/oidc/index.js", () => ({
}),
}));
+// DefaultSandbox loads the SDK itself; route that load to a test's fake project.
+const sdk = vi.hoisted(() => ({
+ module: undefined as { Sandbox: object; Snapshot: object } | undefined,
+}));
+vi.mock("#compiled/@vercel/sandbox/index.js", () => ({
+ get Sandbox() {
+ return sdk.module?.Sandbox;
+ },
+ get Snapshot() {
+ return sdk.module?.Snapshot;
+ },
+}));
+
+// The default image is tagged with the installed eve version, and template
+// keys hash it, so pin it for the recorded keys below.
+vi.mock("#execution/sandbox/bindings/eve-image.js", async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ VERCEL_EVE_SANDBOX_IMAGE: "vcr.vercel.com/vercel/eve/base:golden",
+}));
+
function createMockCommandResult() {
return {
exitCode: 0,
@@ -208,14 +239,34 @@ async function templateKeyOf(build: (module: object) => Promise<unknown>): Promi
}
/** An environment with preparation, which Vercel captures in a template snapshot. */
-function createVercelSandbox(input: Parameters<typeof createVercelImplementation>[0] = {}) {
+type VercelTestInput = NonNullable<Parameters<typeof createVercelImplementation>[0]> & {
+ readonly prepare?: (sandbox: VercelSandboxSession) => Promise<void> | void;
+};
+
+/** The binding behind the public provider contract, as core runs it. */
+function vercelImplementation({ prepare, ...input }: VercelTestInput = {}) {
+ const provider = defineSandboxProvider({
+ name: "vercel",
+ environment: () => createVercelImplementation(input),
+ });
+ const environment = provider.environment(prepare === undefined ? {} : { prepare });
+ return getSandboxEnvironmentRuntime(environment)
+ .implementation as LegacySandboxProviderImplementation<
+ VercelSandboxRuntimeOptions,
+ VercelSandboxPreparedArtifact,
+ VercelSandboxSessionState,
+ VercelSandboxSession
+ >;
+}
+
+function createVercelSandbox(input: VercelTestInput = {}) {
return createSandboxProviderHarness(
- createVercelImplementation({ prepare: async () => {}, ...input }),
+ vercelImplementation({ prepare: async () => {}, ...input }),
{},
);
}
-function createTestVercelSandbox(input: Parameters<typeof createVercelImplementation>[0] = {}) {
+function createTestVercelSandbox(input: VercelTestInput = {}) {
return createVercelSandbox({
...input,
createSandbox: async ({ createOptions, sandboxModule }) =>
@@ -343,9 +394,7 @@ describe("createVercelSandbox", () => {
it("reuses template identity until authored source or resources change", async () => {
async function prepareName(input: {
- createOptions?: NonNullable<
- Parameters<typeof createVercelImplementation>[0]
- >["createOptions"];
+ createOptions?: VercelTestInput["createOptions"];
resourcesKey?: string;
sourceRevision: string;
}) {
@@ -380,6 +429,17 @@ describe("createVercelSandbox", () => {
expect(explicitImage).not.toBe(first);
});
+ it("reports a create option the template key cannot hash as a Vercel preparation failure", async () => {
+ const provider = createTestVercelSandbox({
+ createOptions: { resources: new Map() } as never,
+ loadSandboxModule: async () => createFakeVercelProvider().sandboxModule as never,
+ });
+
+ await expect(provider.prepare({ appRoot: "/tmp/test-app-root" })).rejects.toThrow(
+ /^Failed to prepare Vercel sandbox snapshot: ctx\.templateKey\(\) accepts only JSON values/,
+ );
+ });
+
it("uses an author-supplied image for fresh Vercel sandboxes", async () => {
const templateSandbox = createMockSandbox({ name: "template-key" });
const sandboxModule = {
@@ -517,16 +577,56 @@ describe("createVercelSandbox", () => {
);
});
+ it("splits the realpath arguments of a large batch across calls and still uploads once", async () => {
+ const { handle, sessionSandbox } = await createTestVercelSession();
+ vi.mocked(sessionSandbox.runCommand).mockReset();
+ vi.mocked(sessionSandbox.runCommand).mockImplementation(
+ async (command: { args?: readonly string[] }) => ({
+ ...createMockCommandResult(),
+ stdout: vi.fn().mockResolvedValue(
+ (command.args ?? [])
+ .slice(3)
+ .map((path) => `/real${path}\0`)
+ .join(""),
+ ),
+ }),
+ );
+ const paths = Array.from(
+ { length: 2_000 },
+ (_, index) => `/workspace/${"nested/".repeat(12)}file-${index}.txt`,
+ );
+
+ await handle.sandbox.writeFiles({
+ files: paths.map((path) => ({ content: Buffer.from(path), path })),
+ });
+
+ const calls = vi
+ .mocked(sessionSandbox.runCommand)
+ .mock.calls.map(([command]) => (command as { args: string[] }).args);
+ expect(calls.length).toBeGreaterThan(1);
+ for (const args of calls) {
+ expect(args.slice(0, 3)).toEqual(["-m", "-z", "--"]);
+ expect(Buffer.byteLength(args.join(" "))).toBeLessThan(100 * 1024);
+ }
+ expect(calls.flatMap((args) => args.slice(3))).toEqual(paths);
+ expect(sessionSandbox.writeFiles).toHaveBeenCalledOnce();
+ expect(sessionSandbox.writeFiles).toHaveBeenLastCalledWith(
+ paths.map((path) => ({ content: Buffer.from(path), path: `/real${path}` })),
+ { signal: undefined },
+ );
+ });
+
it("resolves and writes all seed paths to the sandbox filesystem in one batch", async () => {
const templateSandbox = createMockSandbox({ name: "template" });
const sessionSandbox = createMockSandbox({ name: "session" });
+ const runCommand = templateSandbox.runCommand.getMockImplementation()!;
vi.mocked(templateSandbox.runCommand).mockImplementation(
- async (options: { readonly detached?: boolean }) =>
+ async (options: { readonly args?: readonly string[]; cmd: string; detached?: boolean }) =>
options.detached === true
? (createMockDetachedCommand([
{ data: "/home/vercel-sandbox\n", stream: "stdout" },
]) as never)
- : createMockCommandResult(),
+ : await runCommand(options),
);
const { sandboxModule } = createFakeVercelProvider(templateSandbox, sessionSandbox);
@@ -629,15 +729,27 @@ describe("createVercelSandbox", () => {
expect(sessionArgs?.[0]).toMatchObject({ timeout: 30 * 60 * 1_000 });
});
- it("applies mounts passed directly to open", async () => {
+ it("mounts a Drive read-write by name and passes Drive references through", async () => {
+ // Like the SDK's `Drive`: a `name` getter, with its metadata in a `drive` field.
+ class Drive {
+ readonly drive = { id: "drv_team" };
+ get name() {
+ return "team-drive";
+ }
+ }
const sessionSandbox = createMockSandbox({ name: "session" });
const create = vi.fn().mockResolvedValue(sessionSandbox);
const provider = createSandboxProviderHarness(
- createVercelImplementation({
+ vercelImplementation({
loadSandboxModule: async () =>
({ Sandbox: { create, get: vi.fn().mockResolvedValue(null) } }) as never,
}),
- { mounts: { "/workspace/repos": { drive: "team-drive", mode: "read-write" } } },
+ {
+ mounts: {
+ "/data": new Drive(),
+ "/shared": { drive: "shared-drive", mode: "snapshot" },
+ },
+ },
);
await provider.openSession({
appRoot: "/tmp/test-app-root",
@@ -645,16 +757,166 @@ describe("createVercelSandbox", () => {
});
expect(create).toHaveBeenCalledWith(
expect.objectContaining({
- mounts: { "/workspace/repos": { drive: "team-drive", mode: "read-write" } },
+ mounts: {
+ "/data": { drive: "team-drive", mode: "read-write" },
+ "/shared": { drive: "shared-drive", mode: "snapshot" },
+ },
}),
);
});
+ /*
+ * Literal values recorded by earlier releases. Session state, sandbox names,
+ * and prepared snapshot IDs outlive deployments, and template keys name the
+ * pointers that later builds reuse, so these must never change.
+ */
+ describe("identity recorded by earlier releases", () => {
+ const appRoot = "/tmp/test-app-root";
+
+ it("names session sandboxes and records their state as before", async () => {
+ const fake = createFakeVercelProvider();
+ const provider = createTestVercelSandbox({
+ loadSandboxModule: async () => fake.sandboxModule as never,
+ });
+
+ const states = [];
+ for (const sessionId of ["session_golden", "tool_session_golden"]) {
+ const { state } = await provider.start({
+ appRoot,
+ prepared: { snapshotId: "snap_golden" },
+ sandboxName: sessionId,
+ });
+ states.push(state);
+ }
+
+ expect(states).toEqual([
+ { sandboxName: "eve-sbx-vercel-e87bbba07bceb2ae5b77ad771b299317", version: 3 },
+ { sandboxName: "eve-sbx-vercel-05f9b7e93088c2627297d73f2e7e04cb", version: 3 },
+ ]);
+ expect(getSandboxEnvironmentRuntime(VercelSandbox.environment())).toMatchObject({
+ providerName: "vercel",
+ stateProtocolVersion: 1,
+ });
+ });
+
+ it("records DefaultSandbox's Vercel artifact and state as before", async () => {
+ vi.stubEnv("VERCEL", "1");
+ vi.stubEnv("VERCEL_PROJECT_ID", "prj_golden");
+ vi.stubEnv("VERCEL_TEAM_ID", "team_golden");
+ vi.stubEnv("VERCEL_TOKEN", "token_golden");
+ const fake = createFakeVercelProvider();
+ sdk.module = fake.sandboxModule;
+ const provider = createSandboxProviderHarness(
+ getSandboxEnvironmentRuntime(DefaultSandbox.environment()).implementation,
+ undefined,
+ );
+
+ const artifact = await provider.prepare({ appRoot });
+ const session = await provider.start({ appRoot, sandboxName: "session_golden" });
+ const toolSession = await provider.start({ appRoot, sandboxName: "tool_session_golden" });
+
+ // An empty environment needs no snapshot.
+ expect(artifact).toEqual({ artifact: {}, provider: "vercel" });
+ expect([session.state, toolSession.state]).toEqual([
+ {
+ provider: "vercel",
+ state: { sandboxName: "eve-sbx-vercel-e87bbba07bceb2ae5b77ad771b299317", version: 3 },
+ stateProtocolVersion: 1,
+ },
+ {
+ provider: "vercel",
+ state: { sandboxName: "eve-sbx-vercel-05f9b7e93088c2627297d73f2e7e04cb", version: 3 },
+ stateProtocolVersion: 1,
+ },
+ ]);
+ expect(fake.sandboxModule.Sandbox.create).toHaveBeenLastCalledWith(
+ expect.objectContaining({ snapshotExpiration: 24 * 60 * 60 * 1000 }),
+ );
+ });
+
+ it("resumes state and a prepared snapshot recorded by an earlier release", async () => {
+ const sandboxName = "eve-sbx-vercel-e87bbba07bceb2ae5b77ad771b299317";
+ const fake = createFakeVercelProvider();
+ fake.seedTemplate(sandboxName, createMockSandbox({ name: sandboxName, status: "stopped" }));
+ const provider = createTestVercelSandbox({
+ loadSandboxModule: async () => fake.sandboxModule as never,
+ });
+ const prepared = { snapshotId: "snap_previous_release" };
+
+ const resumed = await provider.openSession({
+ appRoot,
+ existing: { sandboxName, version: 3 },
+ prepared,
+ sandboxName: "session_golden",
+ });
+ const started = await provider.start({ appRoot, prepared, sandboxName: "session_golden" });
+
+ expect(resumed.sandbox.name).toBe(sandboxName);
+ expect(started.state).toEqual({ sandboxName, version: 3 });
+ expect(fake.sandboxModule.Sandbox.create).not.toHaveBeenCalled();
+ });
+
+ it("derives template keys from create options, image, resources, and source revision as before", async () => {
+ const managedFiles = {
+ resourcesKey: "resources-golden",
+ skills: [{ content: "# Skill", relativePath: "golden/SKILL.md" }],
+ workspace: [{ content: "notes", relativePath: "notes.md" }],
+ };
+ const keyFor = (input: {
+ readonly createOptions?: VercelTestInput["createOptions"];
+ readonly managedFiles?: typeof managedFiles;
+ readonly sourceRevision?: string;
+ }) =>
+ templateKeyOf(async (sandboxModule) =>
+ createTestVercelSandbox({
+ createOptions: input.createOptions,
+ loadSandboxModule: async () => sandboxModule as never,
+ // Managed files alone need a snapshot; prepare is not part of the key.
+ prepare: input.managedFiles === undefined ? async () => {} : undefined,
+ }).prepare({
+ appRoot,
+ ...input.managedFiles,
+ sourceRevision: input.sourceRevision ?? "revision-golden",
+ }),
+ );
+ const options = {
+ env: { GOLDEN: "1" },
+ networkPolicy: "deny-all",
+ resources: { vcpus: 4 },
+ tags: { team: "golden" },
+ timeout: 600_000,
+ } as const;
+
+ const keys = {
+ defaults: await keyFor({}),
+ managedFiles: await keyFor({ managedFiles }),
+ image: await keyFor({ createOptions: { image: "registry.example/eve:golden" } }),
+ source: await keyFor({
+ createOptions: { source: { type: "git", url: "https://example.test/agent.git" } },
+ }),
+ options: await keyFor({ createOptions: options }),
+ credentials: await keyFor({
+ createOptions: { ...options, projectId: "prj_golden", teamId: "team_golden", token: "t" },
+ }),
+ sourceRevision: await keyFor({ sourceRevision: "revision-other" }),
+ };
+
+ expect(keys).toEqual({
+ defaults: "eve-sbx-tpl-vercel-1f6d699611395741504fc8a4b10df805",
+ managedFiles: "eve-sbx-tpl-vercel-82b4e1f8627add9d53d329878f5bb047",
+ image: "eve-sbx-tpl-vercel-1f48759fa1e48bb0d5af6910a423593a",
+ source: "eve-sbx-tpl-vercel-2f6b04f764532fa85e252b7c80bbfe56",
+ options: "eve-sbx-tpl-vercel-e7a2ead2a2bdd5be4fbbc9025a7cd05b",
+ credentials: "eve-sbx-tpl-vercel-e7a2ead2a2bdd5be4fbbc9025a7cd05b",
+ sourceRevision: "eve-sbx-tpl-vercel-d995fa0bea286a7b26343f99a4c5e0a1",
+ });
+ });
+ });
+
describe("session identity and cleanup", () => {
function session() {
const fake = createFakeVercelProvider();
const provider = createTestVercelSandbox({
- loadDeleteSandboxModule: async () => fake.sandboxModule as never,
loadSandboxModule: async () => fake.sandboxModule as never,
});
const start = (
@@ -723,7 +985,6 @@ describe("createVercelSandbox", () => {
},
};
const provider = createTestVercelSandbox({
- loadDeleteSandboxModule: async () => sandboxModule as never,
loadSandboxModule: async () => sandboxModule as never,
});
const open = async (sessionId = "tool_session_abc") =>
@@ -1163,12 +1424,12 @@ describe("createVercelSandbox", () => {
it("captures a template only when preparation, managed files, or an authored source need one", async () => {
const prepareWith = async (
- input: Parameters<typeof createVercelImplementation>[0],
+ input: VercelTestInput,
workspace: { content: string; relativePath: string }[] = [],
) => {
const create = vi.fn(async (options: { name: string }) => createMockSandbox(options));
const provider = createSandboxProviderHarness(
- createVercelImplementation({
+ vercelImplementation({
...input,
createSandbox: async ({ createOptions }) => (await create(createOptions)) as never,
loadSandboxModule: async () =>
@@ -1195,6 +1456,25 @@ describe("createVercelSandbox", () => {
}
});
+ it("gives prepare the build sandbox's name and network policy", async () => {
+ const fake = createFakeVercelProvider();
+ let name: string | undefined;
+ await createTestVercelSandbox({
+ loadSandboxModule: async () => fake.sandboxModule as never,
+ prepare: async (sandbox) => {
+ name = sandbox.name;
+ await sandbox.setNetworkPolicy("deny-all");
+ },
+ }).prepare({ appRoot: "/tmp/test-app-root" });
+
+ const build = (await fake.sandboxModule.Sandbox.create.mock.results[0]?.value) as ReturnType<
+ typeof createMockSandbox
+ >;
+ expect(name).toBe(build.name);
+ expect(name).toMatch(/^eve-sbx-tpl-vercel-[0-9a-f]{32}-[0-9a-f]{8}$/u);
+ expect(build.update).toHaveBeenCalledWith({ networkPolicy: "deny-all" });
+ });
+
it("reports an unavailable prepared snapshot without mutating the build template", async () => {
const snapshotExpiredError = Object.assign(
new Error("Vercel sandbox create API returned 410"),
@@ -1252,52 +1532,44 @@ 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: createSandboxesInOrder(templateSandbox, sessionSandbox),
- get: vi.fn().mockResolvedValue(null),
- },
- };
+ it("stops a Vercel session again after it resumes", async () => {
+ const { handle, sessionSandbox } = await createTestVercelSession();
+ vi.mocked(sessionSandbox.runCommand).mockResolvedValue(createMockDetachedCommand() as never);
+
+ await handle.onSandboxStop();
+ await handle.sandbox.run({ command: "printf resumed" });
+ await handle.onRuntimeShutdown();
+
+ expect(sessionSandbox.stop).toHaveBeenCalledTimes(2);
+ });
+
+ it("stops the sandbox and asks Vercel to delete orphan snapshots when deleting it", async () => {
+ const fake = createFakeVercelProvider();
const provider = createTestVercelSandbox({
- loadDeleteSandboxModule: async () => ({ Sandbox: { get: stableGet } }) as never,
- loadSandboxModule: async () => sandboxModule as never,
- });
- await provider.prepare({
- appRoot: "/tmp/test-app-root",
+ loadSandboxModule: async () => fake.sandboxModule as never,
});
const handle = await provider.openSession({
appRoot: "/tmp/test-app-root",
+ prepared: { snapshotId: "prepared-snapshot" },
sandboxName: "session-key",
});
+ const sandbox = fake.sandboxes.get(handle.sandbox.name)!;
const abortSignal = new AbortController().signal;
await expect(handle.onSandboxDelete({ 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({
+ expect(fake.sandboxModule.Sandbox.get).toHaveBeenLastCalledWith(
+ expect.objectContaining({ name: handle.sandbox.name, resume: false, signal: abortSignal }),
+ );
+ expect(sandbox.stop).toHaveBeenCalledTimes(1);
+ expect(sandbox.delete).toHaveBeenCalledWith({
deleteOrphanSnapshots: true,
signal: abortSignal,
});
+ expect(sandbox.stop.mock.invocationCallOrder[0]).toBeLessThan(
+ sandbox.delete.mock.invocationCallOrder[0]!,
+ );
+ expect(fake.sandboxes.size).toBe(0);
});
it("skips the stop call on shutdown when the sandbox is not running", async () => {
@@ -1339,7 +1611,7 @@ describe("createVercelSandbox", () => {
const sessionSandbox = createMockSandbox({ name: "session" });
const create = vi.fn().mockResolvedValue(sessionSandbox);
const provider = createSandboxProviderHarness(
- createVercelImplementation({
+ vercelImplementation({
createOptions: environment,
createSandbox: async ({ createOptions }) => {
await create(createOptions);
@@ -1364,14 +1636,12 @@ describe("createVercelSandbox", () => {
it("discards a fresh template-less session when applying its policy fails", async () => {
const sessionSandbox = createMockSandbox({ name: "session" });
sessionSandbox.update.mockRejectedValueOnce(new Error("policy rejected"));
- const stableDelete = vi.fn().mockResolvedValue(undefined);
+ const fake = createFakeVercelProvider(sessionSandbox);
const provider = createSandboxProviderHarness(
- createVercelImplementation({
- createSandbox: async () => sessionSandbox as never,
- loadDeleteSandboxModule: async () =>
- ({ Sandbox: { get: vi.fn().mockResolvedValue({ delete: stableDelete }) } }) as never,
- loadSandboxModule: async () =>
- ({ Sandbox: { get: vi.fn().mockResolvedValue(null) } }) as never,
+ vercelImplementation({
+ createSandbox: async ({ createOptions, sandboxModule }) =>
+ await sandboxModule.Sandbox.create(createOptions),
+ loadSandboxModule: async () => fake.sandboxModule as never,
}),
{ networkPolicy: "deny-all" },
{ preparedArtifact: () => ({}) },
@@ -1381,7 +1651,8 @@ describe("createVercelSandbox", () => {
provider.start({ appRoot: "/tmp/test-app-root", sandboxName: "session-key" }),
).rejects.toThrow("policy rejected");
expect(sessionSandbox.stop).toHaveBeenCalledTimes(1);
- expect(stableDelete).toHaveBeenCalledTimes(1);
+ expect(sessionSandbox.delete).toHaveBeenCalledTimes(1);
+ expect(fake.sandboxes.size).toBe(0);
});
it("brokers credentials through the session's setNetworkPolicy to sandbox.update", async () => {
@@ -1427,35 +1698,20 @@ describe("createVercelSandbox", () => {
});
});
- it("exposes /workspace-rooted resolved paths through the public session", async () => {
- const templateSandbox = createMockSandbox({ name: "template" });
- const sessionSandbox = createMockSandbox({ name: "session" });
- const sandboxModule = {
- Sandbox: {
- create: createSandboxesInOrder(templateSandbox, sessionSandbox),
- get: vi.fn().mockResolvedValue(null),
- },
- };
-
- const provider = createTestVercelSandbox({
- loadSandboxModule: async () => sandboxModule as never,
- });
-
- await provider.prepare({
- appRoot: "/tmp/test-app-root",
- });
+ it("runs commands in a working directory resolved from /workspace", async () => {
+ const { handle, sessionSandbox } = await createTestVercelSession();
+ vi.mocked(sessionSandbox.runCommand).mockResolvedValue(createMockDetachedCommand() as never);
+ vi.mocked(sessionSandbox.runCommand).mockClear();
- const handle = await provider.openSession({
- appRoot: "/tmp/test-app-root",
- sandboxName: "session-key",
- });
+ await handle.sandbox.run({ command: "pwd", workingDirectory: "python-analysis" });
+ await handle.sandbox.run({ command: "pwd", workingDirectory: "/tmp" });
+ await handle.sandbox.run({ command: "pwd" });
- expect(handle.sandbox.resolvePath("/workspace/python-analysis/run.py")).toBe(
- "/workspace/python-analysis/run.py",
- );
- expect(handle.sandbox.resolvePath("python-analysis/run.py")).toBe(
- "/workspace/python-analysis/run.py",
- );
+ expect(sessionSandbox.runCommand.mock.calls.map(([options]) => options.cwd)).toEqual([
+ "/workspace/python-analysis",
+ "/tmp",
+ "/workspace",
+ ]);
});
it("converts Vercel Node file streams to the public Web stream contract", async () => {
diff --git a/packages/eve/src/execution/sandbox/bindings/vercel.ts b/packages/eve/src/execution/sandbox/bindings/vercel.ts
index 5e7f642c6..2f6d6bdb2 100644
--- a/packages/eve/src/execution/sandbox/bindings/vercel.ts
+++ b/packages/eve/src/execution/sandbox/bindings/vercel.ts
@@ -1,84 +1,72 @@
import { randomBytes } from "node:crypto";
-import type { VercelSandboxSession } from "#public/sandbox/vercel.js";
-import { VERCEL_EVE_SANDBOX_IMAGE } from "#execution/sandbox/bindings/eve-image.js";
-import {
- applyInitialVercelNetworkPolicy,
- createVercelNetworkPolicySetter,
- ensureVercelSandboxBaseRuntime,
- withBaseSetupNetworkPolicy,
-} from "#execution/sandbox/bindings/vercel-base-runtime.js";
import type {
- InternalSandboxSession,
SandboxProcess,
- SandboxReadFileOptions,
SandboxRemovePathOptions,
- SandboxSession,
- SandboxSpawnOptions,
- SandboxWriteFileOptions,
SandboxWriteFilesOptions,
-} from "#shared/sandbox-session.js";
-import {
- isSandboxPreparedArtifactRecord,
- sandboxProviderResourceIdentity,
- providerResourceTargetFiles,
- type SandboxPreparedArtifact,
- type SandboxProviderHandle,
- type LegacySandboxProviderImplementation,
- type SandboxProviderSessionContext,
-} from "#shared/sandbox-provider.js";
-import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";
+} from "#public/sandbox/index.js";
import {
- invalidPreparedSandboxArtifactError,
- invalidSandboxSessionStateError,
-} from "#shared/sandbox-recorded-data-error.js";
-import { SandboxSessionGoneError } from "#shared/sandbox-session-gone-error.js";
+ SANDBOX_AGENT_ENV,
+ SandboxSessionGoneError,
+ SandboxTemplateNotProvisionedError,
+ type SandboxConnection,
+ type SandboxJson,
+ type SandboxPrepareContext,
+ type SandboxProviderImplementation,
+ type SandboxSessionContext,
+} from "#public/sandbox/provider.js";
import type {
- VercelSandboxMountOptions,
+ VercelSandboxMountMode,
+ VercelSandboxMounts,
VercelSandboxRuntimeOptions,
} from "#public/sandbox/vercel-sandbox.js";
-import { WORKSPACE_ROOT } from "#runtime/workspace/types.js";
-import { createLoggingSandboxSession } from "#execution/sandbox/logging-session.js";
-import { adaptMultiplexedCommandToSandboxProcess } from "#execution/sandbox/multiplexed-command.js";
-import { buildSandboxSession, SANDBOX_AGENT_ENV } from "#execution/sandbox/session.js";
-import { createSandboxProviderIdentity } from "#execution/sandbox/provider-identity.js";
-import { streamToBuffer } from "#execution/sandbox/stream-utils.js";
+import type { VercelSandboxSession } from "#public/sandbox/vercel.js";
+import { VERCEL_EVE_SANDBOX_IMAGE } from "#execution/sandbox/bindings/eve-image.js";
+import {
+ applyInitialVercelNetworkPolicy,
+ createVercelNetworkPolicySetter,
+ ensureVercelSandboxBaseRuntime,
+ withBaseSetupNetworkPolicy,
+} from "#execution/sandbox/bindings/vercel-base-runtime.js";
import {
createVercelEveImageSandbox,
type CreateVercelSandbox,
type VercelSandboxCreateParams,
} from "#execution/sandbox/bindings/vercel-create-sdk.js";
-import {
- errorMessage,
- ensureVercelSandboxTags,
- resolveVercelSandboxTags,
-} from "#execution/sandbox/bindings/vercel-options.js";
import {
isVercelSandboxMissingError,
isVercelSandboxNameConflictError,
isVercelSnapshotNotFoundError,
isVercelSnapshotUnavailableError,
} from "#execution/sandbox/bindings/vercel-errors.js";
-import { withToolSessionRetention } from "#execution/sandbox/bindings/vercel-tool-sessions.js";
-import { isToolSessionId } from "#execution/tool-session/id.js";
-import { withToolSessionSandboxes } from "#execution/tool-session/sandbox.js";
-import {
- getNamedVercelSandbox,
- isVercelSnapshotCreated,
-} from "#execution/sandbox/bindings/vercel-lookup.js";
import {
deleteNamedVercelSandbox,
deleteUnusableVercelSandbox,
- deleteVercelSandbox,
stopVercelSandbox,
} from "#execution/sandbox/bindings/vercel-lifecycle.js";
+import {
+ getNamedVercelSandbox,
+ isVercelSnapshotCreated,
+} from "#execution/sandbox/bindings/vercel-lookup.js";
+import {
+ errorMessage,
+ ensureVercelSandboxTags,
+ resolveVercelSandboxTags,
+} from "#execution/sandbox/bindings/vercel-options.js";
import { normalizeVercelReadStream } from "#execution/sandbox/bindings/vercel-read-stream.js";
-import { resolveSandboxModelPath } from "#shared/skill-paths.js";
import type {
VercelCreateOptions,
VercelModule,
VercelSandbox,
} from "#execution/sandbox/bindings/vercel-sdk-types.js";
+import { withToolSessionRetention } from "#execution/sandbox/bindings/vercel-tool-sessions.js";
+import { adaptMultiplexedCommandToSandboxProcess } from "#execution/sandbox/multiplexed-command.js";
+import { createSandboxProviderIdentity } from "#execution/sandbox/provider-identity.js";
+import { isObject } from "#shared/guards.js";
+import {
+ invalidPreparedSandboxArtifactError,
+ invalidSandboxSessionStateError,
+} from "#shared/sandbox-recorded-data-error.js";
export type VercelSandboxPreparedArtifact = {
readonly snapshotId?: string;
@@ -89,43 +77,25 @@ export type VercelSandboxSessionState = {
readonly version: 3;
};
-type VercelEnvironmentOptions = VercelCreateOptions & {
- readonly prepare?: (sandbox: SandboxSession) => Promise<void> | void;
-};
-
-export function createVercelSandboxProvider(
- environmentOptions: Readonly<VercelEnvironmentOptions> | undefined,
-): LegacySandboxProviderImplementation<
- VercelSandboxRuntimeOptions,
- VercelSandboxPreparedArtifact,
- VercelSandboxSessionState,
- VercelSandboxSession
-> {
- const { prepare, ...authoredCreateOptions } = environmentOptions ?? {};
- return createVercelSandbox({ createOptions: authoredCreateOptions, prepare });
-}
+/** Capabilities a Vercel connection adds to the session. */
+export type VercelSandboxExtensions = Pick<VercelSandboxSession, "name" | "setNetworkPolicy">;
interface CreateVercelSandboxInput {
readonly createSandbox?: CreateVercelSandbox;
readonly createOptions?: VercelCreateOptions;
- readonly loadDeleteSandboxModule?: () => Promise<VercelModule>;
readonly loadSandboxModule?: () => Promise<VercelModule>;
- readonly prepare?: (sandbox: SandboxSession) => Promise<void> | void;
}
export function createVercelSandbox(
input: CreateVercelSandboxInput = {},
-): LegacySandboxProviderImplementation<
+): SandboxProviderImplementation<
VercelSandboxRuntimeOptions,
VercelSandboxPreparedArtifact,
VercelSandboxSessionState,
- VercelSandboxSession
+ VercelSandboxExtensions
> {
const loadSandboxModule =
input.loadSandboxModule ?? (async () => await import("#compiled/@vercel/sandbox/index.js"));
- const loadDeleteSandboxModule =
- input.loadDeleteSandboxModule ??
- (async () => await import("#compiled/@vercel/sandbox/index.js"));
const createOptions: ResolvedVercelCreateOptions = {
...input.createOptions,
env: { ...SANDBOX_AGENT_ENV, ...input.createOptions?.env },
@@ -133,15 +103,80 @@ export function createVercelSandbox(
};
const createSandbox = input.createSandbox ?? createVercelEveImageSandbox;
+ return {
+ async onSessionEnd(context, state, { abortSignal }) {
+ await deleteNamedVercelSandbox({
+ createOptions,
+ sandboxModule: await loadSandboxModule(),
+ sandboxName: state?.sandboxName ?? vercelSessionName(context.session.id),
+ signal: abortSignal,
+ });
+ },
+ async prepare(context) {
+ // Without inputs a snapshot only repeats the base setup every session
+ // runs anyway. An authored `source` keeps one, so sessions start from
+ // the build's capture instead of fetching the source again.
+ if (context.isEmpty && createOptions.source === undefined) return {};
+ try {
+ const templateKey = `eve-sbx-tpl-vercel-${context
+ .templateKey({
+ createOptions: vercelIdentityOptions(createOptions),
+ resolvedImage:
+ createOptions.source === undefined
+ ? (createOptions.image ?? VERCEL_EVE_SANDBOX_IMAGE)
+ : undefined,
+ version: 3,
+ })
+ .slice(0, 32)}`;
+ const snapshotId = await ensureTemplate({
+ context,
+ createOptions,
+ createSandbox,
+ loadSandboxModule,
+ templateKey,
+ });
+ return { snapshotId };
+ } catch (error) {
+ throw new Error(`Failed to prepare Vercel sandbox snapshot: ${errorMessage(error)}`, {
+ cause: error,
+ });
+ }
+ },
+ async resume(_context, artifact, stateValue) {
+ requirePreparedVercelTemplate(artifact);
+ const state = requireVercelSessionState(stateValue);
+ const sandboxModule = await loadSandboxModule();
+ const sandbox = await getNamedVercelSandbox({
+ createOptions,
+ sandboxModule,
+ sandboxName: state.sandboxName,
+ });
+ if (sandbox === null) {
+ throw new SandboxSessionGoneError(
+ `Vercel sandbox session "${state.sandboxName}" no longer exists.`,
+ );
+ }
+ await ensureVercelSandboxBaseRuntime(sandbox);
+ return createVercelConnection(sandbox);
+ },
+ async start(context, options, artifact) {
+ const sandboxName = vercelSessionName(context.session.id);
+ const sandbox = await openSession(context, options, artifact, sandboxName);
+ return { connection: createVercelConnection(sandbox), state: { sandboxName, version: 3 } };
+ },
+ // Saved filesystems expire, so a keyed tool session's sandbox is bounded.
+ toolSessions: true,
+ };
+
async function openSession(
- context: SandboxProviderSessionContext,
+ context: SandboxSessionContext,
options: Readonly<VercelSandboxRuntimeOptions> | undefined,
- artifactValue: SandboxPreparedArtifact,
+ artifactValue: SandboxJson,
sandboxName: string,
- ) {
+ ): Promise<VercelSandbox> {
const artifact = requirePreparedVercelTemplate(artifactValue);
const { mounts, ...runtimeOptions } = options ?? {};
- const toolSession = isToolSessionId(context.session.id);
+ const toolSession = context.kind === "tool-session";
const authoredCreateOptions = {
...createOptions,
...runtimeOptions,
@@ -157,21 +192,18 @@ export function createVercelSandbox(
const ensureSessionInput: EnsureSessionInput = {
createOptions: sessionCreateOptions,
createSandbox,
- resolveSessionCreateOptions: mounts === undefined ? undefined : async () => ({ mounts }),
+ mounts: mounts === undefined ? undefined : toVercelMounts(mounts),
sandboxModule,
sessionKey: sandboxName,
snapshotId: artifact.snapshotId,
tags,
};
- let session: VercelSandboxSessionCreateResult;
try {
- session = await ensureSession(ensureSessionInput);
- session = await ensureUsableSession({
+ const session = await ensureUsableSession({
// Only an expired snapshot gives a tool session a fresh sandbox.
expired: toolSession ? isVercelSnapshotNotFoundError : isVercelSnapshotUnavailableError,
input: ensureSessionInput,
- loadDeleteSandboxModule,
- session,
+ session: await ensureSession(ensureSessionInput),
});
// Template-less sessions run base setup with open egress, so the policy
// from open() or else the environment applies only once it finishes.
@@ -181,10 +213,10 @@ export function createVercelSandbox(
await applyInitialVercelNetworkPolicy(session.sandbox, networkPolicy);
} catch (error) {
try {
- await deleteVercelSandbox({
+ await deleteNamedVercelSandbox({
createOptions: sessionCreateOptions,
- loadDeleteSandboxModule,
- sandbox: session.sandbox,
+ sandboxModule,
+ sandboxName: session.sandbox.name,
});
} catch (cleanupError) {
throw new AggregateError(
@@ -196,6 +228,7 @@ export function createVercelSandbox(
throw error;
}
}
+ return session.sandbox;
} catch (error) {
if (isVercelSnapshotUnavailableError(error) && artifact.snapshotId !== undefined) {
throw new SandboxTemplateNotProvisionedError({
@@ -209,89 +242,7 @@ export function createVercelSandbox(
{ cause: error },
);
}
- const handle = createHandle({
- createOptions: sessionCreateOptions,
- loadDeleteSandboxModule,
- sandbox: session.sandbox,
- });
- return handle;
}
-
- const implementation: ReturnType<typeof createVercelSandbox> = {
- async onSessionEnd(context, state) {
- await deleteNamedVercelSandbox({
- createOptions,
- loadDeleteSandboxModule,
- sandboxName: state?.sandboxName ?? vercelSessionName(context.session.id),
- });
- },
- async prepare(context) {
- const seedFiles = providerResourceTargetFiles(context.resources);
- // Without inputs a snapshot only repeats the base setup every session
- // runs anyway. An authored `source` keeps one, so sessions start from
- // the build's capture instead of fetching the source again.
- if (
- input.prepare === undefined &&
- seedFiles.length === 0 &&
- createOptions.source === undefined
- )
- return {};
- const templateKey = `eve-sbx-tpl-vercel-${createSandboxProviderIdentity({
- createOptions: vercelIdentityOptions(createOptions),
- resolvedImage:
- createOptions.source === undefined
- ? (createOptions.image ?? VERCEL_EVE_SANDBOX_IMAGE)
- : undefined,
- resources: sandboxProviderResourceIdentity(context.resources),
- sourceRevision: context.sourceRevision,
- version: 3,
- }).slice(0, 32)}`;
- try {
- const snapshotId = await ensureTemplate({
- createOptions,
- createSandbox,
- loadSandboxModule,
- log: context.log,
- prepareSandbox: input.prepare,
- seedFiles,
- templateKey,
- });
- return { snapshotId };
- } catch (error) {
- throw new Error(`Failed to prepare Vercel sandbox snapshot: ${errorMessage(error)}`, {
- cause: error,
- });
- }
- },
- async resume(_context, artifact, stateValue) {
- requirePreparedVercelTemplate(artifact);
- const state = requireVercelSessionState(stateValue);
- const sandboxModule = await loadSandboxModule();
- const sandbox = await getNamedVercelSandbox({
- createOptions,
- sandboxModule,
- sandboxName: state.sandboxName,
- });
- if (sandbox === null) {
- throw new SandboxSessionGoneError(
- `Vercel sandbox session "${state.sandboxName}" no longer exists.`,
- );
- }
- await ensureVercelSandboxBaseRuntime(sandbox);
- return createHandle({ createOptions, loadDeleteSandboxModule, sandbox });
- },
- async start(context, options, artifact) {
- const sandboxName = vercelSessionName(context.session.id);
- const handle = await openSession(context, options, artifact, sandboxName);
- return {
- handle,
- state: { sandboxName, version: 3 },
- };
- },
- };
- // Saved filesystems expire, so a keyed tool session's sandbox is bounded.
- // A handle is only an SDK client, so a call that ends has nothing to free.
- return withToolSessionSandboxes(implementation);
}
/**
@@ -309,22 +260,16 @@ function vercelIdentityOptions(options: object | undefined): object | undefined
return Object.fromEntries(Object.entries(options).filter(([key]) => !excluded.has(key)));
}
-function requireVercelSessionState(state: SandboxPreparedArtifact): VercelSandboxSessionState {
- if (
- !isSandboxPreparedArtifactRecord(state) ||
- state.version !== 3 ||
- typeof state.sandboxName !== "string"
- ) {
+function requireVercelSessionState(state: SandboxJson): VercelSandboxSessionState {
+ if (!isObject(state) || state.version !== 3 || typeof state.sandboxName !== "string") {
throw invalidSandboxSessionStateError("Vercel sandbox");
}
return { sandboxName: state.sandboxName, version: 3 };
}
-function requirePreparedVercelTemplate(
- artifact: SandboxPreparedArtifact,
-): VercelSandboxPreparedArtifact {
+function requirePreparedVercelTemplate(artifact: SandboxJson): VercelSandboxPreparedArtifact {
if (
- !isSandboxPreparedArtifactRecord(artifact) ||
+ !isObject(artifact) ||
(artifact.snapshotId !== undefined && typeof artifact.snapshotId !== "string")
) {
throw invalidPreparedSandboxArtifactError("Vercel sandbox");
@@ -332,18 +277,32 @@ function requirePreparedVercelTemplate(
return artifact.snapshotId === undefined ? {} : { snapshotId: artifact.snapshotId };
}
-type VercelSeedFile = { readonly content: string | Uint8Array; readonly path: string };
+/**
+ * eve's mounts in the SDK's `{ drive, mode }` form. A `Drive` mounts
+ * read-write by name, as the SDK does, so a `Drive` from the app's own
+ * `@vercel/sandbox` install works too.
+ */
+function toVercelMounts(
+ mounts: VercelSandboxMounts,
+): Record<string, { readonly drive: string; readonly mode: VercelSandboxMountMode }> {
+ return Object.fromEntries(
+ Object.entries(mounts).map(([path, mount]) => [
+ path,
+ "mode" in mount
+ ? { drive: mount.drive, mode: mount.mode }
+ : { drive: mount.name, mode: "read-write" },
+ ]),
+ );
+}
/** Create options with the default sandbox timeout applied once. */
type ResolvedVercelCreateOptions = VercelCreateOptions & { readonly timeout: number };
interface EnsureTemplateInput {
- readonly prepareSandbox?: (sandbox: SandboxSession) => void | Promise<void>;
+ readonly context: SandboxPrepareContext;
readonly createOptions: ResolvedVercelCreateOptions;
readonly createSandbox: CreateVercelSandbox;
readonly loadSandboxModule: () => Promise<VercelModule>;
- readonly log?: (message: string) => void;
- readonly seedFiles: ReadonlyArray<VercelSeedFile>;
readonly templateKey: string;
}
@@ -371,7 +330,7 @@ async function ensureTemplate(input: EnsureTemplateInput): Promise<string> {
snapshotId: publishedSnapshotId,
}))
) {
- input.log?.("reusing prepared sandbox template");
+ input.context.log("reusing prepared sandbox template");
return publishedSnapshotId;
}
@@ -383,7 +342,7 @@ async function ensureTemplate(input: EnsureTemplateInput): Promise<string> {
*/
await publishTemplatePointer(input, sandboxModule, pointer, snapshotId).catch(
(error: unknown) => {
- input.log?.(`could not publish sandbox template: ${errorMessage(error)}`);
+ input.context.log(`could not publish sandbox template: ${errorMessage(error)}`);
},
);
return snapshotId;
@@ -408,26 +367,10 @@ async function prepareTemplateSnapshot(
}),
});
try {
- input.log?.("preparing base runtime inside sandbox");
+ input.context.log("preparing base runtime inside sandbox");
await ensureVercelSandboxBaseRuntime(sandbox);
await applyInitialVercelNetworkPolicy(sandbox, input.createOptions.networkPolicy);
-
- const templateSession = buildSandboxSession(
- createVercelInternalSandboxSession(sandbox),
- createVercelNetworkPolicySetter(sandbox),
- );
-
- await writeVercelSandboxSeedFiles({
- sandbox,
- seedFiles: input.seedFiles,
- session: templateSession,
- });
-
- input.log?.("running sandbox preparation");
- await input.prepareSandbox?.(
- createLoggingSandboxSession({ log: input.log, session: templateSession }),
- );
-
+ await input.context.populate(createVercelConnection(sandbox));
// The returned snapshot, not the handle's cached `currentSnapshotId`, which the SDK may not refresh.
return (await sandbox.snapshot()).snapshotId;
} finally {
@@ -437,7 +380,7 @@ async function prepareTemplateSnapshot(
* it's not persistent, and no other build looks it up.
*/
await sandbox.delete().catch((error: unknown) => {
- input.log?.(`could not delete sandbox ${sandbox.name}: ${errorMessage(error)}`);
+ input.context.log(`could not delete sandbox ${sandbox.name}: ${errorMessage(error)}`);
});
}
}
@@ -489,9 +432,7 @@ async function publishTemplatePointer(
interface EnsureSessionInput {
readonly createOptions: VercelCreateOptions;
readonly createSandbox: CreateVercelSandbox;
- readonly resolveSessionCreateOptions?: () =>
- | Promise<VercelSandboxMountOptions>
- | VercelSandboxMountOptions;
+ readonly mounts?: ReturnType<typeof toVercelMounts>;
readonly sandboxModule: VercelModule;
readonly sessionKey: string;
readonly snapshotId?: string;
@@ -506,7 +447,6 @@ interface VercelSandboxSessionCreateResult {
async function ensureUsableSession(input: {
readonly expired: (error: unknown) => boolean;
readonly input: EnsureSessionInput;
- readonly loadDeleteSandboxModule: () => Promise<VercelModule>;
readonly session: VercelSandboxSessionCreateResult;
}): Promise<VercelSandboxSessionCreateResult> {
try {
@@ -521,8 +461,8 @@ async function ensureUsableSession(input: {
try {
await deleteUnusableVercelSandbox({
createOptions: input.input.createOptions,
- loadDeleteSandboxModule: input.loadDeleteSandboxModule,
- sandbox: input.session.sandbox,
+ sandboxModule: input.input.sandboxModule,
+ sandboxName: input.session.sandbox.name,
});
} catch (error) {
// Another instance that saw the same expiry deleted it first.
@@ -546,8 +486,7 @@ async function ensureSession(input: EnsureSessionInput): Promise<VercelSandboxSe
return { created: false, sandbox: existing };
}
- const sessionCreateOptions = await input.resolveSessionCreateOptions?.();
- const createParams = createSessionCreateParams(input, sandboxName, sessionCreateOptions);
+ const createParams = createSessionCreateParams(input, sandboxName);
if (input.tags !== undefined) {
createParams.tags = input.tags;
}
@@ -572,12 +511,9 @@ async function ensureSession(input: EnsureSessionInput): Promise<VercelSandboxSe
function createSessionCreateParams(
input: EnsureSessionInput,
sandboxName: string,
- sessionCreateOptions: VercelSandboxMountOptions = {},
): VercelSandboxCreateParams {
- const createOptions: VercelCreateOptions = {
- ...input.createOptions,
- ...sessionCreateOptions,
- };
+ const createOptions: VercelCreateOptions = { ...input.createOptions };
+ if (input.mounts !== undefined) createOptions.mounts = input.mounts;
if (input.snapshotId === undefined) {
return withBaseSetupNetworkPolicy({
...createOptions,
@@ -607,49 +543,29 @@ function createSessionCreateParams(
};
}
-function createHandle(input: {
- readonly createOptions: VercelCreateOptions;
- readonly loadDeleteSandboxModule: () => Promise<VercelModule>;
- readonly sandbox: VercelSandbox;
-}): SandboxProviderHandle<VercelSandboxSession> {
- const { sandbox } = input;
+function createVercelConnection(
+ sandbox: VercelSandbox,
+): SandboxConnection<VercelSandboxExtensions> {
return {
- sandbox: {
- ...buildSandboxSession(
- createVercelInternalSandboxSession(sandbox),
- createVercelNetworkPolicySetter(sandbox),
- ),
+ extensions: {
name: sandbox.name,
+ setNetworkPolicy: createVercelNetworkPolicySetter(sandbox),
},
- async onSandboxDelete(options) {
- await deleteVercelSandbox({
- createOptions: input.createOptions,
- loadDeleteSandboxModule: input.loadDeleteSandboxModule,
- sandbox,
- signal: options?.abortSignal,
- });
- },
- async onSandboxStop() {
- await stopVercelSandbox(sandbox);
+ async readFile(options) {
+ return normalizeVercelReadStream(await sandbox.readFile({ path: options.path }));
},
- async onRuntimeShutdown() {
- try {
- await stopVercelSandbox(sandbox);
- } catch {
- // Provider-side timeout is the backstop when the sandbox is unreachable.
- }
+ async removePath(options: SandboxRemovePathOptions) {
+ await sandbox.fs.rm(options.path, {
+ force: options.force,
+ recursive: options.recursive,
+ signal: options.abortSignal,
+ });
},
- };
-}
-
-function createVercelInternalSandboxSession(sandbox: VercelSandbox): InternalSandboxSession {
- return {
- resolvePath: resolveVercelSandboxPath,
- async spawn(options: SandboxSpawnOptions): Promise<SandboxProcess> {
+ async spawn(options): Promise<SandboxProcess> {
const command = await sandbox.runCommand({
args: ["-lc", options.command],
cmd: "bash",
- cwd: options.workingDirectory ?? WORKSPACE_ROOT,
+ cwd: options.workingDirectory,
detached: true,
env: options.env,
signal: options.abortSignal,
@@ -659,14 +575,8 @@ function createVercelInternalSandboxSession(sandbox: VercelSandbox): InternalSan
getOutput: (log) => log.stream,
});
},
- async readFile(options: SandboxReadFileOptions) {
- return normalizeVercelReadStream(await sandbox.readFile({ path: options.path }));
- },
- async writeFile(options: SandboxWriteFileOptions) {
- const files = [{ content: await streamToBuffer(options.content), path: options.path }];
- await sandbox.writeFiles(await resolveVercelWriteFiles(sandbox, files, options.abortSignal), {
- signal: options.abortSignal,
- });
+ async stop() {
+ await stopVercelSandbox(sandbox);
},
async writeFiles(options: SandboxWriteFilesOptions) {
if (options.files.length === 0) return;
@@ -675,58 +585,53 @@ function createVercelInternalSandboxSession(sandbox: VercelSandbox): InternalSan
{ signal: options.abortSignal },
);
},
- async removePath(options: SandboxRemovePathOptions) {
- await sandbox.fs.rm(options.path, {
- force: options.force,
- recursive: options.recursive,
- signal: options.abortSignal,
- });
- },
};
}
-async function writeVercelSandboxSeedFiles(input: {
- readonly sandbox: VercelSandbox;
- readonly seedFiles: ReadonlyArray<VercelSeedFile>;
- readonly session: SandboxSession;
-}): Promise<void> {
- if (input.seedFiles.length === 0) {
- return;
- }
-
- const files = await Promise.all(
- input.seedFiles.map(async (file) => ({
- content: typeof file.content === "string" ? Buffer.from(file.content) : file.content,
- path: await resolveSandboxModelPath({
- path: file.path,
- sandbox: input.session,
- }),
- })),
- );
-
- await input.sandbox.writeFiles(files);
-}
-
-function resolveVercelSandboxPath(path: string): string {
- if (path.startsWith("/")) {
- return path;
- }
- return `${WORKSPACE_ROOT}/${path}`;
-}
+/** Keeps each `realpath` argument list far below the kernel's argument size limit. */
+const REALPATH_ARGUMENT_BYTES = 64 * 1024;
/**
* The SDK writes by unpacking a tar archive, which replaces a symlinked
* destination instead of writing through it. Resolve every path first, with
- * one `realpath` call. `-z` ends each path with NUL, so names with whitespace
- * or newlines come back intact.
+ * as few `realpath` calls as the argument size limit allows.
*/
async function resolveVercelWriteFiles(
sandbox: VercelSandbox,
files: SandboxWriteFilesOptions["files"],
signal?: AbortSignal,
): Promise<{ content: Uint8Array; path: string }[]> {
+ const paths: string[] = [];
+ let batch: string[] = [];
+ let batchBytes = 0;
+ for (const file of files) {
+ const bytes = Buffer.byteLength(file.path) + 1;
+ if (batch.length > 0 && batchBytes + bytes > REALPATH_ARGUMENT_BYTES) {
+ paths.push(...(await resolveVercelPaths(sandbox, batch, signal)));
+ batch = [];
+ batchBytes = 0;
+ }
+ batch.push(file.path);
+ batchBytes += bytes;
+ }
+ paths.push(...(await resolveVercelPaths(sandbox, batch, signal)));
+ return files.map((file, index) => {
+ const path = paths[index];
+ if (path === undefined || !path.startsWith("/")) {
+ throw new Error(`Failed to resolve Vercel Sandbox write path: ${file.path}`);
+ }
+ return { content: file.content, path };
+ });
+}
+
+/** `-z` ends each path with NUL, so names with whitespace or newlines come back intact. */
+async function resolveVercelPaths(
+ sandbox: VercelSandbox,
+ paths: readonly string[],
+ signal?: AbortSignal,
+): Promise<string[]> {
const result = await sandbox.runCommand({
- args: ["-m", "-z", "--", ...files.map((file) => file.path)],
+ args: ["-m", "-z", "--", ...paths],
cmd: "realpath",
signal,
});
@@ -734,19 +639,13 @@ async function resolveVercelWriteFiles(
const stderr = (await result.stderr()).trim();
throw new Error(`Failed to resolve Vercel Sandbox write paths with realpath: ${stderr}`);
}
- const paths = (await result.stdout()).split("\0").slice(0, -1);
- if (paths.length !== files.length) {
+ const resolved = (await result.stdout()).split("\0").slice(0, -1);
+ if (resolved.length !== paths.length) {
throw new Error(
- `Failed to resolve Vercel Sandbox write paths: realpath printed ${paths.length} paths for ${files.length} files.`,
+ `Failed to resolve Vercel Sandbox write paths: realpath printed ${resolved.length} paths for ${paths.length} files.`,
);
}
- return files.map((file, index) => {
- const path = paths[index];
- if (path === undefined || !path.startsWith("/")) {
- throw new Error(`Failed to resolve Vercel Sandbox write path: ${file.path}`);
- }
- return { content: file.content, path };
- });
+ return resolved;
}
/**
diff --git a/packages/eve/src/public/sandbox/vercel-sandbox.ts b/packages/eve/src/public/sandbox/vercel-sandbox.ts
index d9a83246b..a774e1b23 100644
--- a/packages/eve/src/public/sandbox/vercel-sandbox.ts
+++ b/packages/eve/src/public/sandbox/vercel-sandbox.ts
@@ -50,23 +50,23 @@ type VercelSandboxAuthorCreateOptions<T> = T extends unknown
export type VercelSandboxCreateOptions = VercelSandboxAuthorCreateOptions<VercelCreateOptions>;
/** Access mode for a Drive mounted into a Vercel Sandbox. */
-export type VercelSandboxMountMode = Vercel.SandboxMountMode;
+export type VercelSandboxMountMode = "read-write" | "snapshot";
-/** A Drive mounted at one absolute path in a Vercel Sandbox. */
-export type VercelSandboxMount = Vercel.SandboxMounts[string];
+/**
+ * A Drive mounted at one absolute path in a Vercel Sandbox: a `Drive` from
+ * `@vercel/sandbox`, mounted read-write, or a `{ drive, mode }` reference to
+ * a Drive by name, such as the one `drive.snapshot()` returns.
+ */
+export type VercelSandboxMount =
+ | { readonly name: string }
+ | { readonly drive: string; readonly mode: VercelSandboxMountMode };
/** Drive mounts keyed by absolute sandbox path. */
-export type VercelSandboxMounts = Vercel.SandboxMounts;
-
-/** Options resolved when eve creates a fresh live session sandbox. */
-export interface VercelSandboxMountOptions {
- readonly mounts?: VercelSandboxMounts;
-}
+export type VercelSandboxMounts = Readonly<Record<string, VercelSandboxMount>>;
/** Options accepted when creating one live Vercel sandbox from an environment. */
export type VercelSandboxRuntimeOptions = Omit<
VercelSandboxCreateOptions,
"fetch" | "image" | "projectId" | "source" | "tags" | "teamId" | "token"
> &
- SandboxNetworkOptions &
- VercelSandboxMountOptions;
+ SandboxNetworkOptions & { readonly mounts?: VercelSandboxMounts };
diff --git a/packages/eve/src/public/sandbox/vercel.test.ts b/packages/eve/src/public/sandbox/vercel.test.ts
index b5c844005..4b851a33c 100644
--- a/packages/eve/src/public/sandbox/vercel.test.ts
+++ b/packages/eve/src/public/sandbox/vercel.test.ts
@@ -1,13 +1,27 @@
import { describe, expect, expectTypeOf, it } from "vitest";
+import type { Drive } from "#compiled/@vercel/sandbox/index.js";
import type { SessionContext } from "#context/session-context.js";
import type { RuntimeSandboxSessionFor } from "#public/definitions/sandbox.js";
-import { Drive, VercelSandbox, type VercelSandboxSession } from "#public/sandbox/vercel.js";
+import {
+ VercelSandbox,
+ type VercelSandboxMount,
+ type VercelSandboxSession,
+} from "#public/sandbox/vercel.js";
describe("VercelSandbox", () => {
it("creates environments", () => {
- const environment = VercelSandbox.environment({ resources: { vcpus: 4 } });
+ const environment = VercelSandbox.environment({
+ prepare: async (sandbox) => {
+ expectTypeOf(sandbox).toExtend<VercelSandboxSession>();
+ },
+ resources: { vcpus: 4 },
+ });
expect(environment.provider).toBe("vercel");
expectTypeOf(environment.open).toBeFunction();
- expectTypeOf(Drive.getOrCreate).toBeFunction();
+ });
+
+ it("accepts the Sandbox SDK's Drive and its snapshot reference as mounts", () => {
+ expectTypeOf<Drive>().toExtend<VercelSandboxMount>();
+ expectTypeOf<ReturnType<Drive["snapshot"]>>().toExtend<VercelSandboxMount>();
});
it("preserves its session capabilities through getSandbox", () => {
diff --git a/packages/eve/src/public/sandbox/vercel.ts b/packages/eve/src/public/sandbox/vercel.ts
index 7c9aee6e2..11eaa15b8 100644
--- a/packages/eve/src/public/sandbox/vercel.ts
+++ b/packages/eve/src/public/sandbox/vercel.ts
@@ -14,7 +14,6 @@ export {
type VercelSandboxEnvironmentOptions,
type VercelSandboxRuntimeOptions,
} from "#sandbox/providers/vercel.js";
-export { Drive } from "#compiled/@vercel/sandbox/index.js";
export type {
VercelSandboxMount,
VercelSandboxMountMode,
diff --git a/packages/eve/src/sandbox/provider.ts b/packages/eve/src/sandbox/provider.ts
index 713c782e1..779999012 100644
--- a/packages/eve/src/sandbox/provider.ts
+++ b/packages/eve/src/sandbox/provider.ts
@@ -277,7 +277,7 @@ function adaptSandboxProvider<
prepare: ((sandbox: SandboxSession & Extensions) => void | Promise<void>) | undefined,
): LegacySandboxProviderImplementation<OpenOptions, Artifact, State, SandboxSession & Extensions> {
const closers = new WeakMap<SandboxProviderHandle, () => Promise<void>>();
- // Connections this process holds per session, so terminal cleanup can close them.
+ // Closable connections this process holds per session, so terminal cleanup can close them.
const open = new Map<string, Set<() => Promise<void>>>();
function createHandle(
@@ -286,18 +286,20 @@ function adaptSandboxProvider<
state: Readonly<State>,
): SandboxProviderHandle<SandboxSession & Extensions> {
const sessionId = context.session.id;
- // eve may stop or close one connection from several paths, such as
- // `sandbox.stop()` and then server shutdown, so each runs once.
- const stop = once(() => connection.stop());
+ // A stopped connection can resume on its next use, so a later stop runs
+ // again; only a stop already in flight is shared. Close runs once.
+ const stop = shared(() => connection.stop());
const close = once(async () => {
const remaining = open.get(sessionId);
remaining?.delete(close);
if (remaining?.size === 0) open.delete(sessionId);
await connection.close?.();
});
- let sessionClosers = open.get(sessionId);
- if (sessionClosers === undefined) open.set(sessionId, (sessionClosers = new Set()));
- sessionClosers.add(close);
+ if (connection.close !== undefined) {
+ let sessionClosers = open.get(sessionId);
+ if (sessionClosers === undefined) open.set(sessionId, (sessionClosers = new Set()));
+ sessionClosers.add(close);
+ }
const release = async () => {
try {
await stop();
@@ -472,6 +474,14 @@ function createConnectionSession<Extensions extends object>(
}
/** Runs `run` at most once while it succeeds; a failed run can be retried. */
+function shared(run: () => Promise<void>): () => Promise<void> {
+ let running: Promise<void> | undefined;
+ return () =>
+ (running ??= run().finally(() => {
+ running = undefined;
+ }));
+}
+
function once(run: () => Promise<void>): () => Promise<void> {
let running: Promise<void> | undefined;
return () =>
diff --git a/packages/eve/src/sandbox/providers/vercel.ts b/packages/eve/src/sandbox/providers/vercel.ts
index 77b2dcff9..6003f9f75 100644
--- a/packages/eve/src/sandbox/providers/vercel.ts
+++ b/packages/eve/src/sandbox/providers/vercel.ts
@@ -1,38 +1,30 @@
import type { VercelSandboxSession } from "#public/sandbox/vercel.js";
+import { createVercelSandbox } from "#execution/sandbox/bindings/vercel.js";
import {
- createVercelSandboxProvider,
- type VercelSandboxPreparedArtifact,
- type VercelSandboxSessionState,
-} from "#execution/sandbox/bindings/vercel.js";
+ defineSandboxProvider,
+ type SandboxProvider,
+ type WithPrepareOption,
+} from "#public/sandbox/provider.js";
import type {
VercelSandboxCreateOptions,
VercelSandboxRuntimeOptions,
} from "#public/sandbox/vercel-sandbox.js";
-import type { SandboxEnvironment } from "#shared/sandbox-environment.js";
-import { defineLegacySandboxProvider } from "#shared/sandbox-provider.js";
-import type { SandboxSession } from "#shared/sandbox-session.js";
-export type VercelSandboxEnvironmentOptions = VercelSandboxCreateOptions & {
- readonly prepare?: (sandbox: SandboxSession) => Promise<void> | void;
-};
+/** Vercel create options plus `prepare`, which receives a {@link VercelSandboxSession}. */
+export type VercelSandboxEnvironmentOptions = WithPrepareOption<
+ VercelSandboxCreateOptions,
+ VercelSandboxSession
+>;
export type { VercelSandboxRuntimeOptions } from "#public/sandbox/vercel-sandbox.js";
-const provider = defineLegacySandboxProvider<
+// `| undefined` keeps the options one optional argument: the create options
+// are a union that would otherwise spread into one signature per member.
+export const VercelSandbox: SandboxProvider<
VercelSandboxEnvironmentOptions | undefined,
VercelSandboxRuntimeOptions,
- VercelSandboxPreparedArtifact,
- VercelSandboxSessionState,
VercelSandboxSession
->({
+> = defineSandboxProvider({
name: "vercel",
- environment: (options) => createVercelSandboxProvider(options),
+ environment: (options: VercelSandboxCreateOptions) =>
+ createVercelSandbox({ createOptions: options }),
});
-
-export const VercelSandbox = {
- name: "vercel",
- environment(
- options?: VercelSandboxEnvironmentOptions,
- ): SandboxEnvironment<VercelSandboxRuntimeOptions, VercelSandboxSession> {
- return provider.environment(options);
- },
-};
diff --git a/packages/eve/test/scenarios/public-api-portability.scenario.test.ts b/packages/eve/test/scenarios/public-api-portability.scenario.test.ts
index 20b8e9773..3b48aaa29 100644
--- a/packages/eve/test/scenarios/public-api-portability.scenario.test.ts
+++ b/packages/eve/test/scenarios/public-api-portability.scenario.test.ts
@@ -69,7 +69,7 @@ export default withEve(config);
import { defineSandboxProvider } from "eve/sandbox/provider";
import { DockerSandbox } from "eve/sandbox/docker";
import { JustBashSandbox } from "eve/sandbox/just-bash";
-import { Drive, VercelSandbox } from "eve/sandbox/vercel";
+import { VercelSandbox } from "eve/sandbox/vercel";
const custom = defineSandboxProvider({
name: "custom",
@@ -87,7 +87,6 @@ void custom.environment();
export const environment = process.env.VERCEL === "1"
? VercelSandbox.environment({ resources: { vcpus: 2 } })
: DefaultSandbox.environment({ docker: { image: "ghcr.io/vercel/eve:latest" } });
-void Drive;
async function verifyMutableNetworkCapability() {
const sandbox = await DockerSandbox.dockerfile().open({ networkPolicy: "deny-all" });
await sandbox.setNetworkPolicy("allow-all");
diff --git a/research/sandbox-provider-api.md b/research/sandbox-provider-api.md
index 1be1c34df..b1f23bfb5 100644
--- a/research/sandbox-provider-api.md
+++ b/research/sandbox-provider-api.md
@@ -329,7 +329,8 @@ runtime
keyed call ends → connection.close?()
terminal outcome → connection.close?() for this process's connections,
onSessionEnd(ctx, state | null, { reason })
- (stop and close run at most once per connection; a failed close never blocks deletion)
+ (close runs at most once per connection; stop is idempotent and may run again after
+ the connection resumes; a failed close never blocks deletion)
```
## Invariants
@@ -395,10 +396,10 @@ names match.
| just-bash | root directory from hash of `{ sessionId, version: 2 }` | `{ autoInstall, customCommands, filesystem, version: 2 }`, first 24 hex |
Docker mounts `await ctx.resourcesDirectory()` and calls
-`ctx.populate(connection, { mountedAt: "/eve/resources" })`. Vercel's
-`DefaultSandbox` facade skips preparation when `ctx.isEmpty`;
-`VercelSandbox.environment()` does not. Vercel and just-bash set
-`toolSessions: true`; only just-bash needs `close()`.
+`ctx.populate(connection, { mountedAt: "/eve/resources" })`. Vercel skips
+preparation when `ctx.isEmpty` and no `source` is set, in
+`VercelSandbox.environment()` itself and therefore under `DefaultSandbox` too.
+Vercel and just-bash set `toolSessions: true`; only just-bash needs `close()`.
## Custom provider example
@@ -517,8 +518,13 @@ the last step. There are no public dual-shape overloads.
3. Migrate Docker, with the golden key and name test.
4. Migrate Vercel Sandbox, with the golden key and name test. Its changeset
notes that a relative `workingDirectory` now resolves from `/workspace`.
+ Implemented: `VercelSandbox.environment()` itself keeps skipping an empty
+ preparation without a `source`, because deployed self-modification relies
+ on it, and the same step removed `Drive` (minor changeset).
5. Make core consume the new shape directly. Remove the internal old shape,
- and the tool-session `WeakMap`. Add a
+ and the tool-session `WeakMap`. Close a connection when the step that
+ opened it lets go of it; until then, eve closes connections only at the
+ other lifecycle points above. Add a
`guard:invariants` rule for files under `src/execution/sandbox/bindings/`
and `src/sandbox/providers/`: they may import the provider contract only
through `#public/sandbox/*`, and may not import core sandbox modules