The Open Framework for Building Agents
fix(eve): sandbox - sync Vercel types and normalize file streams (#176)
Andrew Barba8f7d97bfc4d6
diff --git a/.changeset/calm-sandboxes-copy.md b/.changeset/calm-sandboxes-copy.mdnew file mode 100644index 000000000..2f5e05082--- /dev/null+++ b/.changeset/calm-sandboxes-copy.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Keep Vercel Sandbox option types synchronized with the installed SDK by vendoring its upstream declaration files instead of maintaining a hand-written copy. Vercel-backed file reads now convert provider Node streams to Eve's public Web stream contract.diff --git a/packages/eve/scripts/vendor-compiled/@vercel/sandbox.mjs b/packages/eve/scripts/vendor-compiled/@vercel/sandbox.mjsindex f04a5d4fb..2202b0474 100644--- a/packages/eve/scripts/vendor-compiled/@vercel/sandbox.mjs+++ b/packages/eve/scripts/vendor-compiled/@vercel/sandbox.mjs@@ -1,29 +1,47 @@+import { relative } from "node:path";+import {+ buildOpaqueTypesStub,+ buildUniqueSymbolStub,+ collectFilesRecursively,createDeclarationCopier,createOptionalNativeStubPlugin,- loadDeclaration,} from "../_shared.mjs";+async function discoverDeclarationFiles({ distDir }) {+ const files = await collectFilesRecursively(distDir, [".d.ts"]);+ return files+ .map((file) => relative(distDir, file).replaceAll("\\", "/"))+ .sort()+ .map((file) => ({ source: file, output: file }));+}+/**- * `@vercel/sandbox` is vendored as a hand-curated adapter (`index.d.ts`)- * that narrows the SDK to the surface eve wraps and renames a couple of- * types upstream never exports (`Command` -> `SandboxCommand`, the inline- * `update` param -> `SandboxUpdateParams`). The adapter intentionally does- * NOT re-declare the firewall network-policy types.- *- * Those types drove a real drift bug: the hand-written copy lagged the- * SDK's credential-brokering matchers (`match`, `forwardURL`, …). So- * `network-policy.d.ts` is copied verbatim from the installed package and- * the adapter re-exports it. The upstream file is self-contained (zero- * imports), so no rewrite rules are needed — and a future version that- * adds an import hard-fails the copier instead of silently drifting.+ * Copy the complete declaration tree from the installed SDK so every Vercel+ * Sandbox version bump updates eve's public option types automatically.+ * Bare type dependencies are redirected to existing vendored declarations+ * or local stubs, while Node built-ins remain external.*/export default {packageName: "@vercel/sandbox",compiledPath: "@vercel/sandbox",plugins: [createOptionalNativeStubPlugin(["fsevents"])],- declaration: await loadDeclaration("@vercel/sandbox.d.ts"),copyDeclarations: createDeclarationCopier({- files: [{ source: "network-policy.d.ts", output: "network-policy.d.ts" }],+ files: discoverDeclarationFiles,+ rewrites: {+ "@workflow/serde": {+ kind: "stub",+ stubBaseName: "_workflow-serde",+ build: buildUniqueSymbolStub,+ },+ "async-retry": {+ kind: "stub",+ stubBaseName: "_async-retry",+ build: buildOpaqueTypesStub,+ },+ fs: { kind: "external" },+ stream: { kind: "external" },+ zod: { kind: "vendored", compiledPath: "zod" },+ },}),};diff --git a/packages/eve/scripts/vendor-compiled/_shared.mjs b/packages/eve/scripts/vendor-compiled/_shared.mjsindex 2e8472ed2..561967d0a 100644--- a/packages/eve/scripts/vendor-compiled/_shared.mjs+++ b/packages/eve/scripts/vendor-compiled/_shared.mjs@@ -209,9 +209,10 @@ function relativeDeclarationSpecifier(fromOutputPath, targetFileName) {/*** Returns `Map<externalModuleName, Set<importedName>>` for every* `import { ... } from '<external>'`, `export { ... } from '<external>'`,- * and `import * as <alias> from '<external>'` in a TypeScript declaration- * source. Local relative paths and `#compiled/*` specifiers are skipped —- * only bare module specifiers appear in the map.+ * `import * as <alias> from '<external>'`, and side-effect+ * `import '<external>'` in a TypeScript declaration source. Local relative+ * paths and `#compiled/*` specifiers are skipped — only bare module+ * specifiers appear in the map.** `as`-renames are flattened to the original left-side name so the stub* exports the symbol the upstream actually references.@@ -225,6 +226,7 @@ export function collectExternalDeclarationImports(source) {const namedPattern = /^(?:import|export)\s+(?:type\s+)?\{([^}]+)\}\s+from\s+['"]([^'"]+)['"];/gm;const namespacePattern =/^import\s+(?:type\s+)?\*\s+as\s+([A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+)['"];/gm;+ const sideEffectPattern = /^import\s+['"]([^'"]+)['"];/gm;const result = new Map();const isExternal = (moduleName) =>@@ -281,19 +283,26 @@ export function collectExternalDeclarationImports(source) {}}+ for (const match of source.matchAll(sideEffectPattern)) {+ addName(match[1]);+ }+return result;}/**- * Rewrites every `from '<moduleName>'` (and the `"`-quoted variant) in- * a declaration source to `from '<replacement>'`. Used to redirect copied- * `.d.ts` imports at locally-vendored stubs or `#compiled/*` re-vendoring.+ * Rewrites every `from '<moduleName>'` and side-effect+ * `import '<moduleName>'` (including their `"`-quoted variants) in a+ * declaration source. Used to redirect copied `.d.ts` imports at+ * locally-vendored stubs or `#compiled/*` re-vendoring.*/export function rewriteImportSource(source, moduleName, replacement) {const escaped = moduleName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");return source.replaceAll(new RegExp(`from '${escaped}'`, "g"), `from '${replacement}'`)- .replaceAll(new RegExp(`from "${escaped}"`, "g"), `from "${replacement}"`);+ .replaceAll(new RegExp(`from "${escaped}"`, "g"), `from "${replacement}"`)+ .replaceAll(new RegExp(`import '${escaped}'`, "g"), `import '${replacement}'`)+ .replaceAll(new RegExp(`import "${escaped}"`, "g"), `import "${replacement}"`);}/**diff --git a/packages/eve/scripts/vendor-compiled/declarations/@vercel/sandbox.d.ts b/packages/eve/scripts/vendor-compiled/declarations/@vercel/sandbox.d.tsdeleted file mode 100644index 6e7863a21..000000000--- a/packages/eve/scripts/vendor-compiled/declarations/@vercel/sandbox.d.ts+++ /dev/null@@ -1,129 +0,0 @@-// The firewall network-policy types are copied verbatim from the installed-// `@vercel/sandbox` at vendor time (see scripts/vendor-compiled/@vercel/sandbox.mjs)-// so the credential-brokering surface never drifts from the SDK.-import type { NetworkPolicy } from "./network-policy.js";--export type {- NetworkPolicy,- NetworkPolicyKeyValueMatcher,- NetworkPolicyMatch,- NetworkPolicyMatcher,- NetworkPolicyRule,- NetworkTransformer,-} from "./network-policy.js";--export interface SandboxKeepLastSnapshotsConfig {- count: number;- expiration?: number | undefined;- deleteEvicted?: boolean | undefined;-}--export interface SandboxUpdateParams {- currentSnapshotId?: string | undefined;- keepLastSnapshots?: SandboxKeepLastSnapshotsConfig | null | undefined;- networkPolicy?: NetworkPolicy | undefined;- persistent?: boolean | undefined;- ports?: number[] | undefined;- resources?: { vcpus?: number | undefined } | undefined;- snapshotExpiration?: number | undefined;- tags?: Record<string, string> | undefined;- timeout?: number | undefined;-}--export interface SandboxCreateOptions {- [key: `__${string}`]: unknown;- env?: Record<string, string> | undefined;- name?: string | undefined;- networkPolicy?: NetworkPolicy | undefined;- onResume?: ((sandbox: Sandbox) => Promise<void>) | undefined;- persistent?: boolean | undefined;- ports?: number[] | undefined;- resources?: { vcpus?: number | undefined } | undefined;- runtime?: string | undefined;- signal?: AbortSignal | undefined;- snapshotExpiration?: number | undefined;- source?: unknown;- tags?: Record<string, string> | undefined;- timeout?: number | undefined;-}--export interface SandboxGetOptions {- name: string;- onResume?: ((sandbox: Sandbox) => Promise<void>) | undefined;- resume?: boolean | undefined;- signal?: AbortSignal | undefined;-}--export interface SandboxRunCommandParams {- args?: readonly string[] | undefined;- cmd: string;- cwd?: string | undefined;- detached?: boolean | undefined;- env?: Record<string, string> | undefined;- signal?: AbortSignal | undefined;- sudo?: boolean | undefined;-}--export interface SandboxRmOptions {- force?: boolean | undefined;- recursive?: boolean | undefined;- signal?: AbortSignal | undefined;-}--export declare class FileSystem {- rm(path: string, options?: SandboxRmOptions): Promise<void>;- unlink(path: string, options?: { signal?: AbortSignal | undefined }): Promise<void>;-}--export interface SandboxCommandLogMessage {- data: string;- stream: "stdout" | "stderr";-}--export declare class SandboxCommand {- readonly cmdId: string;- readonly cwd: string;- exitCode: number | null;- logs(opts?: {- signal?: AbortSignal | undefined;- }): AsyncGenerator<SandboxCommandLogMessage, void, void>;- wait(opts?: { signal?: AbortSignal | undefined }): Promise<SandboxCommandFinished>;- stdout(opts?: { signal?: AbortSignal | undefined }): Promise<string>;- stderr(opts?: { signal?: AbortSignal | undefined }): Promise<string>;- kill(signal?: string, opts?: { abortSignal?: AbortSignal | undefined }): Promise<void>;-}--export interface SandboxCommandFinished extends SandboxCommand {- exitCode: number;-}--export type SandboxCommandResult = SandboxCommandFinished;--export declare class Sandbox {- currentSnapshotId?: string | undefined;- readonly fs: FileSystem;- id: string;- name: string;- networkPolicy?: NetworkPolicy | undefined;- persistent: boolean;- status: string;- tags?: Record<string, string> | undefined;- static create(options?: SandboxCreateOptions): Promise<Sandbox>;- static get(options: SandboxGetOptions): Promise<Sandbox>;- domain(port: number): string;- readFile(file: { path: string }): Promise<ReadableStream<Uint8Array> | null>;- readFileToBuffer(file: { path: string }): Promise<Buffer | null>;- runCommand(input: SandboxRunCommandParams & { detached: true }): Promise<SandboxCommand>;- runCommand(input: SandboxRunCommandParams): Promise<SandboxCommandFinished>;- snapshot(options?: unknown): Promise<{ snapshotId: string }>;- stop(options?: unknown): Promise<void>;- update(- params: SandboxUpdateParams,- opts?: { signal?: AbortSignal | undefined } | undefined,- ): Promise<void>;- writeFiles(- files: readonly { content: string | Uint8Array; path: string }[],- options?: unknown,- ): Promise<void>;- [key: string]: any;-}diff --git a/packages/eve/src/execution/sandbox/bindings/vercel-base-runtime.ts b/packages/eve/src/execution/sandbox/bindings/vercel-base-runtime.tsindex 8136aa4b1..9853865a9 100644--- a/packages/eve/src/execution/sandbox/bindings/vercel-base-runtime.ts+++ b/packages/eve/src/execution/sandbox/bindings/vercel-base-runtime.ts@@ -1,14 +1,13 @@-import type {- SandboxCreateOptions,- Sandbox as SdkSandbox,-} from "#compiled/@vercel/sandbox/index.js";-import { buildDockerBaseSetupScript } from "#execution/sandbox/bindings/docker-base-setup.js";+import type {+ VercelCreateOptions,+ VercelSandbox,+} from "#execution/sandbox/bindings/vercel-sdk-types.js";/*** Prepares a fresh Vercel sandbox for use by the framework.*/-export async function ensureVercelSandboxBaseRuntime(sandbox: SdkSandbox): Promise<void> {+export async function ensureVercelSandboxBaseRuntime(sandbox: VercelSandbox): Promise<void> {await runSandboxBootstrapStep(sandbox, {failureMessage: "Failed to initialize Vercel sandbox base runtime.",script: buildDockerBaseSetupScript(),@@ -16,8 +15,8 @@ export async function ensureVercelSandboxBaseRuntime(sandbox: SdkSandbox): Promi}export async function applyInitialVercelNetworkPolicy(- sandbox: SdkSandbox,- networkPolicy: SandboxCreateOptions["networkPolicy"],+ sandbox: VercelSandbox,+ networkPolicy: VercelCreateOptions["networkPolicy"],): Promise<void> {if (networkPolicy !== undefined) {await sandbox.update({ networkPolicy });@@ -25,7 +24,7 @@ export async function applyInitialVercelNetworkPolicy(}async function runSandboxBootstrapStep(- sandbox: SdkSandbox,+ sandbox: VercelSandbox,input: { readonly failureMessage: string; readonly script: string },): Promise<void> {const result = await runBootstrapCommand(sandbox, input.script);@@ -42,7 +41,7 @@ async function runSandboxBootstrapStep(throw new Error(`${input.failureMessage}${output ? `\n${output}` : ""}`);}-async function runBootstrapCommand(sandbox: SdkSandbox, script: string): Promise<string | null> {+async function runBootstrapCommand(sandbox: VercelSandbox, script: string): Promise<string | null> {return await readBootstrapFailure(await sandbox.runCommand({args: ["-lc", script],@@ -52,7 +51,7 @@ async function runBootstrapCommand(sandbox: SdkSandbox, script: string): Promise}async function runBootstrapCommandWithSudo(- sandbox: SdkSandbox,+ sandbox: VercelSandbox,script: string,): Promise<string | null> {return await readBootstrapFailure(@@ -64,7 +63,7 @@ async function runBootstrapCommandWithSudo(}async function readBootstrapFailure(- result: Awaited<ReturnType<SdkSandbox["runCommand"]>>,+ result: Awaited<ReturnType<VercelSandbox["runCommand"]>>,): Promise<string | null> {if (result.exitCode === 0) {return null;diff --git a/packages/eve/src/execution/sandbox/bindings/vercel-create-sdk.ts b/packages/eve/src/execution/sandbox/bindings/vercel-create-sdk.tsindex 182df5e5e..80a6933b2 100644--- a/packages/eve/src/execution/sandbox/bindings/vercel-create-sdk.ts+++ b/packages/eve/src/execution/sandbox/bindings/vercel-create-sdk.ts@@ -1,16 +1,14 @@-import type * as VercelSandboxSdk from "#compiled/@vercel/sandbox/index.js";import type {- SandboxCreateOptions,- Sandbox as SdkSandbox,-} from "#compiled/@vercel/sandbox/index.js";+ VercelCreateOptions,+ VercelModule,+ VercelSandbox,+} from "#execution/sandbox/bindings/vercel-sdk-types.js";-export type VercelSandboxModule = typeof VercelSandboxSdk;--export type VercelSandboxCreateParams = SandboxCreateOptions & {+export type VercelSandboxCreateParams = VercelCreateOptions & {readonly name: string;readonly persistent: boolean;- readonly source?: SandboxCreateOptions["source"] | { snapshotId: string; type: "snapshot" };- readonly tags?: Record<string, string> | undefined;+ readonly source?: VercelCreateOptions["source"];+ tags?: Record<string, string> | undefined;} & VercelSandboxInternalCreateOptions;type VercelSandboxInternalCreateOptions = {@@ -19,13 +17,13 @@ type VercelSandboxInternalCreateOptions = {export type CreateVercelSandbox = (input: {readonly createOptions: VercelSandboxCreateParams;- readonly sandboxModule: VercelSandboxModule;-}) => Promise<SdkSandbox>;+ readonly sandboxModule: VercelModule;+}) => Promise<VercelSandbox>;export async function createVercelEveImageSandbox(input: {readonly createOptions: VercelSandboxCreateParams;- readonly sandboxModule: VercelSandboxModule;-}): Promise<SdkSandbox> {+ readonly sandboxModule: VercelModule;+}): Promise<VercelSandbox> {const createOptions: VercelSandboxCreateParams = {...input.createOptions,__image: VERCEL_EVE_SANDBOX_IMAGE,diff --git a/packages/eve/src/execution/sandbox/bindings/vercel-credentials.ts b/packages/eve/src/execution/sandbox/bindings/vercel-credentials.tsindex 069b28d64..c0b5578f4 100644--- a/packages/eve/src/execution/sandbox/bindings/vercel-credentials.ts+++ b/packages/eve/src/execution/sandbox/bindings/vercel-credentials.ts@@ -1,15 +1,13 @@import { getVercelOidcToken } from "#compiled/@vercel/oidc/index.js";-import type { SandboxCreateOptions } from "#compiled/@vercel/sandbox/index.js";+import type { VercelCreateOptions } from "#execution/sandbox/bindings/vercel-sdk-types.js";-export function getVercelSandboxFetch(- createOptions: SandboxCreateOptions,-): typeof globalThis.fetch {+export function getVercelSandboxFetch(createOptions: VercelCreateOptions): typeof globalThis.fetch {const fetchOverride = (createOptions as { readonly fetch?: typeof globalThis.fetch }).fetch;return fetchOverride ?? globalThis.fetch;}export async function getVercelSandboxCredentials(- createOptions: SandboxCreateOptions,+ createOptions: VercelCreateOptions,): Promise<VercelSandboxCredentials> {const teamId =readNonEmptyString(createOptions, "teamId") ??diff --git a/packages/eve/src/execution/sandbox/bindings/vercel-lookup.ts b/packages/eve/src/execution/sandbox/bindings/vercel-lookup.tsindex 03db1e12f..b1a58365b 100644--- a/packages/eve/src/execution/sandbox/bindings/vercel-lookup.ts+++ b/packages/eve/src/execution/sandbox/bindings/vercel-lookup.ts@@ -1,20 +1,19 @@-import type {- SandboxCreateOptions,- SandboxGetOptions,- Sandbox as SdkSandbox,-} from "#compiled/@vercel/sandbox/index.js";-import {getVercelSandboxCredentials,getVercelSandboxFetch,} from "#execution/sandbox/bindings/vercel-credentials.js";-import type { VercelSandboxModule } from "#execution/sandbox/bindings/vercel-create-sdk.js";+import type {+ VercelCreateOptions,+ VercelGetOptions,+ VercelModule,+ VercelSandbox,+} from "#execution/sandbox/bindings/vercel-sdk-types.js";export async function getNamedVercelSandbox(input: {- readonly createOptions: SandboxCreateOptions;- readonly sandboxModule: VercelSandboxModule;+ readonly createOptions: VercelCreateOptions;+ readonly sandboxModule: VercelModule;readonly sandboxName: string;-}): Promise<SdkSandbox | null> {+}): Promise<VercelSandbox | null> {try {return await input.sandboxModule.Sandbox.get(await getVercelSandboxGetOptions(input));} catch (error) {@@ -32,9 +31,9 @@ export async function getNamedVercelSandbox(input: {}async function getVercelSandboxGetOptions(input: {- readonly createOptions: SandboxCreateOptions;+ readonly createOptions: VercelCreateOptions;readonly sandboxName: string;-}): Promise<SandboxGetOptions> {+}): Promise<VercelGetOptions> {const baseOptions = {name: input.sandboxName,resume: false,@@ -47,7 +46,7 @@ async function getVercelSandboxGetOptions(input: {...credentials,fetch: getVercelSandboxFetch(input.createOptions),signal: input.createOptions.signal,- } as SandboxGetOptions;+ } as VercelGetOptions;} catch {return baseOptions;}diff --git a/packages/eve/src/execution/sandbox/bindings/vercel-read-stream.ts b/packages/eve/src/execution/sandbox/bindings/vercel-read-stream.tsnew file mode 100644index 000000000..bef400172--- /dev/null+++ b/packages/eve/src/execution/sandbox/bindings/vercel-read-stream.ts@@ -0,0 +1,21 @@+import { Readable } from "node:stream";++/**+ * Normalizes the Vercel SDK's Node-readable file response to Eve's public+ * WHATWG byte-stream contract.+ */+export function normalizeVercelReadStream(+ stream: object | null,+): ReadableStream<Uint8Array> | null {+ if (stream === null || isWebReadableStream(stream)) {+ return stream;+ }+ if (stream instanceof Readable) {+ return Readable.toWeb(stream) as ReadableStream<Uint8Array>;+ }+ throw new TypeError("Vercel Sandbox returned an unsupported file stream.");+}++function isWebReadableStream(value: object): value is ReadableStream<Uint8Array> {+ return "getReader" in value && typeof value.getReader === "function";+}diff --git a/packages/eve/src/execution/sandbox/bindings/vercel-sdk-types.ts b/packages/eve/src/execution/sandbox/bindings/vercel-sdk-types.tsnew file mode 100644index 000000000..58195e0fe--- /dev/null+++ b/packages/eve/src/execution/sandbox/bindings/vercel-sdk-types.ts@@ -0,0 +1,11 @@+import type * as Vercel from "#compiled/@vercel/sandbox/index.js";++export type VercelCommand = Vercel.Command;++export type VercelCreateOptions = NonNullable<Parameters<typeof Vercel.Sandbox.create>[0]>;++export type VercelGetOptions = Parameters<typeof Vercel.Sandbox.get>[0];++export type VercelModule = typeof Vercel;++export type VercelSandbox = Vercel.Sandbox;diff --git a/packages/eve/src/execution/sandbox/bindings/vercel.test.ts b/packages/eve/src/execution/sandbox/bindings/vercel.test.tsindex 41fb6eb14..f3675d32a 100644--- a/packages/eve/src/execution/sandbox/bindings/vercel.test.ts+++ b/packages/eve/src/execution/sandbox/bindings/vercel.test.ts@@ -1,3 +1,5 @@+import { Readable } from "node:stream";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { SandboxTemplateNotProvisionedError } from "#public/definitions/sandbox-backend.js";@@ -45,6 +47,7 @@ function createMockSandbox(input: {unlink: vi.fn().mockResolvedValue(undefined),},name: input.name,+ readFile: vi.fn<(file: { path: string }) => Promise<object | null>>().mockResolvedValue(null),runCommand: vi.fn().mockResolvedValue(createMockCommandResult()),snapshot: vi.fn().mockResolvedValue({ snapshotId: `${input.name}-snapshot` }),status: input.status ?? "running",@@ -68,6 +71,45 @@ function createTestVercelSandbox(input: Parameters<typeof createVercelSandbox>[0});}+async function createTestVercelSession() {+ const templateSandbox = createMockSandbox({ name: "template" });+ const sessionSandbox = createMockSandbox({ name: "session" });+ const sandboxModule = {+ Sandbox: {+ create: vi.fn().mockResolvedValueOnce(templateSandbox).mockResolvedValueOnce(sessionSandbox),+ get: vi.fn().mockResolvedValue(null),+ },+ };+ const backend = createTestVercelSandbox({+ loadSandboxModule: async () => sandboxModule as never,+ });++ await backend.prewarm({+ runtimeContext: { appRoot: "/tmp/test-app-root" },+ seedFiles: [],+ templateKey: "template-key",+ });+ const handle = await backend.create({+ runtimeContext: { appRoot: "/tmp/test-app-root" },+ sessionKey: "session-key",+ templateKey: "template-key",+ });++ return { handle, sessionSandbox };+}++async function consumeWebStream(stream: ReadableStream<Uint8Array>): Promise<string> {+ const reader = stream.getReader();+ const chunks: Uint8Array[] = [];+ while (true) {+ const result = await reader.read();+ if (result.done) {+ return Buffer.concat(chunks).toString("utf8");+ }+ chunks.push(result.value);+ }+}+beforeEach(() => {vi.stubEnv("VERCEL_OIDC_TOKEN", undefined);vi.stubEnv("VERCEL_ORG_ID", undefined);@@ -1361,6 +1403,60 @@ describe("createVercelSandbox", () => {);});+ it("converts Vercel Node file streams to the public Web stream contract", async () => {+ const { handle, sessionSandbox } = await createTestVercelSession();+ sessionSandbox.readFile.mockResolvedValueOnce(+ Readable.from([Buffer.from("hello "), Buffer.from("sandbox")]),+ );++ const stream = await handle.session.readFile({ path: "/workspace/message.txt" });++ expect(stream).not.toBeNull();+ expect(await consumeWebStream(stream!)).toBe("hello sandbox");+ expect(sessionSandbox.readFile).toHaveBeenCalledWith({ path: "/workspace/message.txt" });+ });++ it("passes existing Web file streams through unchanged", async () => {+ const { handle, sessionSandbox } = await createTestVercelSession();+ const providerStream = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(Buffer.from("web stream"));+ controller.close();+ },+ });+ sessionSandbox.readFile.mockResolvedValueOnce(providerStream);++ const stream = await handle.session.readFile({ path: "/workspace/message.txt" });++ expect(stream).toBe(providerStream);+ expect(await consumeWebStream(stream!)).toBe("web stream");+ });++ it("preserves missing Vercel files as null", async () => {+ const { handle } = await createTestVercelSession();++ await expect(handle.session.readFile({ path: "/workspace/missing.txt" })).resolves.toBeNull();+ });++ it("propagates Vercel file-read errors unchanged", async () => {+ const { handle, sessionSandbox } = await createTestVercelSession();+ const providerError = new Error("provider read failed");+ sessionSandbox.readFile.mockRejectedValueOnce(providerError);++ await expect(handle.session.readFile({ path: "/workspace/message.txt" })).rejects.toBe(+ providerError,+ );+ });++ it("rejects unsupported Vercel file-stream values", async () => {+ const { handle, sessionSandbox } = await createTestVercelSession();+ sessionSandbox.readFile.mockResolvedValueOnce({ readable: true });++ await expect(handle.session.readFile({ path: "/workspace/message.txt" })).rejects.toThrow(+ "Vercel Sandbox returned an unsupported file stream.",+ );+ });+it("forwards env to runCommand when spawning a process", async () => {const templateSandbox = createMockSandbox({ name: "template" });const sessionSandbox = createMockSandbox({ name: "session" });diff --git a/packages/eve/src/execution/sandbox/bindings/vercel.ts b/packages/eve/src/execution/sandbox/bindings/vercel.tsindex 0989a4b0d..bc04760c5 100644--- a/packages/eve/src/execution/sandbox/bindings/vercel.ts+++ b/packages/eve/src/execution/sandbox/bindings/vercel.ts@@ -1,9 +1,3 @@-import type {- SandboxCreateOptions,- Sandbox as SdkSandbox,- SandboxCommand as SdkSandboxCommand,-} from "#compiled/@vercel/sandbox/index.js";-import {applyInitialVercelNetworkPolicy,ensureVercelSandboxBaseRuntime,@@ -40,18 +34,24 @@ import {createVercelEveImageSandbox,type CreateVercelSandbox,type VercelSandboxCreateParams,- type VercelSandboxModule,} from "#execution/sandbox/bindings/vercel-create-sdk.js";import {isVercelSandboxMissingError,isVercelSnapshotUnavailableError,} from "#execution/sandbox/bindings/vercel-errors.js";import { getNamedVercelSandbox } from "#execution/sandbox/bindings/vercel-lookup.js";+import { normalizeVercelReadStream } from "#execution/sandbox/bindings/vercel-read-stream.js";+import type {+ VercelCommand,+ VercelCreateOptions,+ VercelModule,+ VercelSandbox,+} from "#execution/sandbox/bindings/vercel-sdk-types.js";export interface CreateVercelSandboxInput {readonly createSandbox?: CreateVercelSandbox;- readonly createOptions?: SandboxCreateOptions;- readonly loadSandboxModule?: () => Promise<VercelSandboxModule>;+ readonly createOptions?: VercelCreateOptions;+ readonly loadSandboxModule?: () => Promise<VercelModule>;}/*** Creates the Vercel-backed sandbox backend.@@ -66,7 +66,7 @@ export function createVercelSandbox(): SandboxBackend<VercelSandboxBootstrapUseOptions, VercelSandboxSessionUseOptions> {const loadSandboxModule =input.loadSandboxModule ?? (async () => await import("#compiled/@vercel/sandbox/index.js"));- const createOptions: SandboxCreateOptions = {+ const createOptions: VercelCreateOptions = {timeout: DEFAULT_SANDBOX_TIMEOUT_MS,...input.createOptions,};@@ -175,9 +175,9 @@ interface EnsureTemplateInput {readonly bootstrap?: (input: SandboxBootstrapContext<VercelSandboxBootstrapUseOptions>,) => void | Promise<void>;- readonly createOptions: SandboxCreateOptions;+ readonly createOptions: VercelCreateOptions;readonly createSandbox: CreateVercelSandbox;- readonly loadSandboxModule: () => Promise<VercelSandboxModule>;+ readonly loadSandboxModule: () => Promise<VercelModule>;readonly log?: (message: string) => void;readonly seedFiles: ReadonlyArray<SandboxSeedFile>;readonly tags?: SandboxBackendTags;@@ -199,8 +199,8 @@ async function ensureTemplateWithUnavailableRetry(}async function readTemplate(input: {- readonly createOptions: SandboxCreateOptions;- readonly loadSandboxModule: () => Promise<VercelSandboxModule>;+ readonly createOptions: VercelCreateOptions;+ readonly loadSandboxModule: () => Promise<VercelModule>;readonly prewarmedTemplates: ReadonlyMap<string, VercelSandboxTemplateRecord>;readonly templateKey: string;}): Promise<VercelSandboxTemplateRecord> {@@ -231,8 +231,8 @@ async function readTemplate(input: {}async function readTemplateForCreate(input: {- readonly createOptions: SandboxCreateOptions;- readonly loadSandboxModule: () => Promise<VercelSandboxModule>;+ readonly createOptions: VercelCreateOptions;+ readonly loadSandboxModule: () => Promise<VercelModule>;readonly prewarmedTemplates: ReadonlyMap<string, VercelSandboxTemplateRecord>;readonly templateKey: string;}): Promise<VercelSandboxTemplateRecord> {@@ -354,10 +354,10 @@ async function ensureTemplate(input: EnsureTemplateInput): Promise<EnsureTemplat}interface EnsureSessionInput {- readonly createOptions: SandboxCreateOptions;+ readonly createOptions: VercelCreateOptions;readonly createSandbox: CreateVercelSandbox;readonly existingMetadata?: Record<string, unknown>;- readonly sandboxModule: VercelSandboxModule;+ readonly sandboxModule: VercelModule;readonly sessionKey: string;readonly snapshotId?: string;readonly tags: Record<string, string> | undefined;@@ -365,7 +365,7 @@ interface EnsureSessionInput {interface VercelSandboxSessionCreateResult {readonly created: boolean;- readonly sandbox: SdkSandbox;+ readonly sandbox: VercelSandbox;}async function ensureSession(input: EnsureSessionInput): Promise<VercelSandboxSessionCreateResult> {@@ -382,7 +382,6 @@ async function ensureSession(input: EnsureSessionInput): Promise<VercelSandboxSe}const createParams = createSessionCreateParams(input, sandboxName);-if (input.tags !== undefined) {createParams.tags = input.tags;}@@ -409,13 +408,15 @@ function createSessionCreateParams(}/*- * Strip both `source` and `runtime` from author-supplied create- * options for the template-backed session path. The framework owns- * the session source there, and the Vercel SDK rejects `runtime`- * when `source` is a snapshot because the runtime is already baked- * into the snapshot filesystem.+ * Strip both `source` and `runtime` from author-supplied create options for the+ * template-backed session path. The framework owns the source there, and the SDK+ * rejects `runtime` for a snapshot because its runtime is already baked into it.*/- const { runtime: _runtime, source: _source, ...sessionCreateOptions } = input.createOptions;+ const {+ runtime: _runtime,+ source: _source,+ ...sessionCreateOptions+ } = input.createOptions as VercelCreateOptions & Partial<Record<"runtime" | "source", unknown>>;return {...sessionCreateOptions,@@ -432,7 +433,7 @@ function withBaseSetupNetworkPolicy(}function createHandle(- sandbox: SdkSandbox,+ sandbox: VercelSandbox,sessionKey: string,): SandboxBackendHandle<VercelSandboxSessionUseOptions> {return {@@ -461,7 +462,7 @@ function createHandle(}function createVercelNetworkPolicySetter(- sandbox: SdkSandbox,+ sandbox: VercelSandbox,): (policy: SandboxNetworkPolicy) => Promise<void> {return async (policy) => {await sandbox.update({ networkPolicy: policy });@@ -469,7 +470,7 @@ function createVercelNetworkPolicySetter(}function createVercelInternalSandboxSession(- sandbox: SdkSandbox,+ sandbox: VercelSandbox,id: string,): InternalSandboxSession {return {@@ -487,8 +488,7 @@ function createVercelInternalSandboxSession(return adaptVercelCommandToSandboxProcess(command);},async readFile(options: SandboxReadFileOptions) {- const stream = await sandbox.readFile({ path: options.path });- return stream ?? null;+ return normalizeVercelReadStream(await sandbox.readFile({ path: options.path }));},async writeFile(options: SandboxWriteFileOptions) {const bytes = await streamToBuffer(options.content);@@ -510,7 +510,7 @@ function createVercelInternalSandboxSession(* `logs()` iterator into two byte streams, exposes a `wait()` that* resolves with the exit code, and forwards `kill()` to the SDK.*/-function adaptVercelCommandToSandboxProcess(command: SdkSandboxCommand): SandboxProcess {+function adaptVercelCommandToSandboxProcess(command: VercelCommand): SandboxProcess {const encoder = new TextEncoder();let stdoutController: ReadableStreamDefaultController<Uint8Array> | undefined;let stderrController: ReadableStreamDefaultController<Uint8Array> | undefined;@@ -578,7 +578,7 @@ function resolveVercelSandboxPath(path: string): string {}function isUnprovisionedTerminalTemplateSandbox(- sandbox: SdkSandbox,+ sandbox: VercelSandbox,authorSnapshotId: string | undefined,): boolean {const currentSnapshotId = sandbox.currentSnapshotId;@@ -601,7 +601,7 @@ function isUnprovisionedTerminalTemplateSandbox(* no source was supplied — those don't seed `currentSnapshotId` with a* pre-existing value the way snapshot sources do.*/-function extractAuthorSnapshotId(createOptions: SandboxCreateOptions): string | undefined {+function extractAuthorSnapshotId(createOptions: VercelCreateOptions): string | undefined {const source = (createOptions as { source?: { type?: string; snapshotId?: string } }).source;if (source?.type === "snapshot" && typeof source.snapshotId === "string") {return source.snapshotId;@@ -615,7 +615,7 @@ function getVercelSandboxName(metadata: Record<string, unknown> | undefined): st}function resolveVercelSandboxTags(- userTags: SandboxCreateOptions["tags"],+ userTags: VercelCreateOptions["tags"],eveTags: SandboxBackendTags | undefined,): Record<string, string> | undefined {const tags: Record<string, string> = {};@@ -648,7 +648,7 @@ function resolveVercelSandboxTags(}async function ensureVercelSandboxTags(- sandbox: SdkSandbox,+ sandbox: VercelSandbox,tags: Record<string, string> | undefined,): Promise<void> {if (tags === undefined || areVercelSandboxTagsEqual(sandbox.tags, tags)) {diff --git a/packages/eve/src/public/sandbox/vercel-sandbox.ts b/packages/eve/src/public/sandbox/vercel-sandbox.tsindex d77c0789a..8df737a22 100644--- a/packages/eve/src/public/sandbox/vercel-sandbox.ts+++ b/packages/eve/src/public/sandbox/vercel-sandbox.ts@@ -1,7 +1,16 @@-import type {- Sandbox as SdkSandbox,- SandboxUpdateParams,-} from "#compiled/@vercel/sandbox/index.js";+import type * as Vercel from "#compiled/@vercel/sandbox/index.js";++type VercelCreateOptions = NonNullable<Parameters<typeof Vercel.Sandbox.create>[0]>;++type VercelUpdateOptions = Parameters<Vercel.Sandbox["update"]>[0];++type VercelSandboxInternalCreateOptions = {+ readonly [key: `__${string}`]: unknown;+};++type VercelSandboxAuthorCreateOptions<T> = T extends unknown+ ? Omit<T, "name" | "onResume" | "persistent" | "signal"> & VercelSandboxInternalCreateOptions+ : never;/*** Options accepted by `vercel(opts)`. Forwarded to Vercel@@ -29,19 +38,11 @@ import type {* snapshot, force a template rebuild (e.g. by changing the sandbox* definition so its template key changes).*/-export type VercelSandboxCreateOptions = Omit<- NonNullable<Parameters<typeof SdkSandbox.create>[0]>,- "name" | "onResume" | "persistent" | "signal"-> &- VercelSandboxInternalCreateOptions;--type VercelSandboxInternalCreateOptions = {- readonly [key: `__${string}`]: unknown;-};+export type VercelSandboxCreateOptions = VercelSandboxAuthorCreateOptions<VercelCreateOptions>;/*** Options accepted by the Vercel backend's `bootstrap({ use })` hook.- * Aliases the Vercel SDK's `SandboxUpdateParams` because bootstrap+ * Tracks the Vercel SDK's `Sandbox.update(...)` parameter because bootstrap* applies its options to the template via `sandbox.update(...)` after* `Sandbox.create()` and before the snapshot is captured. The Vercel* SDK persists `update`-d settings on the sandbox so they survive into@@ -51,11 +52,11 @@ type VercelSandboxInternalCreateOptions = {* {@link VercelSandboxSessionUseOptions}; both are exposed as separate* named aliases so future divergence is non-breaking.*/-export type VercelSandboxBootstrapUseOptions = SandboxUpdateParams;+export type VercelSandboxBootstrapUseOptions = VercelUpdateOptions;/*** Options accepted by the Vercel backend's `onSession({ use })` hook.- * Aliases the Vercel SDK's `SandboxUpdateParams`; passed values are+ * Tracks the Vercel SDK's `Sandbox.update(...)` parameter; passed values are* applied to the live session via the SDK's `update`.*/-export type VercelSandboxSessionUseOptions = SandboxUpdateParams;+export type VercelSandboxSessionUseOptions = VercelUpdateOptions;diff --git a/packages/eve/src/shared/sandbox-network-policy.ts b/packages/eve/src/shared/sandbox-network-policy.tsindex 0ab401f33..71a01f1ba 100644--- a/packages/eve/src/shared/sandbox-network-policy.ts+++ b/packages/eve/src/shared/sandbox-network-policy.ts@@ -1,4 +1,4 @@-import type { NetworkPolicy } from "#compiled/@vercel/sandbox/index.js";+import type * as Vercel from "#compiled/@vercel/sandbox/index.js";/*** Firewall network policy applied to a live sandbox session.@@ -23,4 +23,4 @@ import type { NetworkPolicy } from "#compiled/@vercel/sandbox/index.js";* entirely (its network policy is fixed at sandbox creation and it runs* no binaries to govern).*/-export type SandboxNetworkPolicy = NetworkPolicy;+export type SandboxNetworkPolicy = Vercel.NetworkPolicy;diff --git a/packages/eve/test/scenarios/compiled-vendor-assets.scenario.test.ts b/packages/eve/test/scenarios/compiled-vendor-assets.scenario.test.tsindex 6b18a656a..94e98b8f9 100644--- a/packages/eve/test/scenarios/compiled-vendor-assets.scenario.test.ts+++ b/packages/eve/test/scenarios/compiled-vendor-assets.scenario.test.ts@@ -1,5 +1,6 @@import { readdir, readFile } from "node:fs/promises";-import { join } from "node:path";+import { createRequire } from "node:module";+import { dirname, join } from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";import { describe, expect, it } from "vitest";@@ -7,6 +8,11 @@ import { describe, expect, it } from "vitest";const EVE_PACKAGE_ROOT = fileURLToPath(new URL("../../", import.meta.url));const COMPILED_VENDOR_ROOT = join(EVE_PACKAGE_ROOT, ".generated", "compiled");const VENDOR_WARNING_LOG_PATH = join(EVE_PACKAGE_ROOT, "scripts", "vendor-warning-log.mjs");+const require = createRequire(import.meta.url);+const VERCEL_SANDBOX_DIST_ROOT = join(+ dirname(require.resolve("@vercel/sandbox/package.json")),+ "dist",+);type VendorWarningLog = {readonly createVendoredDependencyWarningFilter: () => {@@ -151,4 +157,30 @@ describe("compiled vendor assets", () => {expect(workflowIndexDts).toContain("from '#compiled/@workflow/errors/index.js'");expect(runtimeRunDts).toContain("from '../_workflow-serde.js'");});++ it("copies the complete @vercel/sandbox declaration tree from the installed package", async () => {+ const [upstreamEntries, vendoredEntries] = await Promise.all([+ readdir(VERCEL_SANDBOX_DIST_ROOT, { recursive: true }),+ readdir(join(COMPILED_VENDOR_ROOT, "@vercel/sandbox"), { recursive: true }),+ ]);+ const upstreamDeclarations = upstreamEntries.filter((entry) => entry.endsWith(".d.ts")).sort();+ const generatedStubNames = new Set(["_async-retry.d.ts", "_workflow-serde.d.ts"]);+ const vendoredDeclarations = vendoredEntries+ .filter((entry) => entry.endsWith(".d.ts") && !generatedStubNames.has(entry))+ .sort();++ expect(vendoredDeclarations).toEqual(upstreamDeclarations);++ const [upstreamIndex, vendoredIndex, vendoredSandbox, vendoredBaseClient] = await Promise.all([+ readFile(join(VERCEL_SANDBOX_DIST_ROOT, "index.d.ts"), "utf8"),+ readFile(join(COMPILED_VENDOR_ROOT, "@vercel/sandbox/index.d.ts"), "utf8"),+ readFile(join(COMPILED_VENDOR_ROOT, "@vercel/sandbox/sandbox.d.ts"), "utf8"),+ readFile(join(COMPILED_VENDOR_ROOT, "@vercel/sandbox/api-client/base-client.d.ts"), "utf8"),+ ]);++ expect(vendoredIndex).toBe(upstreamIndex);+ expect(vendoredSandbox).toContain('from "./_workflow-serde.js"');+ expect(vendoredBaseClient).toContain('from "../_async-retry.js"');+ expect(vendoredBaseClient).toContain('import "#compiled/zod/index.js"');+ });});