---
title: "Quickstart: your first sandbox | Pethost Agent Sandboxes"
description: "Create a sandbox, run a command, write a file, open a port and clean up: from Python, TypeScript, Go, Rust, the pethost CLI or your agent."
---

[Agent Sandboxes docs](https://pethost.dev/docs/sandboxes/) · Start

# Quickstart: your first sandbox

Updated 22 November 2026 · 11 min read

Your first sandbox in a few minutes: install an SDK, make an API token, create a sandbox, run a command in it, write a file, open a port to the internet, let it pause, and delete it. Each step is one call, in Python, TypeScript, Go or Rust, and the same steps follow with the `pethost` CLI.

**In short**

- **One package:** the SDK you already know from Pethost, with a client for sandboxes beside it: `pethost.sandboxes`, `pethost/sandboxes`, `github.com/pethost-dev/sdk/go/sandboxes`, `pethost::sandboxes`.
- **One token:** an API token in `PETHOST_TOKEN`. The client finds each sandbox's server and its token by itself.
- **One id:** every call names its sandbox by `sandbox_id`.
- **Nothing to clean up by hand:** a sandbox you forget pauses after 5 minutes and stops after 30.

## Install an SDK

The sandboxes' client is part of Pethost's SDK in each language, so one install gives you both. Python 3.10, Node 22 (or Bun, or Deno), Go 1.26 and Rust 1.88 or newer.

Python

```
pip install pethost
```

TypeScript

```
npm install pethost          # or: bun add pethost
deno add jsr:@pethost/sdk    # Deno: import from "@pethost/sdk/sandboxes"
```

Go

```
go get github.com/pethost-dev/sdk/go
```

Rust

```
cargo add pethost
cargo add tokio --features macros,rt-multi-thread,time
```

CLI

```
curl -fsSL https://pethost.dev/install.sh | sh    # macOS, Linux
irm https://pethost.dev/install.ps1 | iex         # Windows, in PowerShell
```

## Make an API token

### Step 1: Make a workspace of Agent Sandboxes

Sign in at [console.pethost.dev](https://console.pethost.dev/) and make a workspace, choosing Agent Sandboxes. A new account's first one starts with a trial: 7 days with $1 of usage and 4 vCPUs, a card required.

### Step 2: Create a token for it

In the workspace, open **Connect an agent or your code** and press **Create an API token**. The token starts with `pth_`, reaches this workspace only, and is shown once. Your tokens are listed, and revoked, in your account's Settings.

### Step 3: Give it to your program

```
export PETHOST_TOKEN=pth_...
```

The Python client and the CLI read it from the environment; the programs below pass it to the TypeScript, Go and Rust clients. Keep it out of your code: it acts as your account.

## Create a sandbox

A sandbox starts from a template. Ours, `base`, is Ubuntu 24.04 with Python, Node.js, Docker, three coding agents and Chrome. `CreateSandbox` answers once the sandbox runs, in about 0.15 s on the server's side, plus your round trip to the panel.

Python

```
from pethost.sandboxes import Sandboxes

sandboxes = Sandboxes()  # reads PETHOST_TOKEN
sandbox = sandboxes.create_sandbox("base")
print(sandbox.sandbox_id, sandbox.state.name)  # 5a4c9z5zw58mvqww RUNNING
```

TypeScript

```
import { Sandboxes } from "pethost/sandboxes";

const sandboxes = new Sandboxes({ token: process.env.PETHOST_TOKEN! });
const sandbox = await sandboxes.createSandbox({ template: "base" });
const sandboxId = sandbox.sandboxId;
console.log(sandboxId, sandbox.state);
```

Go

```
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/pethost-dev/sdk/go/sandboxes"
)

func main() {
	ctx := context.Background()
	client := sandboxes.NewClient(sandboxes.Config{Token: os.Getenv("PETHOST_TOKEN")})

	sandbox, err := client.CreateSandbox(ctx, &sandboxes.CreateSandboxRequest{Template: "base"})
	if err != nil {
		log.Fatal(err)
	}
	id := sandbox.SandboxID
	fmt.Println(id, sandbox.State)

	// The next steps go on here.
}
```

Rust

```
use pethost::sandboxes::{types::*, Client};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let sandboxes = Client::new(&std::env::var("PETHOST_TOKEN")?);
    let sandbox = sandboxes
        .create_sandbox(CreateSandboxRequest { template: "base".into(), ..Default::default() })
        .await?;
    let id = sandbox.sandbox_id.clone();
    println!("{id} {:?}", sandbox.state);

    // The next steps go on here.
    Ok(())
}
```

HTTP

```
curl -s https://console.pethost.dev/pethost.sandboxes.v1.SandboxService/CreateSandbox \
  -H "Authorization: Bearer $PETHOST_TOKEN" -H "Content-Type: application/json" \
  -d '{"template": "base"}'
# {"sandbox_id": "w86eeaozgndh3gj2", "state": "SANDBOX_STATE_RUNNING", "template": "base@17", …,
#  "connection": {"url": "https://sbx1.sandboxes.pethost.network", "token": "…", …}}
```

Keep the id: every other call names the sandbox by it. You can also give a sandbox a `name`, unique in the workspace, which `ListSandboxes` finds it by.

## Run a command

`RunCommand` runs a shell command as the user `user` in `/home/user`, and answers when it ends, with its exit code and the last 32 KiB of its output. A command that takes longer than 45 s answers RUNNING and goes on: [commands and files](https://pethost.dev/docs/sandboxes/commands-and-files/) says how to follow it.

Python

```
command = sandboxes.run_command(sandbox.sandbox_id, command="python3 -c 'print(6 * 7)'")
print(command.exit_code, command.stdout)  # 0 42
```

TypeScript

```
const command = await sandboxes.runCommand({ sandboxId, command: "python3 -c 'print(6 * 7)'" });
console.log(command.exitCode, command.stdout); // 0 42
```

Go

```
command, err := client.RunCommand(ctx, &sandboxes.RunCommandRequest{SandboxID: id, Command: "python3 -c 'print(6 * 7)'"})
if err != nil {
	log.Fatal(err)
}
fmt.Println(*command.ExitCode, command.Stdout) // 0 42
```

Rust

```
let command = sandboxes
    .run_command(RunCommandRequest {
        sandbox_id: id.clone(),
        command: "python3 -c 'print(6 * 7)'".into(),
        ..Default::default()
    })
    .await?;
println!("{:?} {}", command.exit_code, command.stdout); // Some(0) 42
```

HTTP

```
# URL and TOKEN: connection.url and connection.token of the create's answer
curl -s "$URL/pethost.sandboxes.v1.SandboxRuntimeService/RunCommand" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{"sandbox_id": "'"$ID"'", "command": "python3 -c '\''print(6 * 7)'\''"}'
# {"commandId": "efpe95t24evu", "state": "COMMAND_STATE_EXITED", "exitCode": 0, "stdout": "42\n", …}
```

The command went to the sandbox's own server, not to the panel. The SDK took the server's address and a token for this sandbox from the create's answer, and asks for new ones by itself when they expire.

## Write and read a file

`WriteFiles` makes changes in order, in one call: it writes files whole, edits one by exact replacement, moves and deletes. Paths are absolute, or relative to `/home/user`, and missing directories are made.

Python

```
from pethost.sandboxes import FileChange, TextEdit

sandboxes.write_files(sandbox.sandbox_id, changes=[
    FileChange(path="app/hello.py", text="print('hello')\n"),
    FileChange(path="app/hello.py", edit=TextEdit(old_text="hello", new_text="hello, sandbox")),
])
print(sandboxes.read_file(sandbox.sandbox_id, path="app/hello.py").text)  # print('hello, sandbox')
```

TypeScript

```
await sandboxes.writeFiles({
  sandboxId,
  changes: [
    { path: "app/hello.py", text: "print('hello')\n" },
    { path: "app/hello.py", edit: { oldText: "hello", newText: "hello, sandbox" } },
  ],
});
const file = await sandboxes.readFile({ sandboxId, path: "app/hello.py" });
console.log(file.text);
```

Go

```
_, err = client.WriteFiles(ctx, &sandboxes.WriteFilesRequest{SandboxID: id, Changes: []sandboxes.FileChange{
	{Path: "app/hello.py", Change: sandboxes.FileChangeText("print('hello')\n")},
	{Path: "app/hello.py", Change: sandboxes.FileChangeEdit{OldText: "hello", NewText: "hello, sandbox"}},
}})
if err != nil {
	log.Fatal(err)
}
file, err := client.ReadFile(ctx, &sandboxes.ReadFileRequest{SandboxID: id, Path: "app/hello.py"})
if err != nil {
	log.Fatal(err)
}
if text, ok := file.Content.(sandboxes.FileText); ok {
	fmt.Print(string(text))
}
```

Rust

```
let write = |change| FileChange { path: "app/hello.py".into(), change: Some(change), ..Default::default() };
sandboxes
    .write_files(WriteFilesRequest {
        sandbox_id: id.clone(),
        changes: vec![
            write(FileChangeChange::Text("print('hello')\n".into())),
            write(FileChangeChange::Edit(TextEdit { old_text: "hello".into(), new_text: "hello, sandbox".into() })),
        ],
    })
    .await?;
let file = sandboxes
    .read_file(ReadFileRequest { sandbox_id: id.clone(), path: "app/hello.py".into(), ..Default::default() })
    .await?;
if let Some(FileContent::Text(text)) = file.content {
    print!("{text}");
}
```

A change that fails stops the batch, and the answer says how many were done and why the next one failed (`failure`): an edit whose `old_text` is not in the file, or is there twice, changes nothing.

## Open a port to the internet

Start a server with `wait_for_port`: the call answers as soon as something listens on the port, while the server runs on. Then make the port public. It gets an address of its own, `https://<port>-<sandbox id>.<server>`, which anyone can open.

Python

```
from pethost.sandboxes import Ingress, PublicPort, SandboxSettings

sandboxes.run_command(sandbox.sandbox_id, command="python3 -m http.server 8000", wait_for_port=8000)
sandbox = sandboxes.update_sandbox(
    sandbox.sandbox_id,
    settings=SandboxSettings(ingress=Ingress(public_ports=[PublicPort(port=8000)])),
)
print(sandbox.settings.ingress.public_ports[0].url)
# https://8000-5a4c9z5zw58mvqww.sbx1.sandboxes.pethost.network
```

TypeScript

```
await sandboxes.runCommand({ sandboxId, command: "python3 -m http.server 8000", waitForPort: 8000 });
const updated = await sandboxes.updateSandbox({
  sandboxId,
  settings: { ingress: { publicPorts: [{ port: 8000 }] } },
});
console.log(updated.settings?.ingress?.publicPorts[0]?.url);
```

Go

```
_, err = client.RunCommand(ctx, &sandboxes.RunCommandRequest{SandboxID: id, Command: "python3 -m http.server 8000", WaitForPort: 8000})
if err != nil {
	log.Fatal(err)
}
updated, err := client.UpdateSandbox(ctx, &sandboxes.UpdateSandboxRequest{SandboxID: id, Settings: &sandboxes.SandboxSettings{
	Ingress: &sandboxes.Ingress{PublicPorts: []sandboxes.PublicPort{{Port: 8000}}},
}})
if err != nil {
	log.Fatal(err)
}
fmt.Println(updated.Settings.Ingress.PublicPorts[0].URL)
```

Rust

```
sandboxes
    .run_command(RunCommandRequest {
        sandbox_id: id.clone(),
        command: "python3 -m http.server 8000".into(),
        wait_for_port: 8000,
        ..Default::default()
    })
    .await?;
let ingress = Ingress { public_ports: vec![PublicPort { port: 8000, ..Default::default() }] };
let updated = sandboxes
    .update_sandbox(UpdateSandboxRequest {
        sandbox_id: id.clone(),
        settings: Some(SandboxSettings { ingress: Some(ingress), ..Default::default() }),
        ..Default::default()
    })
    .await?;
if let Some(ingress) = updated.settings.and_then(|settings| settings.ingress) {
    println!("{}", ingress.public_ports[0].url);
}
```

MCP

```
UpdateSandbox {"sandbox_id": "…", "settings": {"ingress": {"public_ports": [{"port": 8000}]}}}
```

Open the address in a browser, or with `curl`: the directory listing of `/home/user` comes back. A port that is not public answers only requests that carry a token for it: [ports and previews](https://pethost.dev/docs/sandboxes/ports-and-previews/).

## Let it pause

Leave the sandbox alone for 5 minutes and it pauses: its memory, its processes and its disk are kept on its server, at 30% of the running price. The next call, SSH login or request to its port wakes it in about 0.1 s, where it was. Here it is paused at once, and the web server is still there after the wake:

Python

```
print(sandboxes.pause_sandbox(sandbox.sandbox_id).state.name)  # PAUSED
check = sandboxes.run_command(sandbox.sandbox_id, command="curl -s -o /dev/null -w '%{http_code}' localhost:8000")
print(check.stdout)  # 200: the server ran on through the pause
print(sandboxes.get_sandbox(sandbox.sandbox_id).state.name)  # RUNNING
```

TypeScript

```
console.log((await sandboxes.pauseSandbox({ sandboxId })).state); // PAUSED
const check = await sandboxes.runCommand({
  sandboxId,
  command: "curl -s -o /dev/null -w '%{http_code}' localhost:8000",
});
console.log(check.stdout); // 200: the server ran on through the pause
console.log((await sandboxes.getSandbox({ sandboxId })).state); // RUNNING
```

Go

```
paused, err := client.PauseSandbox(ctx, &sandboxes.PauseSandboxRequest{SandboxID: id})
if err != nil {
	log.Fatal(err)
}
fmt.Println(paused.State) // PAUSED
check, err := client.RunCommand(ctx, &sandboxes.RunCommandRequest{
	SandboxID: id,
	Command:   "curl -s -o /dev/null -w '%{http_code}' localhost:8000",
})
if err != nil {
	log.Fatal(err)
}
fmt.Println(check.Stdout) // 200: the server ran on through the pause
```

Rust

```
let paused = sandboxes
    .pause_sandbox(PauseSandboxRequest { sandbox_id: id.clone(), ..Default::default() })
    .await?;
println!("{:?}", paused.state); // Paused
let check = sandboxes
    .run_command(RunCommandRequest {
        sandbox_id: id.clone(),
        command: "curl -s -o /dev/null -w '%{http_code}' localhost:8000".into(),
        ..Default::default()
    })
    .await?;
println!("{}", check.stdout); // 200: the server ran on through the pause
```

MCP

```
PauseSandbox {"sandbox_id": "…"}
```

After 30 idle minutes it stops: its processes end, and its disk goes to object storage, where it costs $0.03 a GiB a month of what it holds. `ResumeSandbox` starts it again. [Lifecycle and idle](https://pethost.dev/docs/sandboxes/lifecycle/) has the timers and how to change them.

## Delete it

`DeleteSandbox` drops the sandbox's memory and disk for good and answers its final record, with what it used.

Python

```
gone = sandboxes.delete_sandbox(sandbox.sandbox_id)
print(gone.state.name, gone.usage)
# DELETED Usage(running_seconds=11, paused_seconds=0, stored_gib_hours=0.0, cost_micros=0)
# cost_micros is what was charged so far: its last seconds are charged a moment later,
# and get_sandbox(sandbox.sandbox_id).usage then says cost_micros=110
```

TypeScript

```
const gone = await sandboxes.deleteSandbox({ sandboxId });
console.log(gone.state, gone.usage);
```

Go

```
gone, err := client.DeleteSandbox(ctx, &sandboxes.DeleteSandboxRequest{SandboxID: id})
if err != nil {
	log.Fatal(err)
}
fmt.Println(gone.State, *gone.Usage)
```

Rust

```
let gone = sandboxes
    .delete_sandbox(DeleteSandboxRequest { sandbox_id: id, ..Default::default() })
    .await?;
println!("{:?} {:?}", gone.state, gone.usage);
```

MCP

```
DeleteSandbox {"sandbox_id": "…"}
```

## The same from the pethost CLI

`pethost sandbox`, or `pethost sbx`, does each of these steps from a terminal, through the Go SDK. A sandbox's name works wherever its id does.

### Step 1: Sign in

```
$ pethost login
```

It signs in in your browser. In a script, set `PETHOST_TOKEN` instead.

### Step 2: Make a sandbox

```
$ pethost sandbox new --name api-dev
✓ Made sandbox api-dev (exdei47yr5je70v5): default, running, from base@17, in <1 s
exdei47yr5je70v5
Next:   pethost sandbox run exdei47yr5je70v5 -- <command>   ·   pethost sandbox shell exdei47yr5je70v5
```

The id is printed alone on stdout, so `id=$(pethost sandbox new)` keeps it.

### Step 3: Run a command, and copy files in

```
$ pethost sandbox run api-dev -- python3 -c 'print(6 * 7)'
42
$ pethost sandbox cp ./app api-dev:app
✓ Copied ./app to exdei47yr5je70v5:app · 2 KB in <1 s
```

### Step 4: Open a port

```
$ pethost sandbox run api-dev -d --wait-for-port 8000 -- python3 -m http.server 8000
It runs on in the sandbox. Its output so far:  pethost api GetCommand '{"sandbox_id": "exdei47yr5je70v5", "command_id": "5f2mo5wikluq"}'
5f2mo5wikluq
$ pethost sandbox ports api-dev --open 8000
8000   https://8000-exdei47yr5je70v5.sbx1.sandboxes.pethost.network
```

### Step 5: Pause it, and delete it

```
$ pethost sandbox pause api-dev
exdei47yr5je70v5   paused
$ pethost sandbox rm api-dev --yes
exdei47yr5je70v5   deleted
```

With several workspaces of sandboxes, name one with `-w`. [The CLI's reference](https://pethost.dev/docs/cli/) has every command.

## The same from your agent

An agent that speaks MCP gets sandboxes as tools: add `https://mcp.pethost.dev/sandboxes` to Claude Code, Codex, Cursor or Claude, sign in in your browser, and ask it to run something in a sandbox. [Connect an agent](https://pethost.dev/docs/sandboxes/connect-an-agent/) has the steps for each.

## What the client does for you

Two services answer. The panel, at `console.pethost.dev`, keeps each sandbox's record: create, settings, pause, fork, delete. The sandbox's own server runs what happens inside it: commands, files, the desktop, links and coding agents. A call of the second kind needs that server's address and a token for that one sandbox. The client takes both from the answer of `CreateSandbox` or `ForkSandbox`, or asks `ConnectSandbox` for them, keeps them until shortly before they expire, and asks again once when a server refuses them. Your API token never goes to a sandbox's server.

A call that makes something takes a `request_id`. The TypeScript client gives each call one when you leave it out, and keeps it when it repeats the call at a new connection, so the server does it once. Send your own and send it again when you retry after a lost answer: the retry answers what the first call did, for 24 hours.

## Which workspace a call acts in

A call that names a sandbox acts in that sandbox's workspace. Any other call acts in the workspace its request names (`workspace`, by id or name), else in the one the client was made with, else in your only workspace of sandboxes. A token that reaches several and a call that names none is refused with `WorkspaceChoice`, which lists them.

## When it does not work

- **`FAILED_PRECONDITION` with `WorkspaceChoice`:** the token reaches several workspaces of sandboxes. Name one: `Sandboxes(workspace="...")`, `workspace` in the request, or `-w` for the CLI.
- **`PERMISSION_DENIED` on `CreateSandbox`:** the token was not granted this workspace. Make one in the workspace's own **Connect an agent or your code**, or grant it in Settings.
- **`UNAUTHENTICATED`:** the token is missing, mistyped or revoked. Check `PETHOST_TOKEN` in the shell that runs the program.
- **`RESOURCE_EXHAUSTED` with `LimitReached`, `vcpus`:** the workspace's sandboxes hold all its vCPUs, running and paused ones alike. The trial has 4: one DEFAULT sandbox, or two SMALL. Delete or stop one, or ask for `SMALL`.
- **`RESOURCE_EXHAUSTED` with `LimitReached`, `starts_per_minute`, `_hour` or `_day`:** too many starts in that window. Starts are free, and bounded: `retry_time` says when the call fits. [Limits](https://pethost.dev/docs/sandboxes/limits/#starts) has each plan's.
- **The command answers RUNNING:** it took longer than 45 s and runs on. `GetCommand` with its `command_id` waits again.

[Errors](https://pethost.dev/docs/sandboxes/errors/) lists every refusal and what to do.

## Questions

### Do I need a separate SDK for sandboxes?

No. The sandboxes' client is part of Pethost's SDK in Python, TypeScript, Go and Rust: install `pethost` and import its sandboxes module.

### Where do I get an API token?

In the console, in your workspace of sandboxes: Connect an agent or your code, then Create an API token. It starts with `pth_` and is shown once.

### Is there a free trial?

Yes: 7 days with $1 of usage and 4 vCPUs, for a new account's first workspace of sandboxes. A card is required.

### What happens if I forget a sandbox?

It pauses after 5 idle minutes and stops after 30, so it costs only its stored data. It is never deleted unless you delete it or set `delete_after_idle_seconds`.

### Can I call the API without an SDK?

Yes. Both services speak Connect, gRPC and gRPC-Web: a POST of JSON to `/pethost.sandboxes.v1.SandboxService/<Method>` with your token works, and the [API reference](https://pethost.dev/docs/sandboxes/api/) has every field.

[PreviousHow Pethost Agent Sandboxes work](https://pethost.dev/docs/sandboxes/how-it-works/) [NextConnect an agent to sandboxes over MCP](https://pethost.dev/docs/sandboxes/connect-an-agent/)

## Try Pethost Agent Sandboxes

A 7-day trial with $1 of usage and 4 vCPUs, with a card. Then a plan from $20 a month, which includes as much usage.

[Start the trial](https://console.pethost.dev/)

Pethost · Stephan Gomer · NIP 1133096755

Pethost

- [Templates](https://pethost.dev/templates/)
- [About](https://pethost.dev/about/)
- [Docs](https://pethost.dev/docs/)
- [Blog](https://pethost.dev/blog/)
- [API](https://pethost.dev/docs/api/)
- [CLI](https://pethost.dev/docs/cli/)
- [Plugin](https://github.com/pethost-dev/plugin)
- [Terms](https://pethost.dev/terms/)
- [Privacy](https://pethost.dev/privacy/)
- [Refunds](https://pethost.dev/refunds/)
- [support@pethost.dev](mailto:support@pethost.dev)

Databases

- [Postgres](https://pethost.dev/postgres/)
- [Valkey](https://pethost.dev/valkey/)

Agent Sandboxes

- [Sandboxes](https://pethost.dev/sandboxes/)
- [Pricing](https://pethost.dev/sandboxes/#pricing)
- [Docs](https://pethost.dev/docs/sandboxes/)
- [API](https://pethost.dev/docs/sandboxes/api/)

Comparisons

- [Coolify vs Dokploy vs CapRover vs Dokku](https://pethost.dev/blog/coolify-vs-dokploy-vs-caprover-vs-dokku/)
- [Coolify Cloud vs Dokploy Cloud](https://pethost.dev/blog/coolify-cloud-vs-dokploy-cloud/)
- [Railway vs Render vs Fly.io pricing](https://pethost.dev/blog/railway-vs-render-vs-fly-io-pricing/)
- [Managed Docker Compose hosting](https://pethost.dev/blog/managed-docker-compose-hosting/)

Alternatives

- [Railway alternatives](https://pethost.dev/blog/railway-alternatives/)
- [Heroku alternatives](https://pethost.dev/blog/heroku-alternatives/)
- [Dokploy alternatives](https://pethost.dev/blog/dokploy-alternatives/)
- [Coolify alternatives](https://pethost.dev/blog/coolify-alternatives/)
- [Render alternatives](https://pethost.dev/blog/render-alternatives/)
- [Sliplane alternatives](https://pethost.dev/blog/sliplane-alternatives/)
