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

# Code sandbox legacy SDK

> Reference for the earlier code sandbox offering built on the CodeSandbox SDK.

<Note>
  This page covers the deprecated code sandbox SDK. Use the [`together-sandbox` SDK](/docs/together-code-sandbox) for new integrations.
</Note>

The legacy code sandbox SDK gives you a fully configurable development environment with fast start-up times, robust snapshotting, and a suite of mature dev tools. It can spin up a sandbox by cloning a template in under three seconds. Inside this VM, you can run any code, install any dependencies, and run servers.

Under the hood, the SDK uses the microVM infrastructure of CodeSandbox to spin up sandboxes. It supports:

* Memory snapshot and restore (checkpointing) at any point in time.
* Resuming or cloning VMs from a snapshot in three seconds.
* VM filesystem persistence, with git version control.
* Environment customization using Docker and Docker Compose (Dev Containers).

## Access

The legacy code sandbox is available on Together's [custom plans](https://www.together.ai/contact-sales). A self-serve option is available by creating an account with [CodeSandbox](https://codesandbox.io/pricing).

<Note>
  [CodeSandbox](https://codesandbox.io/blog/joining-together-ai-introducing-codesandbox-sdk) is a Together company, and its products are migrating to the Together platform. The [`together-sandbox` SDK](/docs/together-code-sandbox) is the successor to this offering. Within CodeSandbox.io, this offering is called the CodeSandbox SDK.
</Note>

## Get started

Install the SDK:

```bash theme={null}
npm install @codesandbox/sdk
```

Then create an API token at [codesandbox.io/t/api](https://codesandbox.io/t/api) by selecting **Create API Token**. Use this token to authenticate with the SDK:

```typescript TypeScript theme={null}
import { CodeSandbox } from "@codesandbox/sdk";

const sdk = new CodeSandbox(process.env.CSB_API_KEY!);

const sandbox = await sdk.sandboxes.create();

const session = await sandbox.connect();

const output = await session.commands.run("echo 'Hello World'");

console.log(output); // Hello World
```

## Sandbox lifecycle

By default a sandbox is created from a template. A template is a memory and filesystem snapshot of a sandbox, so a new sandbox is a direct continuation of the template. If the template was running a dev server, that dev server is running when the sandbox is created.

When you create, resume, or restart a sandbox, you can read its `bootupType` to see how it started:

* **`FORK`:** The sandbox was created from a template. This happens when you call `create` successfully.
* **`RUNNING`:** The sandbox was already running when you called `resume`.
* **`RESUME`:** The sandbox was resumed from hibernation.
* **`CLEAN`:** The sandbox was created or resumed from scratch because it was not running and had no snapshot. This can happen if the sandbox was shut down or restarted, the snapshot expired, or something went wrong.

## Manage `CLEAN` bootups

When a sandbox boots from scratch, the platform:

1. Starts the Firecracker VM.
2. Creates a default user, called pitcher-host.
3. Builds the Docker image specified in `.devcontainer/devcontainer.json`, if one is configured.
4. Starts the Docker container.
5. Mounts the `/project/sandbox` directory as a volume inside the Docker container.

You can connect to the sandbox during this process and track its progress:

```javascript JavaScript theme={null}
const sandbox = await sdk.sandboxes.create();

const setupSteps = sandbox.setup.getSteps();

for (const step of setupSteps) {
  console.log(`Step: ${step.name}`);
  console.log(`Command: ${step.command}`);
  console.log(`Status: ${step.status}`);

  const output = await step.open();

  output.onOutput((output) => {
    console.log(output);
  });

  await step.waitUntilComplete();
}
```

## Use templates

Code sandbox has default templates that you can use to create sandboxes. These templates are available in the Template Library, and the "Universal" template is used by default. To create your own template, use the CodeSandbox CLI.

### Create a template

Create a new folder in your project and add the files you want available inside your sandbox. For example, set up a Vite project:

```bash theme={null}
npx create-vite@latest my-template
```

Configure the template with tasks so that it installs dependencies and starts the dev server. Create a `my-template/.codesandbox/tasks.json` file with the following content:

```json theme={null}
{
  "setupTasks": ["npm install"],
  "tasks": {
    "dev-server": {
      "name": "Dev Server",
      "command": "npm run dev",
      "runAtStart": true
    }
  }
}
```

The `setupTasks` run after the sandbox has started, before any other tasks.

Deploy the template to the clusters:

```bash theme={null}
CSB_API_KEY=<your_api_key> npx @codesandbox/sdk build ./my-template --ports 5173
```

<Note>
  The template is built with the Micro VM tier unless you pass `--vmTier` to the build command.
</Note>

This creates sandboxes for each of the clusters, writes files, restarts, waits for port 5173 to be available, and then hibernates. This generates the snapshot that lets you quickly create sandboxes already running a dev server from the template.

When all clusters are updated successfully, you get back a template tag to use when you create sandboxes:

```javascript JavaScript theme={null}
const sandbox = await sdk.sandboxes.create({
  source: "template",
  id: "some-template-tag",
});
```

## Connect to sandboxes in the browser

In addition to running your sandbox on the server, you can connect it to the browser. This requires some collaboration with the server:

```javascript JavaScript theme={null}
app.post("/api/sandboxes", async (req, res) => {
  const sandbox = await sdk.sandboxes.create();
  const session = await sandbox.createBrowserSession({
    // Create isolated sessions by using a unique reference to the user
    id: req.session.username,
  });

  res.json(session);
});

app.get("/api/sandboxes/:sandboxId", async (req, res) => {
  const sandbox = await sdk.sandboxes.resume(req.params.sandboxId);
  const session = await sandbox.createBrowserSession({
    // Resume any existing session by using the same user reference
    id: req.session.username,
  });

  res.json(session);
});
```

Then in the browser:

```javascript JavaScript theme={null}
import { connectToSandbox } from "@codesandbox/sdk/browser";

const sandbox = await connectToSandbox({
  // The session object you either passed on page load or fetched from the server
  session: initialSessionFromServer,
  // When reconnecting to the sandbox, fetch the session from the server
  getSession: (id) => fetchJson(`/api/sandboxes/${id}`),
});

await sandbox.fs.writeTextFile("test.txt", "Hello World");
```

The browser session manages the connection automatically and reconnects if the connection is lost. This is controlled by an option called `onFocusChange`, and by default it reconnects when the page is visible:

```javascript JavaScript theme={null}
const sandbox = await connectToSandbox({
  session: initialSessionFromServer,
  getSession: (id) => fetchJson(`/api/sandboxes/${id}`),
  onFocusChange: (notify) => {
    const onVisibilityChange = () => {
      notify(document.visibilityState === "visible");
    };

    document.addEventListener("visibilitychange", onVisibilityChange);

    return () => {
      document.removeEventListener("visibilitychange", onVisibilityChange);
    };
  },
});
```

If you tell the browser session when it is in focus, it reconnects automatically when hibernated, unless you explicitly disconnect the session.

While the `connectToSandbox` promise is resolving, you can listen to initialization events to show a loading state:

```javascript JavaScript theme={null}
const sandbox = await connectToSandbox({
  session: initialSessionFromServer,
  getSession: (id) => fetchJson(`/api/sandboxes/${id}`),
  onInitCb: (event) => {},
});
```

## Disconnect the sandbox

Disconnecting the session ends the session and automatically hibernates the sandbox after a timeout. You can also hibernate the sandbox explicitly from the server:

```javascript JavaScript theme={null}
import { connectToSandbox } from "@codesandbox/sdk/browser";

const sandbox = await connectToSandbox({
  session: initialSessionFromServer,
  getSession: (id) => fetchJson(`/api/sandboxes/${id}`),
});

// Disconnect returns a promise that resolves when the session is disconnected
sandbox.disconnect();

// Optionally hibernate the sandbox explicitly by creating an endpoint on your server
fetch("/api/sandboxes/" + sandbox.id + "/hibernate", {
  method: "POST",
});

// You can reconnect explicitly from the browser by
sandbox.reconnect();
```

## Pricing

The self-serve option for running the legacy code sandbox is priced according to the CodeSandbox SDK plans, which have two main pricing components:

* **VM credits:** The unit of measurement for VM runtime. One credit equates to a specific amount of resources used per hour, depending on the specs of the VM you are using. VM credits follow a pay-as-you-go approach and are priced at \$0.01486 per credit.
* **VM concurrency:** The maximum number of VMs you can run simultaneously with the SDK. Each CodeSandbox plan has a different VM concurrency limit.

<Note>
  Minutes are the smallest unit of measurement for VM credits. If a VM runs for 3 minutes and 25 seconds, you are billed the equivalent of 4 minutes of VM runtime.
</Note>

### VM credit prices by VM size

The table below summarizes how many VM credits each VM size uses per hour of runtime. The Nano VM size is the default recommendation, as it provides enough resources for most simple workflows. Pico is mostly suitable for very simple code execution jobs.

| VM size | Credits / hour | Cost / hour | CPU | RAM |
| :- | :- | :- | :- | :- |
| Pico | 5 credits | \$0.0743 | 2 cores | 1 GB |
| Nano | 10 credits | \$0.1486 | 2 cores | 4 GB |
| Micro | 20 credits | \$0.2972 | 4 cores | 8 GB |
| Small | 40 credits | \$0.5944 | 8 cores | 16 GB |
| Medium | 80 credits | \$1.1888 | 16 cores | 32 GB |
| Large | 160 credits | \$2.3776 | 32 cores | 64 GB |
| XLarge | 320 credits | \$4.7552 | 64 cores | 128 GB |

### Concurrent VMs

Pick the plan that matches how many concurrent VMs you require:

* Build (free) plan: 10 concurrent VMs.
* Scale plan: 250 concurrent VMs.
* Enterprise plan: custom concurrent VMs.

If you expect a high volume of VM runtime, the Enterprise plan also provides discounts on VM credits. For enterprise pricing, [contact sales](https://www.together.ai/contact-sales).

### Estimate your bill

To estimate your bill, you must consider:

* The base price of your CodeSandbox plan.
* The number of included VM credits on that plan.
* How many VM credits you expect to require.

As an example, say you plan to run 80 concurrent VMs on average, each running 3 hours per day, every day, on the Nano VM size:

* You need a Scale plan.
* You use a total of 72,000 VM credits per month (80 VMs x 3 hours/day x 30 days x 10 credits/hour).
* Your Scale plan includes 1,100 free VM credits each month, so you purchase 70,900 VM credits.

Based on this, your expected bill for that month is:

* Base price of the Scale plan: \$170.
* Total price of VM credits: \$1,053.57 (70,900 VM credits x \$0.01486 per credit).
* Total bill: \$1,223.57.

## Further reading

Learn more about sandbox configuration and features in the [CodeSandbox SDK documentation](https://codesandbox.io/docs/sdk/manage-sandboxes).


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