@spheron/sandbox
v0.1.1
Published
Run commands and move files on a Spheron Agent GPU Sandbox from code.
Readme
@spheron/sandbox
Run commands and move files on a Spheron Agent GPU Sandbox from your own code. It is the same sandbox an AI agent gets through the Spheron connector, driven with a GPU VM API key instead.
A sandbox is a real GPU VM you keep for hours: files, packages and models stay on it between jobs, and your own SSH key keeps working the whole time. A VM takes a few minutes to boot, so it suits training, fine-tuning, evals and long jobs, not one-off snippets.
Zero dependencies. Node 18 or later, Bun and Deno. It is an ES module: CommonJS code loads it with require('@spheron/sandbox') on Node 20.19+ and 22.12+, or with await import('@spheron/sandbox') on older Node.
bun add @spheron/sandboxQuickstart
Create a GPU VM API key in the dashboard (Settings, API Keys) and export it:
export SPHERON_API_KEY=sai_pk_...import { Sandbox } from '@spheron/sandbox';
// Cheapest H100 offer up to $3/hour that can take the sandbox. Waits until commands can run (a few minutes).
const sandbox = await Sandbox.create({ gpu: 'h100', gpuCount: 1, maxHourlyPrice: 3 });
const gpu = await sandbox.commands.run('nvidia-smi --query-gpu=name,memory.total --format=csv');
console.log(gpu.output);
await sandbox.files.write('/root/train.py', trainScript);
const job = await sandbox.commands.start('cd /root && python train.py', { timeoutSec: 6 * 3600 });
for await (const chunk of job.stream()) process.stdout.write(chunk);
const metrics = await sandbox.files.read('/root/metrics.json');
await sandbox.terminate(); // billing stopsThe instance bills at its normal hourly price from the moment it runs until you stop or terminate it.
Creating a sandbox
Sandbox.create() lists offers, deploys the cheapest match with the sandbox on and waits for it. When an offer is sold out or cannot take the sandbox, it moves on to the next one (nothing is created or billed for a refused offer).
| Option | Default | |
|---|---|---|
| gpu | any | GPU model, one word: h100, a100, l40s, rtx4090 |
| gpuCount | any | GPUs per instance |
| maxHourlyPrice | none | Most to pay per hour for the whole instance, in USD. Set it. |
| spot | false | Spot offers only: cheaper, and can be reclaimed at any time |
| regions, providers | all | Narrow the search |
| offer | | Deploy this exact offer (from Sandbox.findOffers()) |
| operatingSystem | Ubuntu with CUDA | Matched against the offer's options |
| teamId | your only team | Required when the key reaches several teams |
| sshKeyId / sshPublicKey | first saved key | Your own access to the VM. Always installed. |
| volumeIds | | Volumes to attach at launch |
| waitUntilReady | true | Return as soon as the create is accepted when false |
| readyTimeoutMs | 20 min | |
| onStatus | | Called with deploying, installing, ready |
To choose by hand:
const offers = await Sandbox.findOffers({ gpu: 'a100', maxHourlyPrice: 2 });
console.table(offers.map((o) => ({ provider: o.provider, gpus: o.gpuCount, region: o.region, price: o.price })));
const sandbox = await Sandbox.create({ offer: offers[0] });Pick one up again later, from any process:
const sandbox = await Sandbox.connect('6650c0ffee...'); // the deployment idCommands
Commands run with bash as the VM's login user, with sudo. Output is stdout and stderr together, up to 1 MB per command. The full log stays on the VM at logPath, readable with sandbox.files.read(r.logPath).
A finished command's status is done when it exits 0 and failed for a non-zero exit (with its exitCode), a timeoutSec kill (error is timed out) or a lost command.
// Wait for it to finish. Killed after timeoutSec (default 600).
const r = await sandbox.commands.run('pip install -r requirements.txt', { cwd: '/root/app', timeoutSec: 1800 });
r.exitCode; r.output;
// Throw CommandExitError unless it exits 0.
await sandbox.commands.run('pytest -q', { check: true });
// Live output.
await sandbox.commands.run('python bench.py', { onOutput: (chunk) => process.stdout.write(chunk) });
// Background job (up to 24 hours): returns at once.
const job = await sandbox.commands.start('python train.py', { env: { WANDB_MODE: 'offline' } });
job.id; // keep it to come back later: sandbox.commands.get(id)
await job.wait({ timeoutMs: 60_000 }).catch(() => {}); // stop waiting, the job keeps running
await job.kill(); // stops it and everything it startedA command sent while the VM is briefly unreachable stays queued and runs once the sandbox is back.
Files
await sandbox.files.write('/root/config.yaml', 'lr: 0.001\n');
await sandbox.files.write('/root/run.sh', script, { mode: '0755' });
const text = await sandbox.files.read('/root/out.txt');
const bytes = await sandbox.files.readBytes('/root/plot.png');
const entries = await sandbox.files.list('/root'); // [{ name, type, size }]
await sandbox.files.exists('/root/checkpoint.pt');File operations run as root, and a file you write belongs to the VM's login user. Missing parent directories are created. Each read or write moves up to 5 MB, and an account moves at most two files at once (the SDK waits and retries). Download datasets and models on the VM itself:
await sandbox.commands.run('huggingface-cli download meta-llama/Llama-3.1-8B --local-dir /root/model', { timeoutSec: 3600 });Lifecycle
await sandbox.status(); // { state: 'ready', reachable: true, deploymentRunning: true, ... }
await sandbox.info(); // the deployment: status, IP, sshCommand, hourlyRate, ...
await sandbox.stop(); // keeps the disk, bills only storage; waits until the provider has stopped it
await sandbox.start(); // waits until it runs and the sandbox is reachable; retries while the provider is not ready
await sandbox.terminate(); // deleted with its disk; after the offer's minimum runtime (usually 20 min)
await sandbox.removeSandbox(); // uninstall the sandbox program, keep the VMErrors
Every error extends SpheronError. API refusals are SpheronApiError with status, code and requestId.
| Error | When |
|---|---|
| AuthenticationError | Missing or wrong key, or an Inference API key |
| NotFoundError | No such instance, no sandbox on it, or a teammate deployed it (only the deployer can use a sandbox) |
| InstanceNotRunningError | The VM is stopped, terminated or failed |
| SandboxNotReadyError | Still installing |
| SandboxUnreachableError | Spheron cannot reach the VM. recovery.command, run over SSH on the VM, brings it back. From commands.run() it also has commandId: the command stays queued and runs once the VM is back, unless you kill it |
| SandboxFailedError | The install failed or the VM died while waiting. Has deploymentId and, when it helps, recoveryCommand |
| CommandExitError | check: true and a non-zero exit |
| NoOfferError | No offer matched, or every one tried was refused (attempts says why) |
| TimeoutError | A wait in the SDK ran out. The VM or command keeps running |
Once an instance exists, every error about it carries its deploymentId: it bills until it is terminated.
Safe requests that hit a dropped connection or a 502/503/504 are retried with backoff (maxRetries, default 3). A 429 is retried for up to 90 seconds, waiting as long as the API asks. File transfers already queue in the SDK: at most 2 run at once per sandbox, the server's limit.
Configuration
Sandbox.create({ apiKey: 'sai_pk_...', baseUrl: 'https://app.spheron.ai', maxRetries: 3, requestTimeoutMs: 90_000, pollIntervalMs: 2000 });apiKey defaults to SPHERON_API_KEY, baseUrl to SPHERON_BASE_URL. requestTimeoutMs bounds one HTTP request; waits such as waitUntilReady take their own timeoutMs. A key scoped to some teams or IP addresses works within that scope.
Good to know
- Only the person who deployed a VM can use its sandbox. Teammates get
NotFoundError. - Every command is logged with its text and exit code. Output and file contents are not.
- The sandbox program only connects outwards to Spheron. It opens no port on the VM.
License
Apache License 2.0. See LICENSE.
