Buddy Sandboxes
Persistent Ubuntu VMs from Buddy.Works with tracked commands, native files, HTTP tunnels, clones and disk snapshots.
Installation
pnpm add sbox-sdk @buddy-works/sandbox-sdk@0.3.0The optional provider SDK loads lazily when an operation needs it. Pin 0.3.0,
as Buddy recommends for its pre-1.0 SDK. Its actual Node engine range is
^20.19.0 || >=22.12.0, which is narrower than the core SDK's range.
Authentication
Enable API access in your Buddy workspace settings. Use a personal access token
with SANDBOX_READ for reads, SANDBOX_WRITE for mutations, and
SANDBOX_MANAGE for deleting sandboxes and snapshots.
export BUDDY_TOKEN="your-token"
export BUDDY_WORKSPACE="your-workspace"
export BUDDY_PROJECT="your-project"
export BUDDY_REGION="US" # optional; US, EU or ASFactory options token, workspace, project, region and apiUrl override
these environment variables. apiUrl falls back to BUDDY_API_URL, including
/api when your self-hosted installation requires it. A region selects the API
host and account location. To use another region, construct another provider;
spec.region must match it.
client.verify() makes one authenticated project list request and never creates
anything. Authorization errors mention API activation and token scopes.
Usage
import { createSandboxClient } from "sbox-sdk";
import { buddy } from "sbox-sdk/buddy";
const client = createSandboxClient({ provider: buddy() });
const sandbox = await client.create({
template: "ubuntu:24.04",
metadata: { application: "agent" },
resources: { vcpus: 2, memoryMB: 4096 },
lifecycle: { idleTimeoutMs: 300_000, onIdle: "stop" },
});
try {
for await (const event of sandbox.commands.run("npm test", {
cwd: "/buddy/app",
env: { CI: "true" },
timeoutMs: 60_000,
})) {
if (event.type === "stdout") process.stdout.write(event.data);
if (event.type === "stderr") process.stderr.write(event.data);
}
await sandbox.files.write("/buddy/result.bin", new Uint8Array([0, 255]));
const saved = await sandbox.snapshots!.create({ name: "after-tests" });
// Disk snapshots can seed a new VM, but cannot restore this VM in place.
const copy = await client.create({ fromSnapshot: saved });
await copy.destroy();
} finally {
await sandbox.destroy();
}getInfo() refreshes live status. STARTING and RESTORING map to creating;
RUNNING with setup INPROGRESS also maps to creating. Setup FAILED or VM
FAILED maps to error. STOPPING and STOPPED map to stopped. Setup STALE
means configuration needs recreation and remains visible in info.raw.
list() fetches Buddy's complete project collection, hydrates full records for
metadata and setup state, then applies metadata, state and limit filters. The
current list endpoint has no cursor or page parameters.
Named creates and getOrCreate() reuse the identifier. A create idempotency key
derives a stable identifier (sbox-<hash>), and a conflicting concurrent create
reconnects to the winner. Buddy does not expose a native idempotency header, so
idempotency is exact by way of the unique identifier: a retried create looks
the identifier up first, and a racing create gets a conflict instead of a second
VM. A reused VM is started if it is stopped and awaited until it is running.
Commands and files
The published SDK's Command.logs() merges stdout and stderr. This adapter
uses a Node child-process wrapper in the VM to frame each stream's bytes before
Buddy combines them. Streaming is therefore emulated, with UTF-8 decoding
across chunk boundaries and real execution exit codes. Node must remain installed
inside custom snapshot VMs. Commands run as buddy; a custom ExecOptions.user
is rejected. The wrapper honors cwd/env, finite stdin and a timeout that kills the
child process group. Kill uses Buddy's cancellation API, not a local disconnect.
Interactive writeStdin / closeStdin, arbitrary signals and PTY are unsupported.
The framed command, including finite stdin and per-command env values, is retained
in Buddy command history. Do not put credentials there; use encrypted sandbox variables.
Background commands use native tracked executions. Process listing and cancellation can use Buddy's retained history, limited to the latest 200 executions. Split-output reattachment is limited to processes started on the same adapter handle.
Uploads use native multipart file transfers; file downloads request octet-stream
bytes. Directory downloads as archives are not exposed as ordinary files.
Binary and 5 MB round-trips are covered offline. Rename uses a quoted mv command;
other file operations use the native API. Code execution starts fresh Python,
JavaScript or TypeScript processes, with no persistent kernel.
Previews and browser auth
const client = createSandboxClient({
provider: buddy({
previewAuth: {
username: "preview",
password: process.env.BUDDY_PREVIEW_PASSWORD!,
},
}),
});
const sandbox = await client.create();
const preview = await sandbox.ports!.expose(3000, { visibility: "private" });
// preview.auth.type === "header", containing Basic Authorization.Public previews use HTTP endpoints with auth_type: NONE. Private previews
require stable explicit Basic credentials and report auth: header.
previewBrowserAuth is false: headers cannot authenticate browser WebSockets.
Buddy's signed-in-user endpoints are not converted into public URLs or presented
as browser token authentication. Port listing omits Buddy-login endpoints and
Basic endpoints whose credentials this adapter cannot supply. Keep the same
previewAuth when reconnecting. Endpoint updates preserve unrelated definitions and reapply known Basic credentials.
They reject changes when existing Basic credentials or TLS private keys cannot
be preserved safely;
coordinate updates from other handles or the Buddy UI to avoid concurrent replacements.
Snapshot templates
const template = await client.templates!.build({
name: "prepared",
source: { snapshot: "your-existing-snapshot-id" },
readyCmd: "test -d /buddy/app",
});
const sandbox = await client.create({ template });Builds boot a temporary VM from the source snapshot, wait for readiness, and save a disk snapshot whose name records the alias and
cache key. The temporary VM is deleted. This is billable work in your account.
Only snapshot sources are supported. Docker images, Dockerfiles, template
env, resources, workdir, user and startCmd settings are rejected because
disk snapshots do not persist the corresponding VM configuration. Supply env and
resources at sandbox creation instead. Snapshots survive deletion
of their source VM. Clone uses Buddy's native clone API; snapshot memory capture
and in-place restore are unsupported.
Capabilities
| Capability | Level | Notes |
|---|---|---|
background / killProcess | native | tracked executions; kill uses Buddy's cancellation API |
streaming | emulated | an in-VM Node wrapper frames stdout and stderr, so they stay separate |
filesUpload | native | multipart upload |
list | native | the complete project collection, hydrated per sandbox |
stop | native | the disk persists (preservesDiskOnStop), RAM does not |
snapshot / fork | native | disk only; fork uses Buddy's clone API |
exposePort / privatePreview | native | HTTP endpoints; private ones use Basic auth from previewAuth |
region | native | selects the API account (US, EU, AS); spec.region must match |
templateBuild | emulated | builds a disk snapshot from a snapshot source |
codeInterpreter | emulated | fresh Python, JavaScript or TypeScript process per call |
pause / setTimeout | unsupported | memory pause and hard-age limits don't exist; use stop() |
stdin / pty | unsupported | stdin on run() is finite only |
egressControl / volumes | unsupported | |
filesWatch / proxiedFetch | unsupported | |
ssh / metrics | unsupported | Buddy's UI and CLI still provide SSH |
gpu / secretsVault | unsupported | inline encrypted secrets work; named vault references are rejected |
statefulKernel | unsupported |
perCommandEnvCwd and exitCodeNative are true. previewModel is tunnel
and previewBrowserAuth is false.
How the spec maps
| sbox | Buddy |
|---|---|
template | os (ubuntu:22.04 / ubuntu:24.04), or a built snapshot template id or alias |
fromSnapshot / templateRef | create from snapshot |
name / idempotencyKey | name and identifier (sbox-<hash> when unnamed; a retried create reuses it) |
env, env-mode secrets | variables (secrets are encrypted) |
metadata | encoded tags |
resources.vcpus / memoryMB | resources tier, rounded up to the smallest paired size |
region | must match the provider's region |
lifecycle.idleTimeoutMs | timeout, in whole seconds rounded up |
ports | HTTP endpoints, public or Basic-auth by previewVisibility |
template strings select Ubuntu 22.04/24.04 or a built snapshot template.
fromSnapshot accepts any snapshot ID. Env values and inline secrets must be
valid variable keys, and a secret may not reuse an env key. A sandbox created with
private visibility keeps future adapter previews private, including after
reconnect.
The create contract for this adapter:
| Field | Level | Behavior |
|---|---|---|
idempotency | exact | unique identifier derived from the key; a racing retry reconnects to the winner |
resources.vcpus / memoryMB | approximate | rounded up to Buddy's paired tier, from 1 vCPU / 2 GiB to 12 vCPU / 24 GiB |
resources.diskMB | rejected | Buddy's disk is a fixed 50 GiB; only 51200 is accepted |
resources.shmMB, gpu | rejected | throws Validation |
lifecycle.idleTimeoutMs | approximate | rounded up to whole seconds (idleTimeoutStepMs: 1000) |
lifecycle.maxAgeMs / ttlMs | rejected | Buddy has no hard-age limit |
onIdle other than stop, autoResume: false, volumes, egress policies and
named vault secrets also throw Validation. Stop preserves disk, not RAM, and
endpoint traffic always wakes a stopped VM; commands do not.
No maxPorts or label limits are declared: the adapter enforces none, and Buddy
documents none. Metadata entries share the sandbox's tag list with one adapter
tag, sbox-private-preview.
Size presets
Buddy sells fixed paired tiers (1x2 through 12x24: N vCPU and 2N GiB) on a
fixed 50 GiB disk, so spec.size lands on a real tier:
| Preset | Tier | Resources |
|---|---|---|
small | 1x2 | 1 vCPU, 2 GB memory, 50 GB disk |
medium | 2x4 | 2 vCPU, 4 GB memory, 50 GB disk |
large | 4x8 | 4 vCPU, 8 GB memory, 50 GB disk |
xlarge | 8x16 | 8 vCPU, 16 GB memory, 50 GB disk |
Fields in resources override the preset, so size: "large" with
resources: { diskMB: 100_000 } is rejected. Use resources.vcpus and
memoryMB for the other tiers.
Verification limits
Tests use MiniShell offline conformance, the real 0.3.0 SDK over a fake authenticated transport, and the exact VM wrapper on local Node. They do not prove live account permissions, tunnel propagation, VM cancellation behavior, snapshot naming limits or provider quotas. The live configuration is opt-in through the required Buddy environment variables; running it creates paid resources.