> ## Documentation Index
> Fetch the complete documentation index at: https://docs.costgraph.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Route sandboxes with ComputeSDK

> Send each new sandbox to the provider in your list that fits your policy, and see what every sandbox costs per agent, run, and customer.

AutoPilot for sandboxes chooses which of your sandbox providers starts each new
sandbox and records when each sandbox starts and stops. You then see what your
sandboxes cost by provider and by tags such as agent, run, or customer.

It works with [ComputeSDK](https://github.com/computesdk/computesdk), the open
source TypeScript SDK for many sandbox providers. You wrap your ComputeSDK
providers with `@costgraph/computesdk`, and every other ComputeSDK call stays
the same. Your sandboxes run in your own provider accounts, each provider bills
you as before, and your provider keys stay in your process.

Two other ways to use AutoPilot for sandboxes are available:

* From another language, call the [REST API](https://docs.costgraph.ai/costgraph/autopilot/sandboxes-api.md).
* To have CostGraph start sandboxes on the provider accounts your team
  connected on Integrations, refer to
  [Run sandboxes on your connected accounts](https://docs.costgraph.ai/costgraph/autopilot/sandboxes-connected.md).

## Requirements

* A CostGraph API key with the `sandbox:route` scope. Create it in
  **Settings > API Keys**.
* Node.js 18 or later, or another runtime with a global `fetch`.
* `computesdk` 4.1.15 or later, and the ComputeSDK package for each provider
  you use, such as `@computesdk/e2b`.

## Set up the sandbox SDK

**1. Install the package**

Store the API key in your environment as `COSTGRAPH_API_KEY`, then install
`@costgraph/computesdk` next to ComputeSDK.

```shell theme={null}
npm install @costgraph/computesdk computesdk
```

**2. Wrap your providers**

Move your ComputeSDK providers inside `costgraph()`. The first provider in
the list is the baseline. Your sandboxes use it while AutoPilot is off, and
AutoPilot compares every other provider with it.

```ts theme={null}
import { compute } from 'computesdk';
import { modal } from '@computesdk/modal';
import { vercel } from '@computesdk/vercel';
import { costgraph } from '@costgraph/computesdk';

const cg = costgraph({
  apiKey: process.env.COSTGRAPH_API_KEY,
  providers: [
    modal({ tokenId: MODAL_TOKEN_ID, tokenSecret: MODAL_TOKEN_SECRET }),
    vercel({ token: VERCEL_TOKEN, teamId: VERCEL_TEAM_ID, projectId: VERCEL_PROJECT_ID }),
  ],
});
compute.setConfig({ provider: cg });
```

**3. Tag your sandboxes**

Pass a size and tags when you create a sandbox. CostGraph groups cost by
the tags in `metadata`.

```ts theme={null}
const sandbox = await compute.instances.create({
  sizeClass: 'md',
  metadata: { agent: 'researcher', run: runId, customer: customerId },
});
```

The `run` tag is the sandbox's run key. Refer to
[Group cost by run](#group-cost-by-run).

**4. Check that sandboxes arrive**

Create a sandbox, then open **AutoPilot** in CostGraph and select the
**Sandboxes** tab. The sandbox appears under **History** with its
provider, size, and tags.

CostGraph now tracks what every sandbox costs. Your sandboxes still start on
the first provider in your list until you [turn on routing](#turn-on-routing).

### Flush reports on shutdown

The package sends start and stop reports in the background and does not keep
your process running. Before your process exits, await `flush()`. It resolves
within 10 seconds by default, or within the limit you pass in milliseconds.

```ts theme={null}
process.on('SIGTERM', async () => {
  await cg.flush(5_000);
  process.exit(0);
});
```

On edge runtimes such as Cloudflare Workers, pass the flush to the runtime with
`ctx.waitUntil(cg.flush())`.

### Package options

`costgraph()` accepts the following options.

| Option | Default | Description |
| - | - | - |
| `apiKey` | Required | Your CostGraph API key. If it is empty, sandboxes start in list order and nothing is reported. |
| `providers` | Required | Your ComputeSDK providers. Each must have a unique `name`. |
| `baseUrl` | `https://api.costgraph.ai` | The CostGraph API address. On a [self-hosted installation](https://docs.costgraph.ai/costgraph/self-hosted/overview.md), set your installation's API address. |
| `tenantId` | None | The tenant to report to, sent as the `X-CostGraph-Tenant-ID` header. |
| `routeTimeoutMs` | `300` | The longest a create waits for a routing answer, in milliseconds. |
| `cacheTtlMs` | `300000` | How long a routing answer is reused, in milliseconds. |
| `fetch` | Global `fetch` | A custom `fetch` implementation. |
| `onError` | Ignore | A function that receives CostGraph errors, for logging. |
| `fallbackOnError` | `true` | Set to `false` to never try another provider after a failed create. ComputeSDK's own `fallbackOnError` does not reach a wrapped provider. |

## Turn on routing

AutoPilot for sandboxes is off by default. While it is off, every sandbox
starts on the first provider in your list, and CostGraph still records its cost.

**1. Open the settings**

In CostGraph, open **AutoPilot**, select the **Sandboxes** tab, and select
**Settings**. Only admins can change these settings.

**2. Turn it on**

Turn on **Enabled** and select a **Routing policy**. The default is
**Cheapest**. Refer to [Policies](#policies).

New sandboxes pick up the change within five minutes, as cached routing
answers expire. **Ready timeout** applies only to sandboxes
that CostGraph starts for you. Refer to
[Readiness limit](https://docs.costgraph.ai/costgraph/autopilot/sandboxes-connected.md#readiness-limit).

## How a provider is chosen

When you create a sandbox with a `sizeClass`, the package asks CostGraph to
order your providers for that size. It then creates the sandbox on the first
provider in that order. The following rules apply:

* Only providers that support the size take part. Refer to [Sizes](#sizes).
  If none does, `create()` throws ComputeSDK's `InstanceSizeError`.
* Your order is kept when AutoPilot is off, when the sandbox has no size, and
  when your first provider has no list price for the size.
* Only the first 20 providers are priced. A provider name CostGraph does not
  recognize keeps its place without a price.

### Expected cost and start time

AutoPilot compares providers on expected cost, start time, and success rate.

* **Expected cost** is the list price for the size over the expected run time,
  rounded up to the provider's billing increment and minimum billed time. The
  expected run time is the median of your stopped sandboxes of that size from
  the last 30 days, capped at 24 hours. Until you have 20 of them, it is 10
  minutes.
* **Start time** is the median time from the create request until the sandbox
  started, over your sandboxes of that size on that provider in the last 30
  days.
* **Success rate** is the share of your creates on that provider in the last 30
  days, at any size, that started.

Until you have 20 starts on a provider, AutoPilot uses
[ComputeSDK's public burst benchmark](https://github.com/computesdk/benchmarks)
for its start time and success rate. A provider outside the benchmark has
neither figure until you have 20 starts there.

### Policies

Each policy orders your providers differently. A single sandbox can request
another policy than the one in **Settings**.

| Policy | Order |
| - | - |
| **Cheapest** | Lowest expected cost first. A provider whose start time is more than twice the baseline's goes after the other priced providers. |
| **Balanced** | The best combination of saving and start time first, among providers that cost no more than the baseline and start within the baseline's start time plus 100 ms or 10%, whichever is larger. |
| **Fastest** | The fastest start first, among providers that cost no more than the baseline. |

In every policy, a provider other than the baseline with a success rate below
95% moves to the end. Providers without a price come after the priced ones.
The baseline stays first when no provider improves on it, and remaining ties
keep your order. The
[routing endpoint reference](https://docs.costgraph.ai/api-reference/sandboxes/choose-the-provider-for-a-new-sandbox.md)
gives the full tie-break order.

### When CostGraph doesn't answer

A create waits up to `routeTimeoutMs` for a routing answer. If CostGraph is
slow, unreachable, or returns an error, the sandbox starts in your list order.
After a failed call, the package uses your list order for 30 seconds before it
asks again. A late answer is cached for the next create.

If your team has a budget set to stop sandboxes, the package waits up to 5
seconds instead. An over budget removes the providers it covers from the order.
When no provider is left, or when CostGraph cannot be reached, `create()` throws
and no sandbox starts. Refer to the `enforce` field of
[Create a budget](https://docs.costgraph.ai/api-reference/budgets/create-a-budget.md).

### When a provider fails

If the chosen provider fails to create the sandbox, the package tries the next
provider in CostGraph's order, then your providers that the answer left out. It
does not try another provider in the following cases, which match ComputeSDK:

* The create has a `sizeClass` or names a provider.
* The create was aborted, or the provider marks the error as not safe to retry.
* `fallbackOnError` is `false`.

The package reports each refused create as a failed start, which lowers that
provider's success rate. A create from a snapshot, or with volumes the package
saw created or listed, goes to the provider that holds them.

### Choose the provider yourself

To skip routing for one sandbox, call the `costgraph()` provider directly and
name the provider. CostGraph still records the sandbox.

```ts theme={null}
const sandbox = await cg.instances.create({ provider: 'e2b', metadata: { agent: 'researcher' } });
```

`compute.instances.create({ provider: 'e2b' })` does not work for this, because
`compute` knows only the `costgraph` provider.

## Sizes

`sizeClass` requests one of ComputeSDK's standard sizes.

| Size | vCPUs | Memory |
| - | - | - |
| `xs` | 1 | 1 GiB |
| `sm` | 1 | 2 GiB |
| `md` | 2 | 4 GiB |
| `lg` | 4 | 8 GiB |
| `xl` | 8 | 16 GiB |
| `2xl` | 16 | 32 GiB |

A provider whose ComputeSDK package maps sizes itself receives the size
unchanged. For the following providers, the package turns the size into the
provider's own create options.

| Provider | Sizes | Notes |
| - | - | - |
| Beam | `xs` to `xl` | |
| Daytona | `xs` to `lg` | Only with `image`, such as `image: 'python:3.12'`, and without `snapshotId` or `templateId`. |
| Modal | `xs` to `2xl` | |
| Northflank | `xs` to `2xl` | |
| Runloop | `xs` to `2xl` | Creates 1 vCPU with 2 GiB for `xs`. |
| Vercel | `xs` to `xl` | Creates 1 vCPU with 2 GiB for `xs`. 16 vCPUs need an Enterprise plan. |

Runloop and Vercel are used for `xs` only when none of your other providers
creates exactly 1 vCPU with 1 GiB. CostGraph then records the size they
created. ComputeSDK rejects CPU and memory options such as `cpu`, `memory`, or
`resources` next to `sizeClass`.

E2B sets CPU and memory per template, so it does not take part in sized
creates. Build an E2B template at the size you need, then create sandboxes
from it by name without `sizeClass`.

```ts theme={null}
const sandbox = await cg.instances.create({ provider: 'e2b', templateId: 'agent-md' });
```

A sandbox without a size stays on your first provider, because each
provider's default size differs. CostGraph prices it at the provider's
documented default size when the price list gives one, and **History** labels
it **Default size**.

## What CostGraph receives

The package sends only the following to CostGraph:

* Your provider names and the size of each create.
* For each sandbox, its provider, sandbox ID, create, start, and stop times,
  and the routing answer it used.
* For each refused create, its provider, time, failure class, and error
  message, cut to 2,000 bytes.
* Your `metadata` string values and the run key. It sends at most 20 keys of up
  to 64 bytes, with values cut to 256 bytes.

CostGraph does not receive your provider keys, code, commands, environment
variables, files, or command output. The package sends reports in batches
every 2 seconds and drops them after a few failed retries.

The package also sets the run key as the label `costgraph.ai/run` on the
sandbox, for providers whose ComputeSDK package passes metadata or labels on.
These are Blaxel, CreateOS, Daytona, E2B, Freestyle, GravixLayer, Lizard,
Microsandbox, Miosa, Novita, OpenComputer, Promigence, Runloop, Sprites,
Superserve, and Tenki.

## Read the Sandboxes tab

Open **AutoPilot** and select the **Sandboxes** tab. The date range at the top
of the page sets the period. The tab opens with the following totals.

| Tile | Meaning |
| - | - |
| **Sandboxes** | Sandboxes reported starting in the period. |
| **Estimated cost** | Each sandbox's run time, up to 24 hours, billed the way its provider bills, at the list price for its size. |
| **Saved** | What routed sandboxes would have cost on your first provider, minus what they cost. |
| **Routed** | Sandboxes AutoPilot started on a provider other than your first. |
| **Running** | Sandboxes with no stop reported yet. |
| **Unpriced** | Sandboxes with no list price for their provider or size. They add no cost. |

A sandbox counts toward **Saved** only when it started on the provider
AutoPilot chose, at the size it was routed for.

The tab has the following views:

* **Managed** shows cost by provider, cost by tag for the 50 most expensive
  tags, and failed starts by provider.
* **Settings** turns routing on and sets the policy.
* **History** lists each sandbox with its provider, size, run time, cost, and
  tags. A routed sandbox shows how the provider was chosen and what it would
  have cost elsewhere.
* **Runs** lists each agent run with its sandbox cost, model cost, and total.

## Group cost by run

A run key groups the sandboxes and model calls of one agent run, so you see
what the whole run cost. Set the run key as the `run` tag on each sandbox of
the run. A sandbox without a `run` tag gets its own generated key, which you
read with `cg.runKey(sandboxId)`.

To add the run's model calls, send the same run key with that run's usage
through your AI gateway. Refer to
[Group usage by agent run](https://docs.costgraph.ai/costgraph/integrations/ai-gateways.md#group-usage-by-agent-run).
The key must match the `run` tag exactly.

A [workflow run](https://docs.costgraph.ai/costgraph/workflows/goals-and-runs.md) also shows its
**Workflow agent** cost, which CostGraph pays for and does not add to the
run's total.

## Limits

* **A sandbox that ends without `destroy()` is not reported as stopped.** This
  includes a sandbox that the provider's own timeout ends. It shows as
  **Running** until its run time reaches 24 hours. Call `destroy()` on every
  sandbox you finish with.
* **Costs are estimates from list prices.** They exclude discounts, credits,
  and included usage. To see billed spend, connect the provider on the
  [Integrations](https://docs.costgraph.ai/costgraph/integrations/overview.md) page where CostGraph
  supports it.

## Related

* [Use AutoPilot for sandboxes from any language](https://docs.costgraph.ai/costgraph/autopilot/sandboxes-api.md)
* [Run sandboxes on your connected accounts](https://docs.costgraph.ai/costgraph/autopilot/sandboxes-connected.md)
* [AutoPilot for CI](https://docs.costgraph.ai/costgraph/autopilot/ci.md)
* [Roles and permissions](https://docs.costgraph.ai/costgraph/security/roles.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.