# Run AI-Generated Code in Isolated Sandboxes | Volcano

URL: https://volcano.dev/solutions/agent-sandboxes

> Run the code your AI agent writes on Volcano: one-shot commands or sessions in isolated VMs, per-user workspaces whose files carry over between turns, previews of agent-built apps over short-lived credentials, and request IDs that keep a retry from running a command twice.

## Give the agent its own computer

Run the code an agent writes in an isolated VM, keep each user's files between turns, and open the app it built over a short-lived credential.

```console
$ volcano cloud sandboxes exec --preset python3.12 -- python -c 'print(6 * 7)'
42
$ volcano cloud sandboxes exec --preset node22 -- \
$   node -e 'console.log(process.version)'
v22.22.0
✓ each command ran in its own VM, cleaned up when it exited
# keep a session when the next command needs the last one's files
```

## The agent wrote the code. Something has to run it.

An agent that analyzes a spreadsheet, answers with a chart or fixes a failing test has to execute code nobody has read. Run it inside your function and it shares a process with your service key and your database connection. Start a fresh container for every command and the next turn loses the files, the packages and the server the last one left behind.

On Volcano that code runs in a Sandbox: an isolated VM your backend starts with a service key. Run a single command and the VM is terminated when it finishes, or keep a session per conversation so the files in /workspace and the processes the agent started are still there next turn. Suspend it between turns without paying for the time, open the server it started over a short-lived credential, and retry a command under the same request ID without running it twice.

## The agent runs its code and reads what happened

*Execution*

Write the model's code into the session and run it. stdout, stderr and the exit code come back in one response, and a nonzero exit is a result rather than an error, so a traceback goes back to the model, which fixes the script and runs it again. For a self-contained calculation, skip the session: a one-shot command gets its own VM and is cleaned up when it exits.

- python3.12 and node22 presets, or your own template
- Each session is its own VM, apart from your functions
- Driven from the API, CLI, SDKs, MCP or dashboard

```console
write  /workspace/sales.xlsx   the user's upload
exec   step_1.py               exit 1 · KeyError: 'Region'
write  /workspace/step_2.py    the model fixed the column name
exec   step_2.py               exit 0 · saved revenue_by_region.png
read   /workspace/revenue_by_region.png
✓ the reply quotes what the code printed, not a guess
```

## Each user's files are still there next turn

*Workspaces*

Give each conversation a session instead of a new VM per command. The files in /workspace and the processes the agent started carry over between turns, so a follow-up reads the results the last turn saved instead of recomputing them. Suspend the session when the reply is sent and resume it on the next message: suspended time uses no runtime, and the snapshot behind it is included.

- Suspend keeps processes and files; resume picks them up
- Billed on memory × running time, not per command
- Up to 1 hour per session on Hobby or 8 hours on Superagent

```console
$ volcano cloud sandboxes suspend $SESSION_ID
# twenty minutes later, the user asks a follow-up
$ volcano cloud sandboxes resume $SESSION_ID
$ volcano cloud sandboxes get $SESSION_ID
  "state": "running",
$ volcano cloud sandboxes exec $SESSION_ID -- python /workspace/follow_up.py
read monthly.csv from the last turn
fastest growth in Q3: west, +18.4%
✓ files intact · the twenty minutes suspended used no runtime
```

## Show the user the app the agent built

*Previews*

A coding agent starts its dev server in the session. Your backend checks that the user owns the thread, then asks for a credential bound to that session and that port, which expires within five minutes. The page posts it to set a secure, HTTP-only cookie and the app opens in the browser; once it expires, the page asks for a fresh one and reconnects. HTTP, WebSocket, SSE and gRPC all use the same URL.

- Bound to one session and one port
- Expires within five minutes, never in a query string
- Grant a signed-in user one session, and only that one

```console
# four requests to the same URL
no credential                        → refused
credential issued for port 8080      → refused
credential for 3000, in the header   → 200 · the app renders
same credential, six minutes later   → refused
the credential decided, not the URL
```

## How it works

1. **Pick the environment**: Start from the python3.12 or node22 preset, or deploy a template from a Dockerfile fragment with the libraries your agent needs. Volcano builds and validates it before it goes live.
2. **A session per conversation**: Create it from your backend with a service key and keep its ID on the thread. Grant the signed-in user that session if their browser needs to reach it.
3. **Run each tool call**: Write the model's code to /workspace, run it under a request ID checkpointed in a durable step, and hand stdout, stderr and the exit code back to the model.
4. **Suspend between turns**: Suspend when the reply is sent and resume on the next message. Copy anything worth keeping to file storage before the session ends.

## A tool, a turn, a preview, and the deploy

### The tool

```python
import json
import os
import shlex

from volcano_sdk import ConflictError, VolcanoClient

# Sandboxes take a service key, so these are project variables. The key stays
# in this function; the code the model wrote runs in a VM that never sees it.
client = VolcanoClient(
    anon_key=os.environ["VOLCANO_ANON_KEY"],
    service_key=os.environ["VOLCANO_SERVICE_KEY"],
    api_url=os.environ["VOLCANO_API_URL"],
)
PROJECT_ID = os.environ["VOLCANO_PROJECT_ID"]


def handler(event, context):
    # The agent sends the code the model wrote and one request_id per tool
    # call, and sends the same ID again if it has to retry the call.
    code = event["code"]
    request_id = event["request_id"]

    try:
        # A fresh VM for this one command, terminated once it exits.
        result = client.sandboxes.exec(
            PROJECT_ID,
            f"python -c {shlex.quote(code)}",
            region="us-east-1",
            preset="python3.12",
            request_id=request_id,
        )
    except ConflictError:
        # Same ID, outcome unknown: Volcano refuses rather than run it twice.
        return {"statusCode": 409, "body": json.dumps({"error": "outcome unknown, not rerun"})}

    # A nonzero exit is a result, not an error. The traceback goes back to the
    # model so it can fix the script and call the tool again.
    return {
        "statusCode": 200,
        "body": json.dumps({
            "stdout": result.stdout,
            "stderr": result.stderr,
            "exit_code": result.exit_code,
        }),
    }
```

### The turn

```javascript
const { durable } = require('@volcano.dev/sdk/durable');
const { VolcanoClient } = require('@volcano.dev/sdk');
// Your model call and thread storage, shared with the rest of the app.
const { callModel, loadThread, saveReply, saveSessionId } = require('./_shared/agent');

const client = new VolcanoClient({
  apiUrl: process.env.VOLCANO_API_URL,
  anonKey: process.env.VOLCANO_ANON_KEY,
  accessToken: process.env.VOLCANO_SERVICE_KEY,
});
const projectId = process.env.VOLCANO_PROJECT_ID;

exports.handler = durable(async (input, ctx) => {
  const auth = input.__volcano_auth;
  if (!auth) throw new Error('start this function with a user access token');

  const thread = await ctx.step('load-thread', () => loadThread(auth.user_id, input.thread_id));

  // One session per conversation. Later turns resume it, so whatever the
  // last turn wrote to /workspace is still there.
  const createId = await ctx.step('create-id', () => crypto.randomUUID());
  const sessionId = await ctx.step('open-session', async () => {
    const session = await openSession(thread.session_id, createId);
    await saveSessionId(auth.user_id, thread.id, session.id);
    return session.id;
  });

  let messages = thread.messages;
  let answer = null;
  for (let turn = 1; turn <= 8; turn += 1) {
    const reply = await ctx.step(`model-${turn}`, () => callModel(messages));
    if (!reply.code) {
      answer = reply.content;
      break;
    }

    // Checkpointed, so a retried step sends the same ID. A finished command
    // returns its stored result; an unfinished one is refused, never rerun.
    const requestId = await ctx.step(`request-id-${turn}`, () => crypto.randomUUID());
    const output = await ctx.step(`run-${turn}`, async () => {
      const session = unwrap(await client.sandboxes.get(sessionId));
      const file = `/workspace/step_${turn}.py`;
      unwrap(await session.files.write(file, new TextEncoder().encode(reply.code)));
      const run = unwrap(await session.exec(`python ${file}`, { requestId }));
      // A traceback goes back to the model to fix. It is not a failed step.
      return { stdout: run.stdout, stderr: run.stderr, exitCode: run.exitCode };
    });

    messages = [...messages, reply, { role: 'tool', content: JSON.stringify(output) }];
  }

  // Eight tool calls without an answer still ends in a reply, so the user is
  // never left waiting on a turn that has finished.
  if (answer === null) {
    answer = 'I ran out of steps on this one. Ask me to keep going and I will pick up from the files in this session.';
  }
  await ctx.step('save-reply', () => saveReply(auth.user_id, thread.id, answer));

  // The user reads the reply. Suspended time uses no runtime.
  await ctx.step('suspend', async () => {
    const session = unwrap(await client.sandboxes.get(sessionId));
    unwrap(await session.suspend());
  });
  return { thread_id: thread.id };
});

// Resume the thread's session while it lives; start a new one once it expires.
async function openSession(existingId, requestId) {
  if (existingId) {
    // Replace the session only when it is gone. Any other error fails the
    // step, so the retry keeps the conversation on its own workspace.
    const { data: session, error } = await client.sandboxes.get(existingId);
    if (error && error.status !== 404) throw error;
    if (session && !['terminating', 'terminated'].includes(session.state)) {
      return untilRunning(session);
    }
  }
  const created = await client.sandboxes.create(projectId, {
    preset: 'python3.12',
    region: 'us-east-1',
    maxDurationSeconds: 3600,
    requestId,
  });
  return untilRunning(unwrap(created));
}

// The last turn's suspend may still be finishing, so resume the session once it
// reaches suspended rather than only when it was already there.
async function untilRunning(session) {
  const deadline = Date.now() + 120_000;
  let resumeRequested = false;
  while (session.state !== 'running') {
    if (Date.now() >= deadline || ['unknown', 'terminated'].includes(session.state)) {
      throw new Error(`Session unavailable: ${session.state}`);
    }
    if (session.state === 'suspended' && !resumeRequested) {
      unwrap(await session.resume());
      resumeRequested = true;
    }
    await new Promise((resolve) => setTimeout(resolve, 1000));
    unwrap(await session.refresh());
  }
  return session;
}

function unwrap({ data, error }) {
  if (error) throw error;
  return data;
}
```

### Preview

```javascript
const { Client } = require('pg');
const { VolcanoClient, databaseConnectionString } = require('@volcano.dev/sdk');

// Issuing a port credential takes a service key, kept in project variables.
const client = new VolcanoClient({
  apiUrl: process.env.VOLCANO_API_URL,
  anonKey: process.env.VOLCANO_ANON_KEY,
  accessToken: process.env.VOLCANO_SERVICE_KEY,
});

exports.handler = async (event) => {
  const auth = event.__volcano_auth;
  if (!auth) {
    return { statusCode: 401, body: JSON.stringify({ error: 'sign in required' }) };
  }

  // Read as the caller, so row-level security decides whether this thread,
  // and the session on it, belong to them.
  const db = new Client({
    connectionString: databaseConnectionString(process.env.DATABASE_URL, {
      userId: auth.user_id,
    }),
  });
  await db.connect();
  let rows;
  try {
    ({ rows } = await db.query('select session_id from threads where id = $1', [event.threadId]));
  } finally {
    await db.end();
  }
  if (!rows[0]?.session_id) {
    return { statusCode: 404, body: JSON.stringify({ error: 'no preview for this thread' }) };
  }

  // A coding agent keeps its session running while the user tries the app.
  const { data: session, error } = await client.sandboxes.get(rows[0].session_id);
  if (error) throw error;
  if (session.state !== 'running') {
    return { statusCode: 409, body: JSON.stringify({ error: 'the preview is not running' }) };
  }

  // The agent started its dev server on 3000. This credential works for this
  // session and this port only, and expires within five minutes.
  const access = await session.access(3000);
  if (access.error) throw access.error;

  // token is left out of JSON on purpose, so name it. The page posts it in a
  // form to {url}_volcano/access, which sets an HTTP-only cookie and redirects
  // to the app. Never put it in a query string.
  return {
    statusCode: 200,
    body: JSON.stringify({ url: access.data.url, token: access.data.token }),
  };
};
```

### Ship it

```bash
volcano login
volcano use my-agent

# The service key, API URL and project ID the functions read
volcano cloud variables deploy

# run-python stays private: only your agent's backend calls it
volcano cloud functions deploy -f run-python

# agent-turn is kind: durable in the manifest. The app starts it with the
# user's session, so it admits signed-in users.
volcano cloud durable deploy -f agent-turn --visibility authenticated

# Signed-in users ask for their own preview; the policy decides which
volcano cloud functions deploy -f open-preview
volcano cloud functions update open-preview --visibility authenticated

# When the presets are not enough: ./sandbox holds a Dockerfile fragment and
# its files. Volcano builds and validates it before it goes live.
volcano cloud sandboxes templates deploy analyst --path ./sandbox --memory 1024

# What is running now, and the runtime it has used
volcano cloud sandboxes sessions
volcano cloud sandboxes usage --json
```

## What you pay for, and what you don't

- **0.5 GBh for 30 minutes at 1 GiB**: Runtime is configured memory times running time, so a session that runs twenty commands costs the same as one that runs one.
- **0 GBh while a session is suspended**: Suspended time uses no allowance or credits, and the snapshot that keeps its files and processes is included.
- **1 VM per session**: Each hosted session is its own isolated VM, so there is no execution fleet of yours to run or to keep apart from your data.

## Outcomes

- **Isolated by default**: Code the model wrote runs in its own VM, never in your function.
- **Context that carries over**: A follow-up reads the files the last turn left in /workspace.
- **No double runs**: A command retried under the same request ID is never run a second time.

## Built on Volcano

- [Where the code runs](https://volcano.dev/features/sandboxes): Isolated VMs from a preset or your own template, as one-shot commands or sessions with files, processes and HTTP ports.
- [The agent loop](https://volcano.dev/features/durable-functions): Durable functions that checkpoint each model call, command and request ID, so a retry never runs the code twice.
- [Who can reach a session](https://volcano.dev/features/authentication): Signed-in users your backend grants one session to, who can run commands and connect but never create or terminate one.
- [Files that outlive the session](https://volcano.dev/features/file-storage): Buckets for the uploads the agent reads and the charts and reports it produces, kept after the session ends.

## Frequently asked questions

### How is the agent's code kept away from my app?

It runs in a Sandbox, not in your function. Each hosted session is its own isolated VM, so the code the model wrote never shares a process with your service key, your database connection or another user's session. Only a service key, a platform token or a full-scope project access token can create one, anonymous keys are refused, and a signed-in user reaches a session only after your backend grants it. Local Sandboxes run as Docker containers that share your machine's kernel, so use hosted ones when you need VM isolation.

### Which languages and libraries can the code use?

Start from the python3.12 or node22 preset. When the agent needs more, deploy a custom template: a Dockerfile fragment using RUN, COPY and CMD, without FROM, on a base image Volcano supplies. Volcano builds and validates it before it activates, and sessions already running keep the image they started with. Deploy it from the CLI, the API, an SDK or the dashboard.

### How long do a session's files last?

As long as the session. Files in /workspace and running processes survive suspend and resume, and are removed when the session is terminated or reaches its lifetime: up to 1 hour on Hobby or 8 hours on Superagent, counted from creation with suspended time included. Copy anything worth keeping, such as a chart or a report, to file storage before then. A suspended session keeps its capacity reserved, so terminate it when the conversation is over.

### How does a user open the app the agent built?

Have the agent start the server in the session, then request a credential for that session and port from your backend. It expires within five minutes. Send it as the X-Volcano-Sandbox-Token header, or have the page post it in a form to the URL followed by \_volcano/access, which sets a secure, HTTP-only cookie and redirects to the app. The start command can return before the server listens, so poll a health route first. To let the user's own client in, grant them the session instead: a grant lets one signed-in user run commands, use files and connect to that session, never create, suspend or terminate one.

### What happens when a command is retried?

Send the same request ID and it is not run again. A command that finished returns its stored result. One whose outcome is unknown, because it is still running or its result was lost, is refused with a 409. A new ID means a new command, so create one per intent, and inside a durable function create it in a step so a replay reuses it.

### How is it billed?

By configured memory times running time. A 1 GiB session running for 30 minutes uses 0.5 GBh however many commands it runs, idle time between them included. Suspended time is free and snapshots are included. Hobby includes 5 GBh per monthly cycle, up to 1 GiB per session and 5 sessions at a time, and refuses new starts and resumes once the allowance is used. Superagent includes 20 GBh, then 25 credits per 5 GBh block, with up to 2 GiB per session and no plan limit on concurrency beyond a 100-session safety ceiling. Local sessions are not billed.

## Get started

Ready to give your agent a sandbox? Create a free account at https://volcano.dev/signup, or have your coding agent follow the setup playbook at https://volcano.dev/setup.md.
