A windswept bonsai on a floating island

Get to know Cadenya

We’re developers who love to build. We set out to create a yes-code platform that makes building agents feel like the best parts of building software.

Vercel Sandbox for AI agents (2026)

Vercel Sandbox

By Cadenya

Vercel Sandbox runs an AI agent’s code in Firecracker microVMs, and Vercel Sandbox pricing bills Active CPU, so time spent waiting on a model call costs no CPU. A network policy (allow-all, deny-all or a domain allowlist) controls egress, credentials brokering keeps API keys out of the sandbox, and you pick one of 19 regions. It’s been generally available since January 30, 2026, with SDKs for TypeScript and Python and a CLI. Cadenya is a hosted agent loop that calls Vercel Sandbox as a tool set, and a coding agent can set it up with no account, in a temporary workspace you claim later.

This guide gives the agent a Bare tool called run_code and answers each call from your own backend. A small worker reads the objective’s events, runs the code in a Vercel Sandbox with @vercel/sandbox, and sends the output back through the API. The worker only makes outbound requests, so nothing on your side accepts traffic from the internet, and the Vercel access token never leaves your servers.

If you already run an HTTP service, an HTTP tool set can call it directly, and that variant comes after the run. The same setup works with E2B, Daytona and Blaxel. Sandboxes for running agent-generated code compares them, and Vercel Workflow for AI agents runs Vercel Sandbox inside a durable workflow. What Cadenya adds to Vercel Sandbox is at the end.

Every price and limit below comes from each vendor’s own pages, checked on November 11, 2026.

Vercel Sandbox at a glance

Vercel SandboxWith Cadenya
PricingPro in iad1: $0.128 an Active CPU hour, $0.0212 a GB-hour of memory, $0.60 per million creationsFree for 1,000 loops a month, $49 a month for 50,000, then $0.0015 a loop
IsolationEach sandbox is a Firecracker microVM with a dedicated kernelThe code runs in the Vercel Sandbox your worker creates for each objective
Network policyallow-all by default, deny-all (DNS included), or an allowlist of domains and CIDR ranges, with credentials brokeringSet networkPolicy in the worker’s Sandbox.create, and requiresApproval lets a person read the code first
Regions19 regions, with fra1, lhr1, cdg1, dub1 and arn1 in Europe. iad1 is the defaultYour worker passes region, so the sandbox runs in the region you choose
Persistence and snapshotsPersistent by default: the filesystem is saved on stop and restored on resumeEach objective keeps a durable event log, and a Continue message picks a waiting objective back up
AuthenticationA Vercel OIDC token, or an access token with team and project IDs outside VercelThe token stays in your worker’s environment, and Cadenya never sees it
SDK languagesJavaScript and TypeScript, Python, and the sandbox CLICadenya SDKs for TypeScript, Python, Ruby and Go, all Apache-2.0
Latest SDK version@vercel/sandbox 3.9.1, vercel 0.12.2 on PyPI, sandbox CLI 4.11.1@cadenya/cadenya 1.9.0, and 1.9.0 in every language

Pricing: Active CPU, memory and creations

Billing has three main meters. Active CPU counts only the time your code uses the CPU, so waiting on “AI model calls” doesn’t count. Provisioned memory counts the memory you allocate, 2 GB per vCPU, while the sandbox runs. And each Sandbox.create() call is one creation.

On Pro, usage draws from the plan’s $20 monthly credit first, and CPU and memory rates vary by region. Hobby includes 5 Active CPU hours, 420 GB-hours and 5,000 creations a month. Vercel’s “AI code validation” example (5 minutes, 2 vCPUs, 4 GB) costs $0.0092, and memory is $0.0071 of it. So stop the sandbox when the agent’s turn ends, as the worker below does.

Isolation, GA status and SDKs

Vercel Sandbox went GA on January 30, 2026, as “an ephemeral compute primitive for safely executing untrusted code.” Each sandbox “runs in its own Firecracker microVM with a dedicated kernel.” The default image holds Node.js and Python 3.14, and the worker uses vercel/sandbox/python:3.14, which pins Python 3.14 with pip, venv and uv.

The SDKs are @vercel/sandbox for TypeScript (3.9.1, October 28, 2026, Apache-2.0), vercel.sandbox in the vercel package on PyPI (0.12.2, Python 3.10 or later), and the sandbox CLI (4.11.1). On Vercel, the SDK signs in with an OIDC token. On your own servers, it takes an access token with your team and project IDs.

Network policy: deny-all, allowlists and credentials brokering

A network policy has three modes, “which can be updated at runtime, without restarting the process.” allow-all is the default. deny-all “Denies all outbound network access, including DNS.” A user-defined policy allows only the domains and CIDR ranges you list:

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

// Sandbox has no Internet or secure-compute access.
const denied = await Sandbox.create({
  networkPolicy: 'deny-all'
});

// Sandbox only gets access to listed websites.
const restricted = await Sandbox.create({
  networkPolicy: {
    allow: ["*.google.com", "ai-gateway.vercel.sh"]
  }
});

A rule on an allowed domain can add headers to its requests. That’s credentials brokering: “The secrets never enter the sandbox, so code running inside it cannot exfiltrate them.” And sandbox.update({ networkPolicy: 'deny-all' }) locks a running sandbox down once it has what it needs. The worker below uses deny-all, since the agent’s Python needs only the standard library.

Regions, persistent sandboxes and snapshots

Vercel Sandbox runs in 19 regions: arn1, bom1, cdg1, cle1, cpt1, dub1, fra1, gru1, hkg1, hnd1, iad1, icn1, kix1, lhr1, pdx1, sfo1, sin1, syd1 and yul1. Pass region to Sandbox.create or set a project default. Otherwise iad1 applies.

Sandboxes are persistent by default. When a session stops, Vercel snapshots the filesystem, and the next SDK call on that sandbox resumes from it. snapshot() saves a state on demand, and Sandbox.fork branches from one. Each session stops after its timeout, which you set at creation and extend with extendTimeout(). The worker below passes persistent: false, because it stops the sandbox after one turn, and non-persistent sandboxes “don’t accrue Snapshot Storage costs.”

How a bare tool runs code in your sandbox

A Bare tool set holds tools with no execution adapter. Cadenya stores the tool, shows it to the model, and waits for you to supply each result. Here’s one run_code call from start to finish:

  1. The agent calls run_code with a Python program as its code argument.
  2. Cadenya records the call, writes a toolCalled event to the objective, and pauses the loop until the call gets content.
  3. Your worker reads that event from the objective’s event stream, creates a sandbox on the first call, and runs the code.
  4. The worker sends stdout, stderr and any error back with setToolCallContent, and the agent reads them on its next loop.

The Vercel access token lives only in your worker’s environment. Cadenya never sees it, and the sandbox never needs to reach Cadenya.

The worker below keeps one sandbox per objective, so a file the agent writes in one call is still there in the next. It kills the sandbox when the agent’s turn ends.

The agent, the tool and the variation as config files

Cadenya’s CLI applies resources from YAML files in .cadenya/, with settings in cadenya.yaml. Each file is one resource, and a child directory takes its parent’s filename:

cadenya.yaml
.cadenya/
  toolSets/
    sandbox.yaml          # the Bare tool set
    sandbox/
      run-code.yaml       # the run_code tool
  agents/
    code-runner.yaml      # the agent
    code-runner/
      default.yaml        # its variation: prompt, model, tools

The bundle key in cadenya.yaml marks every resource the CLI writes, and it’s how the CLI knows which ones it owns:

bundleKey: code-runner

The tool set, in .cadenya/toolSets/sandbox.yaml:

metadata:
  name: Sandbox
spec:
  description: Runs Python in an isolated sandbox through your worker
  adapter:
    type: bare
    bare: {}

The tool, in .cadenya/toolSets/sandbox/run-code.yaml. llmToolName is the name the model sees, and parameters is the JSON Schema of its arguments:

metadata:
  name: Run code
spec:
  llmToolName: run_code
  description: >-
    Run Python 3 code in an isolated sandbox and get back its stdout, stderr
    and any error. Files you write stay in the sandbox for the rest of this
    conversation. Print every value you need to see.
  parameters:
    type: object
    properties:
      code:
        type: string
        description: The complete Python 3 program to run.
    required:
      - code
    additionalProperties: false
  config:
    type: bare
    bare: {}

The agent, in .cadenya/agents/code-runner.yaml:

state: published
metadata:
  name: Code runner
spec:
  description: Answers questions about numbers and data by running Python with run_code

And its variation, in .cadenya/agents/code-runner/default.yaml. The model is a setting here, so switching models is a one-line change:

metadata:
  name: Default
spec:
  systemPromptTemplate: |
    You answer questions about numbers and data. Never compute a result in
    your head: write a short Python 3 program, run it with the run_code tool,
    and read its output. If the code fails, fix it and run it again. Then
    answer in one or two sentences with the exact numbers the code printed.
  modelConfig:
    modelId: getting-started-key.xingchen-xing4-0-29b-a4b-free
    temperature: 0
  constraints:
    maxToolCalls: 8
  assignments:
    - type: toolId
      toolId: external_id:sandbox/run-code

Any model that cadenya models list shows and that supports tool calls works in modelId. The CLI reads CADENYA_API_KEY and CADENYA_WORKSPACE_ID from the environment. Plan first, then apply:

cadenya config plan
cadenya config apply

Plan prints every create, update and delete before apply writes anything. The cadenya-config-loader GitHub Action runs the same plan or apply from a workflow, as Config files explains.

A worker that answers run_code

The worker needs the Cadenya TypeScript SDK and Vercel’s Sandbox SDK:

npm install @cadenya/cadenya @vercel/sandbox

The worker talks to the sandbox through one small interface, so it stays the same on E2B, Daytona and Blaxel. In src/sandboxes/types.ts:

export interface RunResult {
  stdout: string;
  stderr: string;
  // Set when the code raised an exception or exited with a non-zero code.
  error?: string;
}

export interface CodeSandbox {
  readonly provider: "e2b" | "daytona" | "blaxel" | "vercel";
  readonly id: string;
  runPython(code: string): Promise<RunResult>;
  kill(): Promise<void>;
}

The worker streams one objective’s events and answers each run_code call. In src/worker.ts:

import type Cadenya from "@cadenya/cadenya";
import type { CodeSandbox, RunResult } from "./sandboxes/types.js";

// Watches one objective and answers every run_code call in a sandbox. The
// sandbox is created on the first call, reused for the next ones, and killed
// when the agent's turn ends. Returns the agent's last message.
export async function serveRunCode(
  client: Cadenya,
  objectiveId: string,
  createSandbox: () => Promise<CodeSandbox>,
): Promise<string> {
  let sandbox: CodeSandbox | undefined;
  let answer = "";
  try {
    const stream = await client.objectives.streamEvents(objectiveId);
    for await (const event of stream) {
      const data = event.data;

      if (data.type === "toolCalled" && data.toolCalled.llmToolName === "run_code") {
        const call = data.toolCalled;
        const code = call.arguments?.code;
        let result: RunResult;
        if (typeof code !== "string" || code.trim() === "") {
          result = { stdout: "", stderr: "", error: "run_code needs a non-empty code string" };
        } else {
          try {
            sandbox ??= await createSandbox();
            result = await sandbox.runPython(code);
          } catch (error) {
            // The agent reads the failure and can try again.
            result = { stdout: "", stderr: "", error: `sandbox error: ${(error as Error).message}` };
          }
        }
        // Long output is cut so one noisy program can't fill the context window.
        await client.objectives.setToolCallContent(objectiveId, call.toolCallId, {
          content: [{ type: "text", text: { text: JSON.stringify(result).slice(0, 8_000) } }],
        });
      }

      if (data.type === "assistantMessage" && data.assistantMessage.content) {
        answer = data.assistantMessage.content;
      }
      // The turn is over when the objective waits for the user, or ends.
      if (data.type === "stateChanged" && data.stateChanged.toState === "OBJECTIVE_STATE_WAITING") break;
      if (data.type === "finalized") break;
      if (data.type === "error" || data.type === "cancelled" || data.type === "timedOut") {
        throw new Error(`objective stopped: ${JSON.stringify(data)}`);
      }
    }
  } finally {
    await sandbox?.kill();
  }
  return answer;
}

A failed sandbox call goes back to the agent as an error it can read, so one bad program doesn’t end the objective. And the SDK’s stream reconnects on its own after a dropped connection, starting from the last event it received.

Two other ways to get the same calls fit a worker that serves many objectives:

  1. Polling. List an objective’s tool calls with executionStatus set to TOOL_CALL_EXECUTION_STATUS_WAITING_FOR_CONTENT, which returns the Bare calls still waiting for a result.
  2. Webhooks. Cadenya sends objective_event.tool_called to the agent’s webhook URL for every call, with the tool, its config and the parsed arguments.

The Vercel Sandbox

The worker runs outside Vercel, so it signs in with an access token. It writes the agent’s code to a file and runs it with python3. In src/sandboxes/vercel.ts:

import { Sandbox } from "@vercel/sandbox";
import type { CodeSandbox, SandboxLabels } from "./types.js";

// Reads VERCEL_TOKEN, VERCEL_TEAM_ID and VERCEL_PROJECT_ID from the environment.
export async function createVercelSandbox(labels: SandboxLabels, name: string): Promise<CodeSandbox> {
  const sbx = await Sandbox.create({
    teamId: process.env.VERCEL_TEAM_ID!,
    projectId: process.env.VERCEL_PROJECT_ID!,
    token: process.env.VERCEL_TOKEN!,
    name,
    image: "vercel/sandbox/python:3.14",
    region: process.env.VERCEL_SANDBOX_REGION ?? "iad1",
    networkPolicy: "deny-all",
    // The worker stops the sandbox when the turn ends, so it skips the snapshot.
    persistent: false,
    // The session stops on its own when the timeout ends, so a crashed
    // worker never leaves one running for long.
    timeout: 10 * 60_000,
    tags: labels,
  });

  let calls = 0;
  return {
    provider: "vercel",
    id: sbx.name,
    async runPython(code) {
      const path = `run_code_${++calls}.py`;
      await sbx.writeFiles([{ path, content: code }]);
      const result = await sbx.runCommand({ cmd: "python3", args: [path], timeoutMs: 60_000 });
      return {
        stdout: await result.stdout(),
        stderr: await result.stderr(),
        error: result.exitCode === 0 ? undefined : `exit code ${result.exitCode}`,
      };
    },
    async kill() {
      await sbx.stop();
    },
  };
}

SandboxLabels is a Record<string, string> in the same types.ts, and the worker passes labels such as the objective ID as tags, so a cleanup job can find the sandbox later. A few things to know about Vercel Sandbox:

  1. runCommand resolves with the result when the program fails. A non-zero exitCode marks the failure, and Python’s traceback is in stderr.
  2. Each call starts a new Python process, so variables don’t carry over between calls. Files do, because the sandbox stays the same.
  3. timeoutMs stops one program that runs too long, and timeout stops the whole session.
  4. stop() is safe to call more than once. To remove the sandbox from the project’s list as well, call sbx.delete() after it.

Run it

The script that starts an objective picks the runner from SANDBOX_PROVIDER. In src/run.ts:

import Cadenya from "@cadenya/cadenya";
import { createSandbox, providerFromEnv } from "./sandboxes/index.js";
import { serveRunCode } from "./worker.js";

const client = new Cadenya(); // reads CADENYA_API_KEY and CADENYA_WORKSPACE_ID
const provider = providerFromEnv(); // e2b, daytona, blaxel or vercel

const objective = await client.objectives.create({
  agentId: "external_id:code-runner",
  firstUserMessage: "What is the 1,000th prime number, and what is the sum of the first 1,000 primes?",
});
const id = objective.metadata.id;

const answer = await serveRunCode(client, id, () =>
  createSandbox(provider, { objective: id }, `run-code-${id.slice(-12).toLowerCase()}`),
);
console.log(answer);

createSandbox in src/sandboxes/index.ts calls createVercelSandbox when SANDBOX_PROVIDER is vercel. Set VERCEL_TOKEN, VERCEL_TEAM_ID and VERCEL_PROJECT_ID, then run it:

SANDBOX_PROVIDER=vercel npx tsx src/run.ts

You should see the agent’s answer in one or two sentences. The agent, the prompt and the worker are the same as in the E2B guide, where a run on October 29, 2026 answered:

The 1,000th prime number is **7919**, and the sum of the first 1,000 primes is **3,682,913**.

The worker sends each result back as {"stdout":"...","stderr":""}, with an error field when the exit code isn’t 0.

Ask a person before the code runs

Set requiresApproval: true on the tool, and Cadenya parks the loop on every run_code call until someone approves or denies it:

spec:
  llmToolName: run_code
  requiresApproval: true

The objective then writes a toolApprovalRequested event with the model’s arguments, which here are the code itself. Approve the call, and the toolCalled event reaches your worker:

cadenya objectives approve-tool-call <objective-id> <tool-call-id>

Or deny it with a memo that steers the agent:

cadenya objectives deny-tool-call <objective-id> <tool-call-id> \
  --memo "Don't open network connections. Read the CSV from /tmp instead."

The worker doesn’t change. It only ever sees calls that a person approved.

The HTTP tool set variant, for teams with an endpoint

If you already host an HTTP service, an HTTP tool set sends each call to it directly, and your service runs the code. Cadenya sends tool set requests only to hosts on the account’s trusted endpoints list, so add yours first:

cadenya trusted-endpoints create --name sandbox-runner --host sandbox-runner.example.com

The tool set sets the base URL and a header that reads a tool set secret, so the token never appears in the prompt or in your repository:

metadata:
  name: Sandbox runner
spec:
  description: Runs Python in an isolated sandbox behind your own run-code endpoint
  adapter:
    type: http
    http:
      baseUrl: https://sandbox-runner.example.com
      headers:
        Authorization: "Bearer {{ secrets.RUN_CODE_TOKEN }}"

The tool keeps the same llmToolName and parameters as the Bare one, with an HTTP config instead. requestBodyTemplate builds the POST body, and {{ arguments | json }} sends the tool’s arguments as JSON:

  config:
    type: http
    http:
      requestMethod: POST
      path: /run-code
      requestBodyContentType: application/json
      requestBodyTemplate: "{{ arguments | json }}"

Apply both, then store the token as a tool set secret. Cadenya encrypts it at rest and decrypts it only when a call uses it:

cadenya config apply
cadenya tool-sets secrets create <tool-set-id> --name RUN_CODE_TOKEN --value "$RUN_CODE_TOKEN"

The endpoint checks the token, runs the code in a fresh Vercel Sandbox with the same runner, and kills the sandbox before it replies. In http-variant/server.ts:

import { timingSafeEqual } from "node:crypto";
import { createServer, type ServerResponse } from "node:http";
import { createSandbox, providerFromEnv, type RunResult } from "../src/sandboxes/index.js";

const token = process.env.RUN_CODE_TOKEN;
if (!token) throw new Error("Set RUN_CODE_TOKEN");
const expected = Buffer.from(`Bearer ${token}`);
const provider = providerFromEnv();
const port = Number(process.env.PORT ?? 8787);

function authorized(header: string | undefined): boolean {
  const given = Buffer.from(header ?? "");
  return given.length === expected.length && timingSafeEqual(given, expected);
}

function reply(res: ServerResponse, status: number, body: RunResult | { error: string }) {
  res.writeHead(status, { "content-type": "application/json" });
  res.end(JSON.stringify(body));
}

createServer(async (req, res) => {
  if (req.method !== "POST" || req.url !== "/run-code") return reply(res, 404, { error: "not found" });
  if (!authorized(req.headers.authorization)) return reply(res, 401, { error: "unauthorized" });

  let raw = "";
  for await (const chunk of req) raw += chunk;
  let code: unknown;
  try {
    code = JSON.parse(raw || "{}").code;
  } catch {
    return reply(res, 400, { error: "the body must be JSON" });
  }
  if (typeof code !== "string" || code.trim() === "") return reply(res, 400, { error: "code must be a non-empty string" });

  try {
    const sandbox = await createSandbox(provider, { variant: "http" }, `run-code-http-${Date.now().toString(36)}`);
    try {
      reply(res, 200, await sandbox.runPython(code));
    } finally {
      await sandbox.kill();
    }
  } catch (error) {
    reply(res, 502, { error: `sandbox error: ${(error as Error).message}` });
  }
}).listen(port);

A call from your own machine shows what the agent gets back:

curl -s -X POST http://127.0.0.1:8787/run-code \
  -H "Authorization: Bearer $RUN_CODE_TOKEN" -H 'content-type: application/json' \
  -d '{"code":"print(sum(range(101)))"}'

You should see:

{"stdout":"5050\n","stderr":""}

And here’s what Cadenya sent for one call, as an echo service at the base URL received it on October 29, 2026, trimmed to the parts your endpoint reads:

{
  "method": "POST",
  "headers": {
    "Authorization": "Bearer dummy-token-for-echo-test",
    "Content-Type": "application/json",
    "User-Agent": "Cadenya-Agent/1.0",
    "X-Cadenya-Objective-Id": "obj_01M64N8E2SATMRXZD1MMJ6SP2H",
    "X-Cadenya-Tool-Call-Id": "toolcall_01M64N8GE7ZRQE6MS1ARFBKGA4"
  },
  "json": {
    "code": "print(6 * 7)"
  }
}

The token came from the tool set secret, and the body from the template. This endpoint starts a new sandbox for each call and kills it before it replies. To keep files between calls, key the sandbox on X-Cadenya-Objective-Id, which names the objective on every call, or use the bare tool, which keeps one sandbox per objective.

What does Cadenya add to Vercel Sandbox?

A sandbox runs the code it’s handed. Vercel’s docs put it in one line: “Run untrusted or agent-generated code in isolated Linux microVMs.” Cadenya is the agent loop around it, hosted, and Vercel Sandbox joins it as one tool set. Here’s what that covers:

  1. The agent loop, with nothing to write or host. Cadenya calls the model, records each tool call, waits for your worker’s result, and calls the model again until the turn is done.
  2. A durable record of every run. Each objective keeps an event log of its loop, with every tool call and its result. List it after a run or stream it while the agent works.
  3. A person approves the code before it runs. requiresApproval parks the loop on toolApprovalRequested, and a denial carries a memo that steers the agent.
  4. Conversations that continue. A Continue message picks a waiting objective back up with the whole conversation. Give its sandbox a fixed name and keep it persistent, and the next SDK call resumes it with the agent’s files.
  5. Your own API next to the sandbox. Point a tool set at your OpenAPI 3 spec, and every operation becomes a tool. Bare, HTTP and MCP tool sets plug in the same way, and any tool can require approval.
  6. Secrets that stay out of the prompt. Tool set secrets use envelope encryption with a unique data key for each value, and Cadenya decrypts them only at the point of use.
  7. Any model, set per variation. The model is a setting on a variation, so a model swap needs no deploy, and weighted selection favors the variations that score well.
  8. The whole setup as files. The agent, its variation and its tools live in .cadenya/, and cadenya config apply or the GitHub Action applies them. SDKs cover TypeScript, Python, Ruby and Go, all at 1.9.0.
  9. A price in one line. Free for 1,000 loops a month, $49 a month for 50,000, then $0.0015 a loop. A loop is one LLM request.

The tool sets guide shows Bare and HTTP tool sets in the app, and the free plan needs no card.

No account yet? A coding agent can create a temporary workspace with cadenya workspaces create --temporary, run its first objectives there, and hand you a link to claim it, as auth.md explains. To create an account, sign up at app.cadenya.com/signup, then copy your API key from the API keys page at app.cadenya.com/account/apiKeys.

Grow wherever AI goes next.

Start shipping agents that are equipped to evolve.

A pine bonsai overlooking a mountain lake