---
title: Migrate from Freestyle VMs to Vercel Sandbox
description: Move Freestyle VM code to Vercel Sandbox in TypeScript, from snapshots and pauses to lifecycle fields, firewall rules, credential brokering, and a staged cutover.
keywords: ["Vercel Sandbox","Freestyle","migrate from Freestyle","Freestyle VMs","AI agent sandbox","sandbox migration"]
url: "https://vercel.com/kb/guide/migrate-from-freestyle-vms-to-vercel-sandbox"
published: 2026-12-01
last_updated: 2026-12-01
authors: Ben Sabic
related_resources:
  - title: "Vercel Sandbox vs Freestyle VMs"
    url: "/kb/guide/vercel-sandbox-vs-freestyle-vms"
    description: "Compare Vercel Sandbox and Freestyle VMs as AI agent sandboxes, including isolation, persistence, network controls, SDKs, and deployment regions."
install_vercel_plugin: npx plugins add vercel/vercel-plugin
search_with_vercel_cli: npx vercel@latest kb search "<query>"
read_with_vercel_cli: "npx vercel@latest kb inspect migrate-from-freestyle-vms-to-vercel-sandbox"
---

To move sandbox workloads from [Freestyle VMs](https://www.freestyle.sh/docs/vms) to [Vercel Sandbox](https://vercel.com/docs/sandbox), update your application's VM calls to use Vercel's TypeScript SDK. Adapt snapshot setup, file persistence, and firewall rules to preserve the behavior your application needs. Review the [migration limitations](#what-doesn%27t-map-from-freestyle-vms) before starting if your application relies on pauses that preserve memory, VMs that run for days, custom domains, or private networks.

Freestyle pauses preserve memory and running processes, and traffic can wake a VM paused by its idle timeout. Vercel preserves files when a persistent sandbox stops, so your application resumes it by name and restarts its processes. Vercel allows outbound traffic by default, while Freestyle requires an allow rule.

You can use Vercel Sandbox from an application on any host. Your backend connects through the SDK using [Vercel credentials](https://vercel.com/docs/sandbox/concepts/authentication), while sandboxed code runs on Vercel's infrastructure. Your application can stay with its current hosting provider.

## Prerequisites

Before you begin, make sure you have a [Vercel account](https://vercel.com/signup) ready. For local development, use Node.js 24+ (or Python 3.11+) and the latest [Vercel CLI](https://vercel.com/docs/cli).

## Migrate with your agent

Use this prompt in your application's repository to have a coding agent check where Freestyle is used and prepare the migration:

### Agent prompt

```txt
Migrate this codebase from Freestyle VMs to Vercel Sandbox.

1. Read and follow the migration guide using the Vercel CLI: `npx vercel@latest kb inspect migrate-from-freestyle-vms-to-vercel-sandbox`.
2. Inventory Freestyle imports and call sites, including snapshots, commands, files, PTY sessions, pauses, lifecycle fields, slugs, domains, firewall rules, TLS rules, identities, private networks, and resizes. Note whether each call site uses version 0.1 or 0.2 of the `freestyle` package. Preserve the application's language and authorization checks.
3. Identify features that need a different design, including pauses, snapshots, and forks that keep memory, VMs that run longer than one session, idle timeouts, wake on traffic, services that start at boot, custom domains, forward auth, private networks and tunnels, port-level firewall rules, SSH access, interactive PTY sessions, identity tokens, live resizes, disks larger than 64 GB, nested virtualization, and GPUs. Ask for a decision only where that choice blocks implementation.
4. Keep both providers behind one application module. Select the provider for each new agent session and retain that choice for the session's lifetime. Keep the Freestyle path available until I approve cutover.
5. Port one call site at a time. Check shell usage, working directories, exit-code handling, session and command timeouts, time units, paths, users, default network access, cleanup, and persistence against the guide and the SDK reference: https://vercel.com/docs/sandbox/sdk/javascript
6. Plan how to stop writes, export and verify files, and reconcile changes if we roll back. Do not delete Freestyle VMs, snapshots, or rules, and do not revoke credentials.
7. Run local checks first. Describe any live test and the resources it creates before running it. Report the results, remaining configuration, and cutover plan. Do not switch production traffic without my approval.
```

## How Freestyle VMs features map to Vercel Sandbox

Replace Freestyle accounts with Vercel projects, rebuild snapshots as images, and use persistent sandboxes for saved files. Pauses that keep memory and custom domains require a [different approach](#what-doesn%27t-map-from-freestyle-vms). To assess the workload before migrating, [compare Vercel Sandbox and Freestyle VMs](https://vercel.com/kb/guide/vercel-sandbox-vs-freestyle-vms).

Freestyle documents a TypeScript SDK, and the mappings use its version 0.2 names alongside Vercel's TypeScript API. For the 0.1 names, use the translation in [step 1](#translate-sdk-0.1-names). If your backend calls its REST API from Python, use Vercel's [Python SDK](https://vercel.com/docs/sandbox/sdk/python), whose names differ from those below. For example, it uses `execution_time_limit` instead of `timeout` and has no resume hook.

Both products have Hobby and Pro plans with different limits. Plan names in this guide refer to Vercel unless the sentence names Freestyle.

### Projects, images, and compute

Replace the Freestyle account and its API key with a Vercel project, and select an image in place of a snapshot.

| Freestyle VMs                                                                                                        | Vercel Sandbox                                                                                                                             | What you change                                                                                                                                            |
| -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Account or team, selected by its API key                                                                             | Vercel project                                                                                                                             | Each sandbox belongs to the project that issued its credentials.                                                                                           |
| API key in `FREESTYLE_API_KEY`                                                                                       | [OIDC token](https://vercel.com/docs/sandbox/concepts/authentication) in `VERCEL_OIDC_TOKEN`, or an access token with team and project IDs | Run `vercel link` and `vercel env pull` for local development.                                                                                             |
| [Base snapshot](https://www.freestyle.sh/docs/vms/base-snapshots) such as `freestyle/ubuntu`, passed as `snapshotId` | [Managed image](https://vercel.com/docs/sandbox/concepts/images), passed as `image`                                                        | Freestyle's Ubuntu snapshots run Ubuntu 24.04. Vercel's managed images run Ubuntu 26.04 or Arch Linux, so check the tools and versions your commands need. |
| Custom snapshot from `vm.snapshot()`, which holds disk and memory                                                    | Custom OCI image in Vercel Container Registry                                                                                              | Build custom images from a Dockerfile. Vercel Sandbox doesn't run an image's `ENTRYPOINT` or `CMD`, and an image holds no running processes.               |
| Size set by the snapshot, such as 4 vCPUs and 8 GiB of memory for `freestyle/ubuntu`                                 | `resources.vcpus`, with 2 GB of memory per vCPU                                                                                            | Set the size at creation. The Vercel default is 2 vCPUs, so pass `resources: { vcpus: 4 }` to match `freestyle/ubuntu`.                                    |
| `vm.resize()`, which grows CPU, memory, or disk on a running VM                                                      | `sandbox.update({ resources })`, applied to the next session                                                                               | Size for peak use, because a running Vercel sandbox has a fixed size. The disk is 64 GB.                                                                   |
| No region option                                                                                                     | `region`, with one of [19 region IDs](https://vercel.com/docs/sandbox/concepts/regions) such as `iad1`                                     | Choose the region for each sandbox, or set a project default. Snapshots and Drives stay in the region that created them.                                   |
| `vm.exec()` runs a shell string as the `ubuntu` user                                                                 | Commands run without a shell as the image's default user, which is `ubuntu` or `arch` on managed images, in `/vercel`                      | Pass the binary and an argument array. Use `bash -c` for shell syntax, `cwd` in place of a `cd` prefix, and `sudo: true` for root commands.                |
| VM ID from `vmId` or `vm.id`, or a `slug`                                                                            | Sandbox `name`                                                                                                                             | Choose a name at creation and store it in place of the ID or slug.                                                                                         |
| `metadata`, with up to 64 entries                                                                                    | Up to five `tags`                                                                                                                          | Use tags for filtering. Store additional metadata in your application database, keyed by sandbox name.                                                     |

### Lifecycle and state

Vercel saves a persistent sandbox's filesystem when it stops. Use its name to find the sandbox later and resume it from that saved state.

| Freestyle VMs                                                                                    | Vercel Sandbox                                                                                                      | What you change                                                                                                                                                                                                  |
| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| No fixed run limit. `maxRunSeconds` and `maxRunTotalSeconds` pause the VM when a budget runs out | `timeout`, extended with `extendTimeout()`                                                                          | A Vercel session ends after 5 minutes unless you set `timeout`. A session lasts up to 45 minutes on Hobby, or 24 hours on Pro and Enterprise. Freestyle's fields take seconds, and `timeout` takes milliseconds. |
| `idleTimeoutSeconds`, which pauses the VM after a period without network activity                | No equivalent                                                                                                       | Vercel Sandbox has no idle timeout, so stop the sandbox from your code. See [idle timeouts and wake on traffic](#idle-timeouts-and-wake-on-traffic).                                                             |
| `vm.pause()`, which keeps files, memory, and running processes                                   | `sandbox.stop()`, which saves files                                                                                 | Replace each `vm.pause()` with `sandbox.stop()`. After each resume, restart processes, for example with the `onResume` hook.                                                                                     |
| `vm.start()`, a `vm.fs` write, or traffic to an idle-paused VM resumes the VM                    | Resume on SDK operations such as `runCommand()`                                                                     | Requests to a stopped sandbox's URL return HTTP 410. Resume the sandbox from your backend first.                                                                                                                 |
| `freestyle.vms.ref()`, with a VM ID or slug                                                      | `Sandbox.get({ name })`                                                                                             | Look up sandboxes by name. The next command resumes a stopped sandbox.                                                                                                                                           |
| `vm.delete()`                                                                                    | `sandbox.delete()`                                                                                                  | Deleting a sandbox preserves its snapshots unless you pass `deleteOrphanSnapshots`.                                                                                                                              |
| `autoDeleteSeconds: 0`, which deletes the VM when it stops                                       | `persistent: false`                                                                                                 | Use non-persistent sandboxes for one-off work.                                                                                                                                                                   |
| `autoDeleteSeconds` and `ttlSeconds`, which delete the VM on a schedule                          | Deletion deadlines enforced by your application; `snapshotExpiration` for saved files                               | Snapshot expiration and sandbox deletion are separate policies. Step 7 maps each lifecycle field.                                                                                                                |
| `vm.snapshot()`, then `freestyle.vms.create({ snapshotId })`                                     | `sandbox.snapshot()`, then a snapshot `source`, or `Sandbox.fork()`                                                 | `snapshot()` stops the session, and a snapshot holds files only. Start processes in each new sandbox.                                                                                                            |
| Files on each VM's own disk                                                                      | The sandbox's filesystem, or [Drives](https://vercel.com/docs/sandbox/concepts/drives), up to four for each sandbox | Use a Drive for files that several sandboxes read, or that exceed the 64 GB disk. Each Drive allows one writable mount at a time.                                                                                |
| PTY sessions from `vm.pty.open()`                                                                | `runCommand()` with `detached: true`, or `sandbox.openInteractive()`                                                | Use a detached command for a background process and an interactive session for a terminal.                                                                                                                       |

### Networking and secrets

The firewall's `networkPolicy` option replaces Freestyle's firewall rules and outbound TLS rules, and public port URLs replace domains.

| Freestyle VMs                                                                | Vercel Sandbox                                                                                                                              | What you change                                                                                                                                                                                  |
| ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| No network access until a rule allows it. `firewall` is required at creation | `'allow-all'` by default                                                                                                                    | Set `networkPolicy` on every sandbox whose VM had restricted rules.                                                                                                                              |
| `firewall: { rules: [] }` with no outbound TLS rules                         | `networkPolicy: 'deny-all'`                                                                                                                 | `deny-all` also blocks DNS.                                                                                                                                                                      |
| Firewall rule from the VM to `{ public: true }`                              | `'allow-all'`, the default                                                                                                                  | Remove the rule.                                                                                                                                                                                 |
| Outbound TLS rules that allow named domains                                  | `networkPolicy: { allow: [...] }`                                                                                                           | Neither product's `*.example.com` matches `example.com`, so list the apex separately. A Freestyle wildcard matches one label, and a Vercel wildcard matches subdomains at any depth.             |
| Firewall rules with a `cidr`, `port`, or `protocol`                          | `networkPolicy: { subnets: { allow: [...] } }`                                                                                              | Vercel policies match domains and CIDR ranges, without port or protocol matching. Denied CIDR ranges take precedence over allowed domains and ranges.                                            |
| `freestyle.firewall.rules.create()` and `delete()` on an existing VM         | `sandbox.update({ networkPolicy })`                                                                                                         | Each update replaces the whole policy.                                                                                                                                                           |
| `env` on each `vm.exec()` call                                               | `env`, at creation or for each command                                                                                                      | Set shared values once at creation.                                                                                                                                                              |
| TLS rule `transform` that adds headers                                       | [Brokering rules](https://vercel.com/docs/sandbox/concepts/firewall) with `transform`                                                       | Rules match on path, method, query, and headers, and work together with an allow list.                                                                                                           |
| Inbound TLS rule that routes a `style.dev` or custom domain to a guest port  | `ports` and `sandbox.domain(port)`                                                                                                          | List up to 15 ports at creation, or change them with `sandbox.update({ ports })`. Each port gets a generated URL.                                                                                |
| `forwardAuth` on an inbound rule                                             | No equivalent                                                                                                                               | Anyone with a port's URL can reach it. Authenticate callers in the server that runs inside the sandbox. See [custom domains and authenticated access](#custom-domains-and-authenticated-access). |
| Private networks in `vpcs`, for traffic between VMs                          | No equivalent                                                                                                                               | Sandboxes reach each other through public port URLs. Authenticate requests between them.                                                                                                         |
| WireGuard tunnels to your own network                                        | [Secure Compute](https://vercel.com/docs/sandbox/concepts/secure-compute) network, set with `networkId`, or a VPN client inside the sandbox | Secure Compute is an additional Enterprise purchase.                                                                                                                                             |
| `freestyle vm ssh`                                                           | `sandbox connect` in the Sandbox CLI                                                                                                        | Vercel provides a terminal session without an SSH server.                                                                                                                                        |
| Identity tokens that let a user's client run commands in one VM              | No equivalent                                                                                                                               | Route each user's commands through your backend. See [SSH, PTY sessions, and identity tokens](#ssh,-pty-sessions,-and-identity-tokens).                                                          |

## Steps

### 1\. Find where your application uses Freestyle VMs

Find Freestyle imports, call sites, and environment variables, then trace aliases through your code and map each use to a migration step or replacement.

```bash
grep -rnE \
  -e "['\"](freestyle|freestyle-sandboxes|@freestyle-sh/[a-z-]+)['\"]" \
  -e 'FREESTYLE_[A-Z_]+|freestyle\.sh|\.style\.dev' \
  --include="*.ts" --include="*.tsx" \
  --include="*.mts" --include="*.cts" \
  --include="*.js" --include="*.jsx" \
  --include="*.mjs" --include="*.cjs" \
  --exclude-dir=node_modules .
```

The search covers JavaScript and TypeScript, including older `freestyle-sandboxes` and `@freestyle-sh/with-*` imports. If other services call Freestyle's REST API, search their files for `api.freestyle.sh` and `FREESTYLE_API_KEY` too.

Check `.env` files and `package.json` for `FREESTYLE_API_KEY` and the `freestyle` dependency, then inspect scripts and CI jobs for `freestyle vm`, `freestyle snapshot`, `freestyle firewall`, and `freestyle tls` commands. Use the findings to choose the relevant migration steps:

| In your code                                                                                                         | Go to                                                                                 |
| -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| `snapshotId`, `vm.snapshot()`, or `freestyle snapshot create`                                                        | [Step 4](#4.-move-your-freestyle-snapshot-to-a-vercel-image)                          |
| `freestyle.vms.create()`, `vm.exec()`, `vm.fs`, or `vm.pty.open()` with an `exec` command                            | [Step 5](#5.-replace-vm-creation,-commands,-and-file-operations)                      |
| `vm.pause()`, `vm.start()`, `freestyle.vms.ref()`, or a snapshot that copies a VM                                    | [Step 6](#6.-replace-pause-and-resume-with-named-sandboxes)                           |
| `idleTimeoutSeconds`, `maxRunSeconds`, `maxRunTotalSeconds`, `ttlSeconds`, or `autoDeleteSeconds`                    | [Step 7](#7.-replace-lifecycle-fields-with-session-timeouts)                          |
| Inbound TLS rules, `style.dev` domains, or `freestyle.domains`                                                       | [Step 8](#8.-replace-domains-with-public-ports)                                       |
| `firewall` rules, outbound TLS rules, or `env` on `vm.exec()`                                                        | [Step 9](#9.-replace-firewall-rules,-environment-variables,-and-credential-injection) |
| Interactive `vm.pty` terminals, `vm.resize()`, `vpcs`, `freestyle.tunnels`, `freestyle.identities`, or `forwardAuth` | [What doesn't map from Freestyle VMs](#what-doesn%27t-map-from-freestyle-vms)         |

#### Translate SDK 0.1 names

The `freestyle` package has two incompatible generations, and this guide maps the 0.2 names. Check the `freestyle` version in `package.json` or your lockfile to see which generation your code uses. Code that uses `VmSpec` or installs `@freestyle-sh/with-*` packages runs on 0.1. Translate these common 0.1 names:

| SDK 0.1                                                                               | SDK 0.2                                         | Vercel Sandbox                                                    |
| ------------------------------------------------------------------------------------- | ----------------------------------------------- | ----------------------------------------------------------------- |
| `VmSpec`, `VmTemplate`, `snapshots.ensure()`, and `@freestyle-sh/with-*` integrations | Set up a VM, then call `vm.snapshot()`          | A managed or custom image                                         |
| `vcpuCount`, `memSizeGb`, and `rootfsSizeGb`                                          | The snapshot's size, then `vm.resize()`         | `resources: { vcpus }`                                            |
| `workdir`                                                                             | A `cd` prefix in the command                    | `cwd`                                                             |
| `aptDeps`                                                                             | `apt-get` through `vm.exec()`                   | A `RUN` instruction in a Dockerfile                               |
| `additionalFiles`                                                                     | `vm.fs.writeTextFile()`                         | `writeFiles()`                                                    |
| `gitRepos`                                                                            | `git clone` through `vm.exec()`                 | A `git` source at creation                                        |
| `systemd.services`                                                                    | A unit file and `systemctl` through `vm.exec()` | A detached `runCommand()` in `onCreate` and `onResume`            |
| `persistence: { type: "ephemeral" }`                                                  | `autoDeleteSeconds: 0`                          | `persistent: false`                                               |
| `vm.vmId`                                                                             | `vm.id`                                         | The sandbox `name`                                                |
| `freestyle.vms.ref({ vmId })`                                                         | `freestyle.vms.ref(idOrSlug)`                   | `Sandbox.get({ name })`                                           |
| `vm.getInfo()`                                                                        | `vm.data()`                                     | `Sandbox.get({ name })`, then properties such as `sandbox.status` |
| `vm.user()`                                                                           | `vm.linuxUser()`                                | `sudo: true` for root, or `sandbox.createUser()`                  |
| `vm.suspend()`                                                                        | `vm.pause()`                                    | `sandbox.stop()`                                                  |
| `vm.stop()` and `vm.kill()`                                                           | A power-off inside the guest                    | `sandbox.stop()`                                                  |
| `vm.fork()`                                                                           | `vm.snapshot()`, then `freestyle.vms.create()`  | `Sandbox.fork()`                                                  |
| `ports`, `domains`, and `freestyle.domains.mappings`                                  | Inbound TLS rules                               | `ports` and `sandbox.domain()`                                    |

The 0.1 package also includes clients for Freestyle Git, serverless deployments, cron, and DNS. This guide covers VMs only, so plan those migrations separately.

### 2\. Link a Vercel project and authenticate

Vercel Sandbox supports OpenID Connect (OIDC) tokens and access tokens. Link your local directory to the project that will own your sandboxes:

```bash
vercel link
```

Save the environment variables and development OIDC token to `.env.local`:

```bash
vercel env pull
```

Load `.env.local` for local runs with Node.js's `--env-file=.env.local` option. Add `FREESTYLE_API_KEY` to the same file while both providers are in use, because the Freestyle SDK reads it from the process environment. The development OIDC token expires after 12 hours; run `vercel env pull` again to refresh it. Applications deployed on Vercel receive automatically managed tokens.

#### Authenticate a backend hosted elsewhere

For a backend hosted elsewhere, create a [Vercel access token](https://vercel.com/docs/rest-api#creating-an-access-token) and copy your [team ID](https://vercel.com/docs/accounts#find-your-team-id) and [project ID](https://vercel.com/docs/project-configuration/general-settings#project-id). Save them as environment variables and pass them to the SDK:

```javascript
const sandbox = await Sandbox.create({
  token: process.env.VERCEL_TOKEN,
  teamId: process.env.VERCEL_TEAM_ID,
  projectId: process.env.VERCEL_PROJECT_ID,
});
```

Keep your Freestyle API key until the migrated workloads pass verification. Retain keys used by workloads remaining on Freestyle.

### 3\. Install the Vercel Sandbox SDK

Install `@vercel/sandbox` for TypeScript and JavaScript:

**pnpm**

```bash
pnpm i @vercel/sandbox
```

**npm**

```bash
npm i @vercel/sandbox
```

**yarn**

```bash
yarn add @vercel/sandbox
```

**bun**

```bash
bun add @vercel/sandbox
```

Keep the `freestyle` package until no workloads use it.

### 4\. Move your Freestyle snapshot to a Vercel image

Replace your Freestyle snapshot with a Vercel [managed image](https://vercel.com/docs/sandbox/concepts/images) or a custom image in Vercel Container Registry. Choose based on the snapshot your VMs start from:

| Freestyle snapshot                                                                         | Vercel replacement                                                                                                                                                                                    |
| ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `freestyle/ubuntu` or another Ubuntu base snapshot, used for its Node.js or Python runtime | A managed image such as `vercel/sandbox/node:24` or `vercel/sandbox/python:3.14`. With no `image`, a sandbox uses `vercel/sandbox/universal`, which includes current Node.js LTS and Python versions. |
| Preinstalled tools that your commands call, such as Docker, Bun, or uv                     | A managed image if it includes them, or a Dockerfile that installs them, built into Vercel Container Registry                                                                                         |
| A custom snapshot taken with `vm.snapshot()` after setup commands                          | A Dockerfile with the matching `RUN` instructions, built into Vercel Container Registry                                                                                                               |
| A snapshot built with `freestyle snapshot create --script`                                 | The same script in a Dockerfile `RUN` instruction, built into Vercel Container Registry                                                                                                               |

#### Build a custom image

If a managed image meets your needs, continue to [sandbox creation](#5.-replace-vm-creation,-commands,-and-file-operations). For a custom image, install Docker and put the snapshot's setup commands in a Dockerfile. Target `linux/amd64` and stay within the registry limits of 15 GB per image and 2 GB per compressed layer:

```docker
FROM node:24-slim
RUN apt-get update && apt-get install -y git
RUN npm install -g pnpm
WORKDIR /workspace
```

Log in, then build and push the image from the linked project:

```bash
vercel vcr login docker
vercel vcr build docker . agent-runtime:latest --push
```

Wait for **Ready** on the registry repository's details page before creating a sandbox. Creation fails with `image_not_ready` while the image is being prepared. Pass the repository and tag as `image`:

```javascript
const sandbox = await Sandbox.create({ image: 'agent-runtime:latest' });
```

#### Start processes and choose resources

Freestyle snapshots hold memory, so a VM created from one starts with its captured processes running. Vercel images hold files, and Sandbox doesn't run their `ENTRYPOINT` or `CMD`. Start the processes with `runCommand()` after creation. Commands in a custom image use its Dockerfile `WORKDIR`, or `/` when none is set; managed images use `/vercel`.

Set `resources.vcpus` at creation to match the size that your Freestyle snapshot supplied. The `freestyle/ubuntu-sm` and `freestyle/ubuntu` snapshots match 2 and 4 vCPUs. The 8 vCPUs in `freestyle/ubuntu-lg` require Vercel Pro, while the 16 and 32 vCPUs in `freestyle/ubuntu-xl` and `freestyle/ubuntu-2xl` require Enterprise.

For an Ubuntu-based managed image, update the package index before installing packages with `apt-get` and `sudo`:

```javascript
await sandbox.runCommand({ cmd: 'apt-get', args: ['update'], sudo: true });
await sandbox.runCommand({
  cmd: 'apt-get',
  args: ['install', '-y', 'git'],
  sudo: true,
});
```

Installed packages remain across persistent sessions. Use the package manager supplied by your image when running Arch or a custom image.

### 5\. Replace VM creation, commands, and file operations

Replace Freestyle's creation, command, and file calls with the corresponding Vercel methods. `Sandbox.create()` uses project credentials and an image reference instead of an API key and a snapshot ID.

Route every sandbox operation through one module in your application, and add a flag that selects Freestyle or Vercel for each new agent session. Add the Vercel calls beside the Freestyle calls, and keep the Freestyle path until step 10.

#### TypeScript SDK calls

| Task                            | Freestyle VMs                                            | Vercel Sandbox                                                                                                                                     |
| ------------------------------- | -------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| Import                          | `Freestyle` from `freestyle`                             | `Sandbox` from `@vercel/sandbox`                                                                                                                   |
| Create a client                 | `new Freestyle()`                                        | No client object                                                                                                                                   |
| Create a VM or sandbox          | `freestyle.vms.create({ firewall })`                     | `Sandbox.create()`                                                                                                                                 |
| Choose the starting environment | `snapshotId`                                             | `image`, or a snapshot `source`                                                                                                                    |
| Set the lifetime                | `maxRunSeconds`, in seconds                              | `timeout`, in milliseconds                                                                                                                         |
| Set resources                   | The snapshot's size, then `vm.resize()`                  | `resources: { vcpus }`                                                                                                                             |
| Set environment variables       | `env` on each `vm.exec()` call                           | `env`, at creation or for each command                                                                                                             |
| Run a command                   | `vm.exec("python3 main.py")`                             | `sandbox.runCommand('python', ['main.py'])`                                                                                                        |
| Set the working directory       | A `cd` prefix in the command string                      | `cwd`                                                                                                                                              |
| Run as root                     | `linuxUser: "root"`                                      | `sudo: true`                                                                                                                                       |
| Read output                     | `result.stdout`                                          | `await result.stdout()`                                                                                                                            |
| Get the exit code               | `result.statusCode`                                      | `result.exitCode`                                                                                                                                  |
| Run in the background           | `vm.pty.open()`, then `detach()`                         | `runCommand()` with `detached: true`                                                                                                               |
| Write a file                    | `vm.fs.writeTextFile(path, text, { mode })`              | `sandbox.writeFiles([{ path, content, mode }])`                                                                                                    |
| Read a file                     | `vm.fs.readTextFile(path)`                               | `sandbox.fs.readFile(path, 'utf8')`, or `sandbox.readFileToBuffer({ path })` for bytes                                                             |
| List, create, or remove paths   | `vm.fs.readDir()`, `vm.fs.mkdir()`, and `vm.fs.remove()` | `sandbox.fs.readdir(path, { withFileTypes: true })`, `sandbox.fs.mkdir(path, { recursive: true })`, and `sandbox.fs.rm(path, { recursive: true })` |
| Find a VM or sandbox            | `freestyle.vms.ref(idOrSlug)`                            | `Sandbox.get({ name })`                                                                                                                            |
| List VMs or sandboxes           | `freestyle.vms.list({ metadata })`                       | `Sandbox.list({ tags })`, which filters on one tag                                                                                                 |
| End a VM or sandbox             | `vm.pause()` or `vm.delete()`                            | `sandbox.stop()` or `sandbox.delete()`                                                                                                             |

On Freestyle, a script creates a VM from the default `freestyle/ubuntu` snapshot, allows outbound access, and passes each command as one string:

```javascript
import { Freestyle } from "freestyle";

const freestyle = new Freestyle();

const { vm } = await freestyle.vms.create({
  maxRunSeconds: 10 * 60,
  // Allow outbound internet access for this VM.
  firewall: {
    rules: [
      {
        action: "allow",
        source: {},
        destination: { public: true },
      },
    ],
  },
});

try {
  await vm.fs.writeTextFile("/tmp/main.py", "print(21 * 2)", { mode: 0o644 });

  const result = await vm.exec({
    command: "cd /tmp && python3 main.py",
    env: { PYTHONUNBUFFERED: "1" },
    timeoutMs: 60_000,
  });
  console.log(result.stdout);
  console.log("exit code", result.statusCode);
} finally {
  await vm.delete();
}
```

The Vercel version runs the same Python script in a disposable sandbox:

```javascript
import { Sandbox } from '@vercel/sandbox';

const sandbox = await Sandbox.create({
  timeout: 10 * 60 * 1000,
  resources: { vcpus: 2 },
  env: { PYTHONUNBUFFERED: '1' },
  persistent: false,
});

try {
  await sandbox.writeFiles([
    { path: 'main.py', content: Buffer.from('print(21 * 2)') },
  ]);

  const result = await sandbox.runCommand({
    cmd: 'python',
    args: ['main.py'],
    timeoutMs: 60_000,
  });
  console.log(await result.stdout());
  console.log('exit code', result.exitCode);
} finally {
  await sandbox.stop();
}
```

The Vercel script uses the default image with 2 vCPUs and 4 GB of memory. Freestyle's default `freestyle/ubuntu` snapshot has 4 vCPUs and 8 GiB, so pass `resources: { vcpus: 4 }` if your workload needs that size. Choose the size for peak CPU and memory use, and keep `persistent: false` for disposable runs.

Save the Vercel script as `sandbox.mjs`, then run it with the environment file loaded:

```bash
node --env-file=.env.local sandbox.mjs
```

The script prints `42` and `exit code 0`, then stops the sandbox.

#### Differences to check in every call

Freestyle's `vm.exec()` passes one string to the guest's shell. Vercel takes a binary and argument array, so use `bash -c` for pipes, redirection, or variable expansion, or `bash -lc` to load the login shell's profile. Because `vm.exec()` has no working-directory option, Freestyle commands use a `cd` prefix to change directories. Replace those prefixes with `cwd` in `runCommand()`.

Freestyle's `vm.fs` requires absolute paths, while Vercel managed images resolve relative paths from `/vercel`. Update commands, system prompts, and tool descriptions accordingly. Both Freestyle's Ubuntu snapshots and Vercel's managed images run commands as a non-root user with passwordless sudo. Replace `linuxUser: "root"` and `vm.linuxUser("root")` with `sudo: true`, or create another Linux user with `sandbox.createUser()`.

Freestyle returns `stdout` and `stderr` as strings; Vercel exposes asynchronous `stdout()` and `stderr()` methods. Keep your error checks and rename `statusCode` to `exitCode`, because neither SDK throws for a non-zero exit code.

#### Set command and session timeouts

Freestyle's lifecycle fields take seconds, but `timeoutMs` on `vm.exec()` takes milliseconds. Vercel's `timeout`, `timeoutMs`, and `extendTimeout()` all take milliseconds. Convert lifecycle values when copying them into the Vercel calls.

Set command limits separately from the session timeout. The Freestyle SDK ends a command after 30 seconds unless you set `timeoutMs`; Vercel has no default command limit. Pass `timeoutMs` for commands that must finish before the session ends. Vercel sessions stop after 5 minutes unless you set `timeout`, whereas a Freestyle VM runs until you pause or delete it unless `maxRunSeconds` is set.

#### Keep lookups and creation policies consistent

Freestyle generates a VM ID and accepts an optional `slug`. On Vercel, set or read the sandbox's `name` at creation and store it for lookups. Check the creation options before routing work to that name:

- Set `networkPolicy` to preserve restricted access, as shown in step 9. Freestyle grants access through rules; Vercel allows all outbound traffic by default.
  
- Use `persistent: false` for disposable runs. Vercel sandboxes are persistent by default, and every stop saves a snapshot that counts toward Snapshot Storage. Freestyle keeps the VM and disk until you or a lifecycle field deletes it, subject to unused-VM retention limits on some plans.
  

#### Background commands and streamed output

`vm.exec()` returns its output after the command ends, so Freestyle applications open a PTY session for streamed output or a long-running process. The session's `onData` callback receives output while the command runs:

```javascript
const session = await vm.pty.open({
  exec: "for i in 1 2 3; do echo $i; sleep 1; done",
  slug: "count",
  onData: (bytes) => process.stdout.write(bytes),
  onExit: (code) => console.log("exit code", code),
});
```

On Vercel, `runCommand()` with `detached: true` returns when the command starts, and `command.logs()` streams its output:

```javascript
const command = await sandbox.runCommand({
  cmd: 'bash',
  args: ['-c', 'for i in 1 2 3; do echo $i; sleep 1; done'],
  detached: true,
});

for await (const line of command.logs()) {
  process.stdout.write(line.data);
}

const finished = await command.wait();
console.log('exit code', finished.exitCode);
```

Freestyle PTYs merge stdout and stderr, while Vercel's `stream` field identifies each log line's source. Store `command.cmdId` to reconnect with `sandbox.getCommand()` in the current session, replacing the slug used by `vm.pty.attach()`. Command IDs cannot reconnect to processes after a resume.

Connections close after 340 seconds without data while the command keeps running. Use the [long-running task pattern](https://vercel.com/docs/sandbox/examples/execute-long-running-tasks) for longer, quiet jobs.

### 6\. Replace pause and resume with named sandboxes

Use a named persistent sandbox in place of pausing a Freestyle VM and tracking its ID for each agent session.

#### Reconnect to a sandbox by name

On Freestyle, your application pauses the VM when an agent session ends, stores the VM ID, and starts that VM to resume it. The excerpt assumes that `vmStore` is your application's persistent mapping of session IDs to VM IDs, and that `vm` and `sessionId` identify the current session.

```javascript
// End of an agent session
await vm.fs.writeTextFile("/home/ubuntu/notes.txt", "draft");
await vm.pause();
await vmStore.set(sessionId, vm.id);

// Next agent session
const resumed = freestyle.vms.ref(await vmStore.get(sessionId));
await resumed.start();
console.log(await resumed.fs.readTextFile("/home/ubuntu/notes.txt"));
```

The same replacement applies when `maxRunSeconds` pauses a Freestyle VM at its run budget. Persistent Vercel sandboxes save files both on timeout and when your code stops them. They don't stop when idle, so replace `idleTimeoutSeconds` with the activity tracking under [idle timeouts and wake on traffic](#idle-timeouts-and-wake-on-traffic).

Give each sandbox a name derived from the agent session, and keep the session associated with that name and provider while both providers are in use. Names are unique within a Vercel project and can't change. Stopping a sandbox saves its files, and a later file or command operation resumes it from that snapshot:

```javascript
// End of an agent session
const sandbox = await Sandbox.getOrCreate({ name: `session-${sessionId}` });
await sandbox.writeFiles([
  { path: 'notes.txt', content: Buffer.from('draft') },
]);
await sandbox.stop();

// Next agent session
const resumed = await Sandbox.get({ name: `session-${sessionId}` });
const result = await resumed.runCommand('cat', ['notes.txt']);
console.log(await result.stdout());
```

The command resumes the sandbox and prints `draft`. Each resume starts a new session with a new timeout, including when a file read triggers it. Freestyle's `vm.fs` can read a paused VM without starting it; on Vercel, cache file listings in your application if you need to display them without resuming the sandbox.

#### Retain saved sessions and handle missing state

Freestyle keeps a paused VM until you or a lifecycle field deletes it, subject to unused-VM retention limits on some plans. Vercel snapshots expire 30 days after last use by default. Set `snapshotExpiration` in milliseconds to match your retention policy, or use `0` to disable expiry. Deleting a sandbox preserves its snapshots unless you enable `deleteOrphanSnapshots` in `sandbox.delete()`; that option removes snapshots no other sandbox uses.

With `resume: true`, `Sandbox.getOrCreate()` recreates a sandbox whose saved snapshot is missing. Initialize or restore the replacement in `onCreate`. If missing session state must fail the request, use `Sandbox.get()` and handle the resume error before accepting more work.

#### Restart processes after a resume

Freestyle pauses keep memory and running processes. Vercel restores only files, so use lifecycle hooks to restart your server when requesting a resume:

```javascript
import { Sandbox } from '@vercel/sandbox';

const sessionId = 'your-session-id';

async function startServer(sandbox) {
  await sandbox.runCommand({
    cmd: 'python',
    args: ['-m', 'http.server', '8000'],
    detached: true,
  });
}

const sandbox = await Sandbox.getOrCreate({
  name: `session-${sessionId}`,
  ports: [8000],
  resume: true,
  onCreate: startServer,
  onResume: startServer,
});

// Check service readiness before sending application traffic.
```

`onCreate` starts the server for a new sandbox. With `resume: true`, an existing stopped sandbox resumes and `getOrCreate()` waits for `onResume` before returning. Check your service's readiness before sending traffic because the detached command can return before the server accepts connections. `onResume` is a callback in your process, so pass it on every `Sandbox.get()` and `Sandbox.getOrCreate()` call that can resume the sandbox.

#### Start many sandboxes from one snapshot

On Freestyle, `vm.snapshot()` returns a `snapshotId` that you pass to `freestyle.vms.create()`, and each new VM starts with the snapshot's processes running. To start many Vercel sandboxes from one prepared environment, take a snapshot and pass its ID as the `source`:

```javascript
const base = await Sandbox.create({
  name: 'base-environment',
  timeout: 15 * 60 * 1000,
  source: {
    type: 'git',
    url: 'https://github.com/your-org/your-repo.git',
    depth: 1,
  },
});
const install = await base.runCommand({
  cmd: 'npm',
  args: ['install'],
  cwd: 'your-repo',
});
if (install.exitCode !== 0) {
  const error = await install.stderr();
  await base.stop();
  throw new Error(error || `npm install exited with ${install.exitCode}`);
}

const snapshot = await base.snapshot();

const worker = await Sandbox.create({
  source: { type: 'snapshot', snapshotId: snapshot.snapshotId },
});
```

The `git` source clones into a directory named after the repository, so the install command sets `cwd`. Calling `base.snapshot()` saves files and stops the session. To fork its latest snapshot, pass the sandbox's name as `sourceSandbox` to `Sandbox.fork()`. Stop or snapshot a running source first, because a fork excludes unsaved changes. Snapshots and forks contain no process memory, so start the processes each new sandbox needs.

Create new sandboxes where the snapshot is available. Configured [failover](https://vercel.com/docs/sandbox/concepts/regions#failover-regions) can load it elsewhere when Vercel cannot provision capacity in the main region.

#### Copy files from paused VMs and snapshots

Vercel Sandbox can't read a Freestyle VM or snapshot directly. Archive the files on Freestyle and download them before importing into Vercel. Use `freestyle.vms.list()` with a `state` filter to find sessions missing from your application's store. The export script uses your `vmStore` and `sessionId`; set `sourceDir` to the directory to migrate, shown here as `/home/ubuntu/workspace`. Rebuild system packages in step 4.

Export only paused or idle sessions with enough free disk space for the compressed archive. Starting a paused VM resumes its processes, so keep application writers stopped until the archive is complete. The script runs `tar` as root to include files written by `vm.fs` and splits the archive into 8 GiB parts, below Freestyle's 16 GiB per-file limit.

```javascript
import { createWriteStream } from 'node:fs';
import { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { Freestyle } from 'freestyle';

const freestyle = new Freestyle();
const vm = freestyle.vms.ref(await vmStore.get(sessionId));
const sourceDir = '/home/ubuntu/workspace';
const quote = (value) => "'" + value.replaceAll("'", "'\\''") + "'";

const { state } = await vm.data();
const startedHere = state !== 'running';
if (startedHere) await vm.start();

try {
  const directory = await vm.exec({
    command: 'mktemp -d /tmp/freestyle-export.XXXXXX',
    linuxUser: 'root',
  });
  if (directory.statusCode !== 0 || !directory.stdout?.trim()) {
    throw new Error(directory.stderr || 'Could not create export directory');
  }
  const exportDir = directory.stdout.trim();
  const archiveCommand =
    `tar -czf - -C ${quote(sourceDir)} . | ` +
    `split -b 8G -d -a 4 - ${quote(exportDir + '/part-')}`;
  const result = await vm.exec({
    command: `bash -o pipefail -c ${quote(archiveCommand)}`,
    linuxUser: 'root',
    timeoutMs: 300_000,
  });
  if (result.statusCode !== 0) {
    throw new Error(result.stderr || 'Archive creation failed');
  }

  const parts = (await vm.fs.readDir(exportDir))
    .map((entry) => entry.name)
    .filter((name) => /^part-\d{4}$/.test(name))
    .sort();
  if (parts.length === 0) throw new Error('No archive parts were created');

  for (const [index, part] of parts.entries()) {
    const stream = await vm.fs.readFileStream(`${exportDir}/${part}`);
    await pipeline(
      Readable.fromWeb(stream),
      createWriteStream('workspace.tgz', { flags: index === 0 ? 'w' : 'a' }),
    );
  }
} finally {
  if (startedHere) await vm.pause();
}
```

The script joins downloaded parts into `workspace.tgz` locally. If it started the VM, `finally` pauses it again, preserving files and memory until cutover. Keep temporary export parts until you've verified the imported files.

The archive command raises the SDK's 30-second default to 5 minutes. Freestyle's docs limit one `vm.exec()` call to 5 minutes; if archiving takes longer, use a PTY session and wait for successful completion before downloading the parts.

#### Use the CLI or recover a snapshot

- Copy a directory from a paused VM with `freestyle vm scp` when you don't need file modes preserved. The CLI doesn't start the VM. Prefer the archive for workspaces containing scripts or symlinks.
  
- Recover a snapshot by creating a temporary VM with `freestyle.vms.create()`. Pass the snapshot's ID as `snapshotId` and an empty array for `firewall.rules`, then use the returned VM in place of the export script's `vmStore` lookup. Delete the temporary VM with `vm.delete()` after exporting.
  

#### Import session files into Vercel

Install the [Sandbox CLI](https://vercel.com/docs/sandbox/sdk/cli) for the file transfer. The yarn command requires Yarn Classic; choose the npm command if you use modern Yarn:

**pnpm**

```bash
pnpm add --global sandbox
```

**yarn**

```bash
yarn global add sandbox
```

**npm**

```bash
npm install --global sandbox
```

**bun**

```bash
bun add --global sandbox
```

Save the commands below as `import-session.sh`. Before running them, configure `sandbox create` for the imported session:

- Set the image, resources, and public ports your application needs. For a custom image, add `--image agent-runtime:latest` and extract into its working directory. `Sandbox.getOrCreate()` ignores creation options when the name already exists, so supply them at import time.
  
- The import command allows all outbound traffic by default. If the VM had no public firewall rule, add `--network-policy deny-all` or one `--allowed-domain` flag per domain allowed by its TLS rules.
  
- Match snapshot retention to the expected idle period, or add `--snapshot-expiration none` to retain saved files indefinitely.
  

Run `bash import-session.sh` from the linked project, or select a project with `--project` and `--scope`. The script stops on an error so you can inspect an incomplete import before removing its archive or saving the session:

```bash
set -e

sandbox create --name session-123 --timeout 30m
sandbox copy ./workspace.tgz session-123:/vercel/workspace.tgz
sandbox exec session-123 -- tar -xzf /vercel/workspace.tgz -C /vercel
sandbox exec session-123 -- rm /vercel/workspace.tgz
sandbox stop session-123
```

Verify the imported files and start the processes your application needs. Memory and running processes don't transfer.

### 7\. Replace lifecycle fields with session timeouts

Freestyle pauses or deletes a VM according to the lifecycle fields you set at creation. On Vercel, the session `timeout` limits each run and `snapshotExpiration` limits retention, and your application handles the rest.

| Freestyle field      | Effect on Freestyle                                                                           | Vercel replacement                                                                                                                                                                                                                             |
| -------------------- | --------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| No lifecycle fields  | The VM runs until your code pauses or deletes it                                              | `timeout`. A session ends after 5 minutes by default, so set `timeout` on every sandbox that replaces a VM without a run limit.                                                                                                                |
| `maxRunSeconds`      | Pauses the VM after one run reaches the budget                                                | `timeout`. The session stops at the timeout and saves the sandbox's files.                                                                                                                                                                     |
| `maxRunTotalSeconds` | Pauses the VM after its total run time reaches the budget                                     | Track the remaining budget in your application, cap each new session's `timeout` and any extension to that remainder, and reject further resumes when it is spent. Reconcile usage with `totalDurationMs` from a fresh `Sandbox.get()` result. |
| `idleTimeoutSeconds` | Pauses the VM after a period without network activity                                         | No equivalent. Track activity in your application, and call `stop()` when work ends. See [idle timeouts and wake on traffic](#idle-timeouts-and-wake-on-traffic).                                                                              |
| `autoDeleteSeconds`  | Deletes the VM after it has remained paused or stopped for the period; `0` makes it ephemeral | Use `persistent: false` for `0`. For a positive idle-deletion deadline, track the last stop in your application and delete the sandbox when the deadline passes. Use `snapshotExpiration` separately to limit saved-file retention.            |
| `ttlSeconds`         | Deletes the VM a fixed time after creation                                                    | Track the creation deadline and call `sandbox.delete()` from a scheduled job, with `deleteOrphanSnapshots: true` when unused snapshots should be removed too.                                                                                  |

Freestyle's fields take seconds. Convert them to milliseconds for Vercel's `timeout`, `extendTimeout()`, and `snapshotExpiration`. Set the session and retention periods at creation, then extend or stop the session from your code:

```javascript
const sandbox = await Sandbox.create({
  name: `session-${sessionId}`,
  // Replaces maxRunSeconds: 30 * 60
  timeout: 30 * 60 * 1000,
  // Retain each automatic snapshot for 7 days after its last use
  snapshotExpiration: 7 * 24 * 60 * 60 * 1000,
});

// While work continues
await sandbox.extendTimeout(10 * 60 * 1000);

// When work ends
await sandbox.stop();
```

Freestyle pauses with memory at `maxRunSeconds`; Vercel stops at `timeout` and restores only files on resume. For previously unlimited runs, set an explicit timeout and extend it while work continues to avoid the 5-minute default.

#### Set retention and deletion deadlines separately

`snapshotExpiration` accepts `0` for no expiry, or a period from 1 day to 10 years measured from each snapshot's last use. To enforce an application deletion deadline, confirm the sandbox is no longer needed, then call `sandbox.delete()` with `deleteOrphanSnapshots: true`. Snapshots referenced by other sandboxes remain, and mounted Drives require separate cleanup.

### 8\. Replace domains with public ports

Replace the inbound TLS rule that routes a domain to a guest port with a Vercel port URL. Vercel supports HTTP and WebSocket traffic on these URLs; rules for other protocols, such as `postgres` or raw `tcp`, need a different service.

On Freestyle, an inbound TLS rule routes `my-app.style.dev` to port 8000:

```javascript
const { vm, vmId } = await freestyle.vms.create({ firewall: { rules: [] } });

const server = await vm.pty.open({
  exec: "python3 -m http.server 8000",
  slug: "server",
});
server.detach();

await freestyle.tls.rules.create({
  action: "allow",
  domain: "my-app.style.dev",
  source: { public: true },
  destination: { vmId, port: 8000 },
});

console.log("https://my-app.style.dev");
```

On Vercel, list the port at creation, start the server as a detached command, and read the port's URL:

```javascript
const sandbox = await Sandbox.create({ ports: [8000] });

await sandbox.runCommand({
  cmd: 'python',
  args: ['-m', 'http.server', '8000'],
  detached: true,
});

console.log(sandbox.domain(8000));
```

Freestyle rules can route to any guest port after startup. On Vercel, list up to 15 ports at creation and replace that list with `sandbox.update({ ports })` when needed. Read each generated `https://` URL on `vercel.run` from `sandbox.domain()` instead of constructing it from a name. This replaces the `style.dev` subdomain or verified domain you chose on Freestyle.

#### Authenticate requests and resume before sending traffic

Anyone with a port's URL can reach it. If the Freestyle service relied on forward auth, add authentication inside the sandbox server as shown under [custom domains and authenticated access](#custom-domains-and-authenticated-access).

Traffic can wake an idle-paused Freestyle VM. Stopped Vercel sandboxes return HTTP 410 without waking, so your backend must resume them with a command and restart the server before sending traffic, as shown in step 6.

### 9\. Replace firewall rules, environment variables, and credential injection

#### Map firewall rules to a network policy

Freestyle starts from no access and adds allow rules. Vercel starts from full outbound access and narrows it with `networkPolicy`. This policy controls outbound traffic; inbound traffic reaches the sandbox through the ports you list. Translate the VM's outbound rules as follows:

| Freestyle rules                                                                        | Vercel `networkPolicy`                        |
| -------------------------------------------------------------------------------------- | --------------------------------------------- |
| `firewall: { rules: [] }`, with no outbound TLS rules                                  | `'deny-all'`                                  |
| A firewall rule from the VM to `{ public: true }`                                      | `'allow-all'`, the default                    |
| Outbound TLS rules for `api.openai.com` and `github.com`, with no public firewall rule | `{ allow: ['api.openai.com', 'github.com'] }` |
| A firewall rule from the VM to `{ cidr: "203.0.113.0/24" }`                            | `{ subnets: { allow: ['203.0.113.0/24'] } }`  |

On Freestyle, an application that limits a VM to named domains creates the VM with no firewall rules and adds one outbound TLS rule for each domain:

```javascript
const { vm, vmId } = await freestyle.vms.create({ firewall: { rules: [] } });

for (const domain of ["api.openai.com", "github.com"]) {
  await freestyle.tls.rules.create({
    action: "allow",
    domain,
    source: { vmId },
    destination: { public: true },
  });
}
```

Set `networkPolicy` at creation or replace the whole policy with `update()`:

```javascript
const sandbox = await Sandbox.create({
  networkPolicy: {
    allow: ['api.openai.com', 'github.com'],
  },
});

await sandbox.update({ networkPolicy: 'deny-all' });
```

Set `networkPolicy` on every sandbox replacing a restricted VM, because outbound traffic is otherwise unrestricted. Freestyle changes individual rules; Vercel replaces the whole policy, so send it in full with each update.

Check which destinations the translated policy admits:

- On both products, list `example.com` separately from `*.example.com`. Freestyle matches one label, such as `api.example.com`; Vercel includes deeper names such as `a.b.example.com`. Use exact hostnames to narrow access.
  
- Vercel matches domains and CIDR ranges, without Freestyle's port or protocol filters. Denied CIDR ranges override allowed domains and ranges.
  
- The `subnets.allow` rules don't restrict DNS lookups, and access to private ranges requires Secure Compute.
  
- Use IP rules for plain HTTP, because Vercel matches domains by TLS hostname.
  

#### Pass environment variables

Freestyle has no VM-wide environment option, so applications pass `env` to each `vm.exec()` call or store values in a snapshot. On Vercel, pass values from your application through `env` when creating the sandbox or running a command:

```javascript
const sandbox = await Sandbox.create({
  env: { DATABASE_URL: process.env.DATABASE_URL },
});

await sandbox.runCommand({
  cmd: 'python',
  args: ['sync.py'],
  env: { API_TOKEN: process.env.API_TOKEN },
});
```

Keep secrets out of command arguments, because Vercel Sandbox can store arguments and return them in command API responses. Values that a Freestyle snapshot stores in files or systemd units don't carry over to a Vercel image, so pass them through `env` at creation.

#### Broker credentials with firewall rules

Code in the sandbox can read every value in its environment. To keep a credential outside the sandbox, replace a Freestyle TLS rule's `transform` with a brokering rule, which adds the header after the request leaves the sandbox:

**Freestyle VMs (TypeScript)**

```javascript
await freestyle.tls.rules.create({
  action: "allow",
  domain: "api.example.com",
  source: { vmId },
  destination: { public: true },
  transform: [
    { headers: { authorization: `Bearer ${process.env.API_TOKEN}` } },
  ],
});
```

**Vercel Sandbox (TypeScript)**

```javascript
const sandbox = await Sandbox.create({
  networkPolicy: {
    allow: {
      'api.example.com': [
        {
          transform: [
            { headers: { Authorization: `Bearer ${process.env.API_TOKEN}` } },
          ],
        },
      ],
    },
  },
});
```

The Vercel policy permits only `api.example.com`, matching a Freestyle VM with no public firewall rule. If the VM also had a public firewall rule, add `'*': []` to the `allow` object to keep other domains reachable. Brokering rules are available on Hobby, Pro, and Enterprise within each plan's usage quotas.

Limit which requests receive credentials with a `match` on path, method, `queryString`, or headers. On both products, nonmatching requests still reach the domain without the credential. To reject them, end the domain's rule list with a `response` rule whose `statusCode` is `403`.

#### Replace transforms and certificate settings

Vercel rules can add headers, forward requests to another URL, or return responses. Freestyle's `oauthBearer`, `s3`, `postgres`, and `jsonPatch` transforms have no built-in equivalent. Refresh or sign credentials in your application, then update the policy or use your own proxy.

Both products terminate TLS for transformed requests. Vercel adds a per-sandbox certificate authority to the system trust store and sets standard certificate environment variables. Remove settings that point `NODE_EXTRA_CA_CERTS`, `REQUESTS_CA_BUNDLE`, `SSL_CERT_FILE`, or `AWS_CA_BUNDLE` at Freestyle's certificate. For custom bundles, configure the [proxy CA certificates](https://vercel.com/docs/sandbox/concepts/security#proxy-ca-certificates).

### 10\. Verify and cut over

#### Validate workload behavior and resource use

Run both providers side by side before changing traffic:

- Run a representative workload on each provider and compare its output, exit codes, and written files.
  
- Compare each sandbox's `networkPolicy` with the Freestyle VM's rules. Confirm that sandboxed code can't reach hosts that Freestyle blocked.
  
- Measure peak CPU and memory on Vercel, then set `vcpus` to cover the peak. Plan maximums are 4 vCPUs and 8 GB on Hobby, 8 vCPUs and 16 GB on Pro, and 32 vCPUs and 64 GB on Enterprise.
  
- Check concurrency and creation rate against the plan quotas. Hobby allows 10 concurrent sandboxes. Pro and Enterprise allow 10,000, with a vCPU allocation rate that starts at 150 vCPUs per minute and ramps to 5,000.
  

Estimate usage with [Sandbox pricing](https://vercel.com/docs/sandbox/pricing). Vercel meters Active CPU, Provisioned Memory, Sandbox Creations, Data Transfer, and Snapshot Storage, plus Drive Storage, Drive Reads, and Drive Writes.

#### Move session state and switch traffic

Before moving state, plan replication between providers if shared data must remain writable during cutover. Otherwise, stop writes during the final export and import.

1. Record which provider owns each existing session and keep its requests on that provider while migrating its state.
   
2. Export files from paused VMs and snapshots as shown in step 6, with writes stopped for the workspaces being moved. Import and verify the files before routing those sessions to Vercel.
   
3. Replace stored `style.dev` URLs with `sandbox.domain()` results, and repoint custom domains from Freestyle to your application's route.
   
4. Switch the flag for new sessions and monitor output and errors. Keep existing sessions on Freestyle until they finish or their state has been imported.
   

#### Keep a rollback path until cleanup

If you roll back, send new sessions to Freestyle. Before returning a session that has written files on Vercel, copy and verify those changes on Freestyle. Retain both providers' state until the rollback period ends.

After that period, remove the migrated workloads' unused Freestyle call sites and data. Retain VMs, snapshots, and rules needed by workloads still on Freestyle. Remove the package and revoke its API key only when every dependent application and job has migrated.

## What doesn't map from Freestyle VMs

These features need a different design on Vercel. Run the examples from the linked project directory with the latest Vercel and Sandbox CLIs.

### Pauses, snapshots, and forks that keep memory

Vercel snapshots preserve files without process memory. Save progress to a file, Drive, or database before stopping the sandbox, then restart the process and load its saved progress on resume. The [process restart example](#restart-processes-after-a-resume) shows how to attach startup logic to the sandbox lifecycle.

Powering off a Freestyle VM from inside the guest also discards its memory. The next `vm.start()` boots from disk, and your code starts its processes again.

### VMs that run longer than one session

Vercel sessions end at their timeout, up to 45 minutes on Hobby or 24 hours on Pro and Enterprise, while a Freestyle VM can run for days with no fixed limit. Persistent sandboxes preserve files between sessions, so save progress to files, run long tasks as detached commands, and restart them in `onResume`.

On Pro and Enterprise, [lifecycle webhooks](https://vercel.com/docs/sandbox/lifecycle-webhooks) notify your backend when a session starts, nears its timeout, or stops. Use the expiry warning to save progress or extend the session within its limit.

To continue pending work after a timeout, handle stopped events whose `stopReason` is `timeout`, deduplicate them by event type and session ID, and fetch the sandbox's current state before resuming it. Check your application's task status so completed or canceled work stays stopped, and keep a workload on Freestyle if one process must hold state in memory for longer than 24 hours.

### Idle timeouts and wake on traffic

Freestyle's `idleTimeoutSeconds` pauses a VM after a period without network activity, and a request to its domain wakes it. Vercel has no idle timeout or wake on HTTP requests, so track activity in your application, extend sessions while work continues, and call `stop()` when work ends.

While a session is still running, extend its deadline with the [Sandbox CLI](https://vercel.com/docs/sandbox/sdk/cli#sandbox-extend):

```bash
sandbox extend session-123 10m
```

Replace `session-123` with your sandbox's name. Extending adds time to the current session; it doesn't reset an idle timer or change the default timeout for later sessions. Use `extendTimeout()` and `stop()` from your application.

Vercel SDK operations that need a running sandbox, such as `runCommand()`, resume a stopped persistent sandbox. Requests to its port URL return HTTP 410 while it is stopped. For a preview, have your backend resume the sandbox, restart its server, and wait for a successful health check before loading the sandbox URL.

### Services that start at boot

Freestyle snapshots capture running processes, and enabled systemd units start on every boot. Vercel restores files, so install dependencies in an image or snapshot and start services with a detached `runCommand()` after creation and each resume. If a unit used `Restart=`, run a supervisor in the sandbox or monitor the process from your backend, because detached commands don't restart after a process exits.

Docker is one such service, because Freestyle's Ubuntu snapshots start the Docker daemon at boot. On Vercel, a persistent sandbox keeps installed packages, so install Docker once. Start `dockerd` with `sudo: true` after creation and after each resume, as the [Docker guide](https://vercel.com/kb/guide/docker#run-docker-inside-a-sandbox) shows.

#### Check that your service is ready

Sandbox creation waits until commands can run, but your server may still be starting. Save this Node.js helper as `wait-for-http.mjs` and use it to check a health URL that covers the service and its dependencies before forwarding traffic:

```javascript
import { setTimeout as delay } from 'node:timers/promises';

export async function waitForHttp(url, headers = {}) {
  for (let attempt = 0; attempt < 20; attempt++) {
    try {
      const response = await fetch(url, {
        headers,
        redirect: 'error',
        signal: AbortSignal.timeout(2_000),
      });
      const ready = response.ok;
      await response.body?.cancel();
      if (ready) return;
    } catch {
      // Retry while the service is starting.
    }
    await delay(500);
  }
  throw new Error('Service did not become ready');
}
```

The helper retries startup failures and throws if the service stays unavailable. The authenticated service below uses it with an authorization header. Run the check again after restarting a service on resume.

### Custom domains and authenticated access

Vercel exposes sandbox ports through generated public URLs. Read each port's URL from `sandbox.domain()` after creating or resuming the sandbox. To give users a stable custom domain, point the domain or a wildcard subdomain at your application and have a route look up the sandbox's current URL and proxy each request to it. The route can also resume a stopped sandbox and add its token, replacing wake on traffic and forward auth for browser requests.

#### Authenticate sandbox services

To replace Freestyle's forward auth, check a per-sandbox bearer token in your server and send requests only from your trusted backend. The token authenticates outside callers, but sandboxed code can read it or change the server.

Save `server.mjs` and `call-protected-service.mjs` beside the [readiness helper](#services-that-start-at-boot). Run the caller locally or on your backend. It creates a token, uploads the server to a sandbox, and sends an authenticated request before stopping it:

**server.mjs**

```javascript
import { createServer } from 'node:http';
import { timingSafeEqual } from 'node:crypto';

const token = process.env.SERVICE_TOKEN;
if (!token) throw new Error('SERVICE_TOKEN is required');
const expected = Buffer.from('Bearer ' + token);

createServer((request, response) => {
  const actual = Buffer.from(request.headers.authorization ?? '');
  if (
    actual.length !== expected.length ||
    !timingSafeEqual(actual, expected)
  ) {
    response.writeHead(401).end('Unauthorized');
    return;
  }
  response.writeHead(200, { 'Content-Type': 'application/json' });
  response.end(JSON.stringify({ ok: true }));
}).listen(3000, '0.0.0.0');
```

**call-protected-service.mjs**

```javascript
import { randomBytes } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { Sandbox } from '@vercel/sandbox';
import { waitForHttp } from './wait-for-http.mjs';

const token = randomBytes(32).toString('hex');
const sandbox = await Sandbox.create({
  ports: [3000],
  timeout: 5 * 60 * 1000,
  persistent: false,
});

try {
  await sandbox.writeFiles([{
    path: 'server.mjs',
    content: await readFile(new URL('./server.mjs', import.meta.url)),
  }]);
  await sandbox.runCommand({
    cmd: 'node',
    args: ['server.mjs'],
    env: { SERVICE_TOKEN: token },
    detached: true,
  });

  const url = sandbox.domain(3000);
  const headers = { Authorization: 'Bearer ' + token };
  await waitForHttp(url, headers);
  const response = await fetch(url, {
    headers,
    redirect: 'error',
    signal: AbortSignal.timeout(5_000),
  });
  if (!response.ok) throw new Error('Service request failed');
  console.log(await response.text());
} finally {
  await sandbox.stop();
}
```

Run the caller from that directory with the credentials saved in step 2:

```bash
node --env-file=.env.local call-protected-service.mjs
```

The caller prints `{"ok":true}` after a successful request, and the server returns HTTP 401 for missing or incorrect tokens. Your backend must authorize each user before calling the sandbox.

Browsers cannot add this authorization header to a page load or iframe, so serve previews through an authenticated proxy that adds the token. Serve untrusted preview HTML from a separate origin that does not receive your application's session cookies, and restrict iframe permissions to those the preview needs.

### Private networks, tunnels, and port-level rules

Vercel doesn't provide a private network between sandboxes, so connect through public port URLs and authenticate requests. Each sandbox has its own localhost and filesystem. [Linux users](https://vercel.com/docs/sandbox/concepts/multi-agent) can separate cooperating processes within one sandbox, but don't provide the isolation of separate VMs.

Freestyle firewall rules can match a port and protocol. Vercel's `subnets.allow` entries admit every port on the allowed range, so narrow the range or enforce the port at the destination.

To replace a WireGuard tunnel into your network, connect Vercel Sandbox to a [Secure Compute network](https://vercel.com/docs/sandbox/concepts/secure-compute), an Enterprise add-on, or run a VPN client inside the sandbox with `sudo`. Keep the workload on Freestyle until one of those options is in place. If a service allows Freestyle's egress IP address, allow the Secure Compute network's static egress IP addresses instead.

### SSH, PTY sessions, and identity tokens

Vercel Sandbox provides terminal sessions without an SSH server. Replace `freestyle vm ssh` with `sandbox connect` in the Sandbox CLI:

```bash
sandbox connect session-123
```

For interactive terminals, `sandbox.openInteractive()` replaces `vm.pty.open()` and returns a WebSocket URL and token. Vercel terminal sessions end when the sandbox stops; Freestyle PTYs live in the guest and survive a pause.

Freestyle identity tokens let a user's client run commands or attach to a PTY session in one VM. Vercel Sandbox has no client token for commands, so route each user's commands through your backend and call `sandbox.openInteractive()` there when the user needs a terminal.

Tools that connect over SSH, such as a port forward from `freestyle vm port-forward`, have no direct replacement. Copy files with `sandbox copy`, and reach a service through a port that you expose with `ports`.

### Live resize and larger disks

`vm.resize()` grows a running Freestyle VM's CPU, memory, or disk. On Vercel, pass `resources.vcpus` to `sandbox.update()`, then stop and resume the sandbox to apply the new size in its next session.

Vercel sandboxes have 1 vCPU or an even number up to 32, with 2 GB of memory per vCPU. Freestyle's Ubuntu base snapshots share that ratio, but `vm.resize()` can grow memory independently. Choose a size for peak memory within your plan. Matching a VM resized to 4 vCPUs and 16 GiB requires 8 vCPUs on Vercel.

#### Store larger workspaces on a Drive

For files that exceed the sandbox's 64 GB local disk, create a [Drive](https://vercel.com/docs/drives/cli-reference#vercel-drives-get-or-create) and mount it at `/data`. Choose the region and size limit before creation; neither can change afterward. Only one sandbox can hold the Drive's writable mount at a time.

Freestyle Pro allows a 256 GB disk per VM. Vercel Hobby and Pro trial Drives are limited to 15 GB, so use external storage when the available Drive capacity is too small. The commands below create a 100 GiB Drive on Pro or Enterprise and a sandbox in the same region:

```bash
vercel drives get-or-create migration-data \
  --region iad1 --max-size 100GiB

sandbox create --name migration-worker \
  --vcpus 4 --timeout 30m --region iad1 \
  --mount migration-data:/data
```

Store large datasets on the Drive under `/data`, separate from the local disk. When work finishes, run `sandbox stop migration-worker`.

To import a workspace that exceeds the local disk, copy the reassembled archive from step 6 to `/data` and extract it there. Allow enough Drive capacity for both the compressed archive and the extracted files, and retain the local archive until verification finishes.

### Nested virtualization and GPUs

Vercel Sandbox supports Docker, VPN clients, and FUSE with `sudo`. Keep workloads that need to start their own virtual machines, such as an Android emulator, on Freestyle; nested virtualization is outside those supported patterns.

Vercel Sandbox provides CPU and memory. Freestyle's experimental GPU option accelerates graphics, such as GPU-accelerated Chromium and OpenGL applications, so keep VMs that depend on it on Freestyle.

### Other SDK features

These Freestyle features have a different interface on Vercel, or none:

| Freestyle feature                                                      | On Vercel Sandbox                                                                                                                                                  |
| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `stdin` on `vm.exec()`                                                 | `stdin: true` with `detached: true` in `runCommand()`, then `command.writeStdin()` and `command.closeStdin()`                                                      |
| `session.write()` and `session.signal()` on a PTY session              | `command.writeStdin()` for input, and `command.kill()` to send a signal                                                                                            |
| `vm.pty.list()`                                                        | No list call in the TypeScript SDK, so store each `cmdId`                                                                                                          |
| `git clone` in the guest, with a TLS rule that adds GitHub credentials | A `git` source at creation with `username` and `password`, then `runCommand('git', [...])`                                                                         |
| `vm.fs.readFileStream()`                                               | `sandbox.readFile()`, which returns a stream, or `sandbox.downloadFile()`                                                                                          |
| Usage fields from `vm.data()`, such as `cpuTimeSeconds`                | `sandbox.totalActiveCpuDurationMs` and `sandbox.totalDurationMs` for cumulative usage. For live CPU and memory, use the Observability tab of the Vercel dashboard. |
| Identity tokens that let a user's client run commands in one VM        | No equivalent. Route each user's commands through your backend.                                                                                                    |
| `freestyle.firewall.evaluate()`                                        | No equivalent. Test access with a command inside the sandbox.                                                                                                      |
| Freestyle's REST API                                                   | The [Sandboxes endpoints](https://vercel.com/docs/rest-api/sandboxes) in the Vercel REST API                                                                       |

Replace Freestyle CLI commands in scripts and CI jobs with these commands:

| Freestyle CLI                         | Vercel replacement                                                                                              |
| ------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `freestyle vm create`                 | `sandbox create`                                                                                                |
| `freestyle vm list`                   | `sandbox list`                                                                                                  |
| `freestyle vm exec <vm> -- <command>` | `sandbox exec <name> -- <command>`                                                                              |
| `freestyle vm ssh <vm>`               | `sandbox connect <name>`                                                                                        |
| `freestyle vm scp`                    | `sandbox copy`                                                                                                  |
| `freestyle vm pause <vm>`             | `sandbox stop <name>`, which saves files only                                                                   |
| `freestyle vm delete <vm>`            | `sandbox remove <name>`                                                                                         |
| `freestyle snapshot create`           | `vercel vcr build` for an image, or `sandbox snapshot <name> --stop` to save files and stop the running session |

## Troubleshooting

Use these checks when behavior changes after moving a workload from Freestyle.

| What you observe                                                                                                                     | What to check                                                                                                                                                                                                               |
| ------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Authentication fails locally after it worked earlier                                                                                 | The development OIDC token expires after 12 hours. Run `vercel env pull` again.                                                                                                                                             |
| `Sandbox.create()` returns `image_not_ready`                                                                                         | Vercel Container Registry is still preparing the image. Retry after the repository details page shows **Ready**, and confirm the image targets `linux/amd64`.                                                               |
| A command that was one string on Freestyle fails to start, or pipes, redirection, and `$VARIABLES` reach the program as literal text | `runCommand()` doesn't use a shell. Pass the binary and an argument array, or wrap the command in `bash -c`.                                                                                                                |
| A command can't find files that it found on Freestyle                                                                                | Managed images use `/vercel` as the working directory. Pass `cwd` in place of a `cd` prefix, and update absolute paths or use relative paths.                                                                               |
| Every command looks like it failed, or failures go unnoticed                                                                         | Freestyle returns `statusCode`, and Vercel returns `exitCode`. Rename the field in each check.                                                                                                                              |
| A sandbox stops after 5 minutes, or a sandbox or command times out much sooner than on Freestyle                                     | A session ends after 5 minutes unless you set `timeout`. Freestyle's lifecycle fields take seconds, and Vercel's TypeScript SDK takes milliseconds, so multiply each copied value by 1,000.                                 |
| A command or file write fails with a permission error                                                                                | Freestyle's `vm.fs` writes as root, while Vercel commands run as the image's default user. Write under `/vercel`, pass `sudo: true` to the command, or write the file with `sandbox.asUser('root').writeFiles()`.           |
| A tool from Freestyle's Ubuntu snapshot isn't found                                                                                  | Vercel's managed images include a different set of tools. Install the tool in a custom image, as shown in step 4.                                                                                                           |
| Sandboxed code reaches hosts that Freestyle blocked                                                                                  | A sandbox created without `networkPolicy` allows all outbound traffic. Set `'deny-all'` or an allow list.                                                                                                                   |
| Requests to a domain that Freestyle allowed are blocked                                                                              | A Vercel allow list blocks every destination that it doesn't name, and `*.example.com` doesn't match `example.com`. Add the domain to the allow list.                                                                       |
| Requests to a sandbox URL return HTTP 410                                                                                            | The sandbox is stopped, and HTTP requests don't resume it. Run a command to resume the sandbox, then restart your server.                                                                                                   |
| A server that ran before a stop isn't running after a resume                                                                         | Vercel restores files, not processes. Start the server in `onCreate` and `onResume`, as shown in step 6.                                                                                                                    |
| The first call to a stopped sandbox fails with `snapshot_not_found`                                                                  | Check whether the saved snapshot still exists. If it has expired, create a replacement sandbox and restore files from a backup. Changing retention cannot recover a deleted snapshot, so configure it for future snapshots. |
| Creation fails with `snapshot_region_mismatch` or `drive_region_mismatch`                                                            | Create the sandbox in the same region as its snapshot or Drive.                                                                                                                                                             |
| A long, quiet command loses its connection                                                                                           | Connections close after 340 seconds without data, and the command keeps running. Follow [Execute long-running tasks](https://vercel.com/docs/sandbox/examples/execute-long-running-tasks).                                  |

## What to build with Vercel Sandbox

Use these patterns when adapting the workloads you moved from Freestyle.

### AI code interpreter

With a code interpreter, a model can write Python or SQL, run it against a user's file, and return the result. Create one sandbox for each request with `persistent: false`, a short `timeout`, and `networkPolicy: 'deny-all'`. Upload the data with `writeFiles()`, then run the model's script with `runCommand()`.

[Add Python execution to a TypeScript agent](https://vercel.com/kb/guide/python-ai-sdk-vercel-sandbox), or read about [code interpreter design](https://vercel.com/i/code-interpreter).

### Coding agents that work on a repository

Coding agents use a Linux workspace to clone a repository, edit files, run checks, and return a branch or draft pull request. Clone a private repository with a `git` source, and install private packages with `credentials: { npm: true }`. With the Sandbox CLI, `sandbox create claude` or `sandbox create codex` starts a supported agent in a sandbox from your terminal.

Use [eve Software Factory](https://vercel.com/templates/eve/eve-software-factory) to turn issues into reviewed draft pull requests.

### App builders with live previews

An app builder gives each project a sandbox with a dev-server URL that your product loads in an iframe. Open the named sandbox with `Sandbox.getOrCreate()`, expose port 3000, and start the server as a detached command.

On later visits, have your backend resume the sandbox and restart the server before loading its preview URL. Extend the session while the user is active; requests to a stopped sandbox's URL do not resume it.

Build a [v0-style app builder](https://vercel.com/kb/guide/v0-clone-openai-agents-vercel-sandbox) with the OpenAI Agents API.

### Agents with persistent, shared workspaces

Long-running agents can keep files between conversations and share reference material with a team. Give each user or task a named sandbox, and keep team files on a Drive that each session mounts as a read-only snapshot.

The [eve with Vercel Drives template](https://vercel.com/templates/eve/eve-vercel-drives-starter) connects an agent in Slack or a terminal to shared team files. It saves new documents through a separate sandbox with write access. Follow the [eve and Drives setup](https://vercel.com/kb/guide/vercel-drives-eve-agent) to configure it.

### Customer code in a multi-tenant product

Use one sandbox per execution to run code written by your customers, third-party developers, or their agents. Start each job from a snapshot that holds its dependencies, and set `networkPolicy` to `'deny-all'` or an allow list. Broker credentials at the Sandbox firewall so customer code never holds them.

See [Notion Workers](https://vercel.com/customers/notion-workers-vercel-sandbox) for a production example of running untrusted code, or [add isolated Python execution](https://vercel.com/kb/guide/python-and-vercel-sandbox) to your own app.

## Next steps

- Configure [session timeouts and persistent files](https://vercel.com/docs/sandbox/concepts/persistent-sandboxes)
  
- Restrict egress and broker credentials with the [Sandbox firewall](https://vercel.com/docs/sandbox/concepts/firewall)
  
- Build custom images with [Vercel Container Registry](https://vercel.com/docs/container-registry)
  
- Mount persistent storage with [Drives](https://vercel.com/docs/sandbox/concepts/drives)
  
- Run agent evals with [Harbor and Terminal-Bench](https://vercel.com/docs/sandbox/ecosystem/harbor)
  
- Estimate your bill with [Sandbox pricing and quotas](https://vercel.com/docs/sandbox/pricing)
  
- Compare [Vercel Sandbox and Freestyle VMs](https://vercel.com/kb/guide/vercel-sandbox-vs-freestyle-vms) for your workload
  

## Frequently asked questions

### Can I move paused Freestyle VMs or Freestyle snapshots to Vercel Sandbox directly?

No. Export files from a started Freestyle VM or one created from the snapshot, then use `sandbox copy` to transfer the archive. Extract it into the Vercel workspace or a mounted Drive; memory and running processes don't transfer.

### Can my application stay on its current host after I migrate to Vercel Sandbox?

Yes. The Vercel Sandbox SDKs work from any backend with an access token, a team ID, and a project ID. Applications deployed on Vercel authenticate with the project's OIDC token instead.

### Can I keep some workloads on Freestyle and move the rest to Vercel Sandbox?

Yes. The `freestyle` and Vercel Sandbox SDKs are independent, so one application can call both. For example, move code execution and coding-agent sessions to Vercel Sandbox, and keep VMs that depend on pauses that keep memory or nested virtualization on Freestyle.

### Do I need to rebuild my Freestyle snapshots for Vercel Sandbox?

Custom snapshots need a Dockerfile built into Vercel Container Registry with `vercel vcr build`. You can replace a Freestyle base snapshot with a Vercel managed image when its runtime versions and installed tools meet your workload's requirements. A snapshot's memory doesn't transfer, so start its processes after creation.

### Do I have to keep using TypeScript after I migrate from Freestyle?

No. Freestyle documents a TypeScript SDK, and Vercel provides TypeScript and Python SDKs. The `vercel-sandbox` package supports Python 3.11 or later with asynchronous and synchronous APIs.

### Do processes keep running when a Vercel sandbox stops and resumes, as they do after a Freestyle pause?

No. Vercel restores files, so use `onResume` to restart servers and background jobs. Pass the hook on every `Sandbox.get()` and `Sandbox.getOrCreate()` call that can resume a session, because it runs in your process.

### Does Vercel Sandbox resume a stopped sandbox automatically?

Yes, for SDK operations. A command or file operation resumes a stopped persistent sandbox with no extra option. HTTP requests to a port URL don't resume the sandbox, so they return HTTP 410 until your code resumes it.

### Can a Vercel sandbox run for days, as a Freestyle VM can?

No single session can exceed 45 minutes on Hobby or 24 hours on Pro and Enterprise. Persistent sandboxes keep files between sessions, so save progress to files and restart the task after each resume.

### Does Vercel Sandbox block network access by default, as Freestyle does?

No. A Vercel sandbox allows outbound network access unless you set `networkPolicy`. Pass `'deny-all'` or an allow list at creation to keep a Freestyle VM's restricted access.

### Can I use a custom domain for a Vercel sandbox port?

Vercel Sandbox exposes each listed port through a generated URL returned by `sandbox.domain()`. For a custom domain or another stable address, serve the sandbox through one of your application's routes. Read the port URL again after each resume and have the route forward requests to it.

### Do commands run as the same user in Vercel Sandbox as they do on Freestyle?

Yes, on Ubuntu images. Freestyle's Ubuntu snapshots and Vercel's Ubuntu managed images both run commands as `ubuntu` with passwordless sudo. Vercel commands start in `/vercel` and don't use a shell. Pass `sudo: true` to `runCommand()` for commands that need root.

## Related Resources

- [Vercel Sandbox vs Freestyle VMs](/kb/guide/vercel-sandbox-vs-freestyle-vms): Compare Vercel Sandbox and Freestyle VMs as AI agent sandboxes, including isolation, persistence, network controls, SDKs, and deployment regions.

## More Vercel Sandbox guides

- [Migrate from Cloudflare Sandbox to Vercel Sandbox](/kb/guide/migrate-from-cloudflare-sandbox-to-vercel-sandbox): Move Cloudflare Sandbox code to Vercel Sandbox in TypeScript or Python, from images and snapshots to Drives, network policies, preview ports, and a staged cutover.
- [Migrate from Upstash Box to Vercel Sandbox](/kb/guide/migrate-from-upstash-box-to-vercel-sandbox): Migrate from Upstash Box to Vercel Sandbox in TypeScript or Python, including runtimes, persistent files, network policies, agents, and a staged cutover.
- [Run research agents, data analysis, and evals on Vercel Sandbox](/kb/guide/sandbox-research-workloads): Give a research agent a Python execution tool, analyze datasets, fork parallel trials from one baseline, restrict network access, and resume a workspace across sessions.

## Reference Architecture

Choose a stack and work through the decisions behind it, with curated documentation, guides, templates, and courses to help you build.

- [Agent stack](/kb/architecture/agents): Build and operate agents with models, tools, and durable workflows.
- [Web applications](/kb/architecture/web): Choose rendering, data, authentication, and caching approaches.
- [Backends](/kb/architecture/backends): Choose a runtime, connect services, and run background work.

[Browse all stacks](/kb/architecture)

## Build with prompts

Build an app, extend an agent, or improve your project with ready-to-use prompts for your coding agent.

[Browse the prompt library](/kb/prompts) · [Read the Markdown index](/kb/prompts.md)

## Search guides from your terminal

Search the Knowledge Base and read guides as Markdown with the Vercel CLI. No login required.

```bash
# Find guides by keyword
npx vercel@latest kb search "rewrites and redirects"
npx vercel@latest kb search "AI SDK streaming"

# Show the latest guides
npx vercel@latest kb

# Print a guide as Markdown, by slug or URL
npx vercel@latest kb inspect <guide>
```
