This is the abridged developer documentation for dvm.run
# What dvm.run is
> Overview of dvm.run and a first sandbox in Python, TypeScript, and Rust.
dvm.run runs Docker images in sandboxes you create, drive, and stop through an API from Python, TypeScript, or Rust. Every sandbox runs on dvm, a deterministic virtual machine, and is recorded automatically. Once it exits, seek (replay the recording to a chosen moment) to any point in the run, step through events, and read files as they existed then. ## A first sandbox * Python python/examples/first_sandbox.py
```python
from dvm import Sandbox
with Sandbox.create("python:3.12") as sandbox:
result = sandbox.run(["python", "-c", "print('hello from a sandbox')"])
print(result.exit_code, result.stdout.decode(), end="")
sandbox.write_file("/tmp/notes.txt", b"written before the end\n")
sandbox.end()
point = sandbox.seek()
print(point.read_file("/tmp/notes.txt").decode(), end="")
```
* TypeScript js/examples/first-sandbox.ts
```ts
import { Sandbox } from "dvm-run";
await using sandbox = await Sandbox.create("python:3.12");
const result = await sandbox.run(["python", "-c", "print('hello from a sandbox')"]);
console.log(result.exitCode, new TextDecoder().decode(result.stdout));
await sandbox.writeFile("/tmp/notes.txt", new TextEncoder().encode("written before the end\n"));
await sandbox.end();
const point = await sandbox.seek();
console.log(new TextDecoder().decode(await point.readFile("/tmp/notes.txt")));
```
* Rust rust/dvm-run/examples/first_sandbox.rs
```rust
#[tokio::main]
async fn main() -> dvm_run::Result<()> {
let client = dvm_run::Client::from_env()?;
let sandbox = client.create_sandbox("python:3.12").await?;
sandbox
.scope(async |sandbox| {
let result = sandbox
.run(["python", "-c", "print('hello from a sandbox')"])
.await?;
print!(
"{} {}",
result.exit_code,
String::from_utf8_lossy(&result.stdout)
);
sandbox
.write_file("/tmp/notes.txt", b"written before the end\n")
.await?;
Ok(())
})
.await?;
let point = sandbox.seek_end().await?;
let notes = point.read_file("/tmp/notes.txt").await?;
print!("{}", String::from_utf8_lossy(¬es));
Ok(())
}
```
This creates a sandbox from `python:3.12`, waits for it to start, runs a command, prints its exit code and output, and writes a file. Closing its input ends the sandbox. Seeking to the end returns a point (a recorded moment in the run) where you can read that file back. Install an SDK and set an API key to run it:
```sh
pip install dvm-run # Python 3.12 or newer
npm install dvm-run # Node 22.12 or newer
cargo add dvm-run tokio --features tokio/macros,tokio/rt-multi-thread
export DVM_API_KEY=... # a key from the panel, or run `dvm-run login`
```
Follow [Getting in](/start/access/) to get an account and API key. ## Where next [Getting in](/start/access/)Sign in, join the waitlist, and get an API key. [For coding agents](/start/agents/)Shortest path to a working sandbox, plus Markdown docs. [Sessions](/guides/sessions/)Run commands and transfer files. [Inspecting a finished run](/guides/inspect/)Seek to a point, step through events, and read files.
# For coding agents
> Quickest path for coding agents to install an SDK, authenticate without a browser, run a sandbox, and fetch the docs as Markdown.
If you are a coding agent writing code against dvm.run, this page gives you everything you need to start. Each step links to the full guide. ## 1. Install an SDK
```sh
pip install dvm-run # Python 3.12 or newer; imports as `dvm`
npm install dvm-run # Node 22.12 or newer; ES modules only
cargo add dvm-run tokio --features tokio/macros,tokio/rt-multi-thread
```
## 2. Authenticate without a browser Export the API key your user provides:
```sh
export DVM_API_KEY=...
```
Every SDK reads `DVM_API_KEY` when no key is passed in code. Do not run `dvm-run login` without a person present to approve it in a browser: it blocks waiting for approval. If you do not have a key, ask your user to create one on the panel’s [API keys page](https://sandbox.dvm.run/keys); their account must be off the waitlist first ([Getting in](/start/access/)). Do not print the key, and never pass it into a sandbox. ## 3. Start a sandbox and read its output * Python python/examples/first_sandbox.py
```python
from dvm import Sandbox
with Sandbox.create("python:3.12") as sandbox:
result = sandbox.run(["python", "-c", "print('hello from a sandbox')"])
print(result.exit_code, result.stdout.decode(), end="")
sandbox.write_file("/tmp/notes.txt", b"written before the end\n")
sandbox.end()
point = sandbox.seek()
print(point.read_file("/tmp/notes.txt").decode(), end="")
```
* TypeScript js/examples/first-sandbox.ts
```ts
import { Sandbox } from "dvm-run";
await using sandbox = await Sandbox.create("python:3.12");
const result = await sandbox.run(["python", "-c", "print('hello from a sandbox')"]);
console.log(result.exitCode, new TextDecoder().decode(result.stdout));
await sandbox.writeFile("/tmp/notes.txt", new TextEncoder().encode("written before the end\n"));
await sandbox.end();
const point = await sandbox.seek();
console.log(new TextDecoder().decode(await point.readFile("/tmp/notes.txt")));
```
* Rust rust/dvm-run/examples/first_sandbox.rs
```rust
#[tokio::main]
async fn main() -> dvm_run::Result<()> {
let client = dvm_run::Client::from_env()?;
let sandbox = client.create_sandbox("python:3.12").await?;
sandbox
.scope(async |sandbox| {
let result = sandbox
.run(["python", "-c", "print('hello from a sandbox')"])
.await?;
print!(
"{} {}",
result.exit_code,
String::from_utf8_lossy(&result.stdout)
);
sandbox
.write_file("/tmp/notes.txt", b"written before the end\n")
.await?;
Ok(())
})
.await?;
let point = sandbox.seek_end().await?;
let notes = point.read_file("/tmp/notes.txt").await?;
print!("{}", String::from_utf8_lossy(¬es));
Ok(())
}
```
Key behaviors to rely on: * `run` returns the exit code along with stdout and stderr as **bytes**. A nonzero exit code is a normal result, not an error; a command killed by a signal exits with `128 + signal`. * A string runs as a shell script (`/bin/bash -lc` if the image includes bash, otherwise `/bin/sh -c`); a list runs directly as argv with no shell. * Commands run as root in the image’s environment and working directory. Create a sandbox with no `command` and no `entrypoint`, as above, to start a session (a sandbox that accepts commands); pass either to run a [one-program sandbox](/guides/programs/) instead. * End every sandbox when finished: use a `with` block, `await using`, `scope`, or `end()`. A sandbox left running continues consuming credit until it hits its time limit. * When the API rejects a request, the SDK raises an error containing the service’s reason: read it ([Errors](/reference/errors/)). * Images must be public; pulls are anonymous. ## 4. Read the docs as Markdown * [/llms.txt](/llms.txt): overview of dvm.run and every page’s Markdown URL. * [/llms-full.txt](/llms-full.txt): all documentation pages in one Markdown file. * [/llms-small.txt](/llms-small.txt): the same content with asides and extra whitespace stripped. * Any individual page: append `.md` to its URL. For example, this page is `https://docs.dvm.run/start/agents.md`, and the home page is `https://docs.dvm.run/index.md`. The SDK source code and Rust API types (`dvm-api`) are in [github.com/deterministic-machines/sdk](https://github.com/deterministic-machines/sdk).
# Getting in
> Sign in with GitHub, leave the waitlist, and set an API key from the panel or a terminal.
Follow these steps to set up an account and authenticate the SDKs. 1. **Sign in.** Open [sandbox.dvm.run](https://sandbox.dvm.run/) (the panel) and sign in with GitHub. Each account is one person. 2. **Wait for access.** New accounts start on the waitlist. The panel shows your status and lets you leave an email address and a note on your use case; with an email, you are notified when approved. Until then, every sandbox call returns `403` with `you're on the waitlist: you can use dvm once we let you in`, and you cannot create an API key. 3. **Get an API key** from the panel or a terminal, as below. Approved accounts include starter credit. See [Plans, limits and credit](/concepts/plans/) for billing and plan limits. ## Create an API key in the panel Create a key on the panel’s [API keys page](https://sandbox.dvm.run/keys). The key appears once: copy it and export it as `DVM_API_KEY`:
```sh
export DVM_API_KEY=...
```
Use a panel key where no person can approve a browser login, such as CI or an autonomous agent. ## Log in from a terminal: `dvm-run login` Each SDK ships the `dvm-run` CLI with one command, `login`. It requests a key for your machine, opens your browser to approve it, and saves it for all three SDKs. * Python
```sh
pip install dvm-run
dvm-run login # or: python -m dvm login
```
* TypeScript
```sh
npm install dvm-run
npx dvm-run login
```
* Rust
```sh
cargo install dvm-run
dvm-run login
```
It prints a URL and verification code, and opens the URL in your browser. Confirm the machine name and code on the panel page to approve; the terminal receives a key named `Login on `. Unapproved logins expire after 10 minutes. * `--no-browser` prints the URL only. Over SSH, open it in any signed-in browser. * `--api-url URL` targets another dvm.run instance instead of `DVM_API_URL` or `https://sandbox.dvm.run`. The key is saved in `dvm/credentials.json` under `$XDG_CONFIG_HOME` (or `~/.config`), readable only by you and keyed by API URL. Logging in again for the same API URL replaces its saved key. ## How SDKs resolve the API URL and key API URL order: 1. Passed in code. 2. `DVM_API_URL`. 3. `https://sandbox.dvm.run`. API key order: 1. Passed in code. 2. `DVM_API_KEY`. 3. Saved by `dvm-run login` for that API URL. With no key, the SDK raises an error before sending a request. | | Passed in code | From the environment | | ---------- | -------------------------------------------------------------------- | --------------------- | | Python | `Sandbox.create(image, api_url=..., api_key=...)`, also on `connect` | any call without them | | TypeScript | `Sandbox.create(image, { apiUrl, apiKey })`, also on `connect` | any call without them | | Rust | `Client::new(api_url, api_key)` | `Client::from_env()` | Every request sends `Authorization: Bearer `. ## How API keys work A key acts as you: no scopes, no expiry, valid until revoked on the API keys page. Only the panel creates and revokes keys; a key cannot create another. Treat each key as a password, and revoke it if exposed.
# Plans, limits and credit
> How plans, limits, and credit work, and what each limit error means.
This page explains how credit and plan limits work and what each error means. For current plan limits and rates, see [dvm.run/pricing](https://dvm.run/pricing/). ## Credit Sandboxes draw from your account’s credit by their vCPUs and memory, for as long as they run, paused time included. Replaying a run to inspect it is free. A sandbox will not start if your remaining credit cannot cover at least one minute of it; the API returns `402` with `your credit is used up: what's left pays for less than a minute of this sandbox`. Some plans relax these restrictions: see the [pricing page](https://dvm.run/pricing/) for each plan’s limits and where credit limits do not apply. ## Limits All limits apply per account. Your plan sets: * **Concurrent sandboxes.** How many active sandboxes (queued, running, or paused) you can have at once. Starting another returns `409` with `you have N sandboxes going, the most the plan allows; stop one first`. * **Concurrent replays.** Counted separately from active sandboxes, up to the same limit. A seek that exceeds it returns `409` with `too many timeline seeks in progress; try again in a moment`. * **Sandbox size.** The maximum vCPUs and memory per sandbox. Requesting more returns `400` with `a sandbox on the plan may have up to vCPUs and MiB`. * **Maximum duration.** A sandbox runs for at most your plan’s time limit, or as long as your starting credit covers if that is shorter. When it reaches its time limit, it fails with that reason and can still be inspected.
# What a recording holds
> How dvm records every sandbox run automatically, what is stored, and what you can do with it.
Every sandbox runs on dvm, a deterministic virtual machine, and is recorded automatically. You do not enable or manage recording. This page explains what a recording captures and how you can use it. ## Determinism dvm runs programs so any run can be replayed identically: same instructions, same thread order, same output. External inputs, such as bytes read from the network, can vary across runs; the recording captures them so a replay sees the same inputs. Recording works identically on any vCPU count. Running the same spec again creates a new sandbox with a fresh recording. ## What a recording holds A recording stores what dvm needs to replay a run identically, including all external inputs: * For a [session](/guides/sessions/) (a sandbox accepting commands and file operations): its full input, which is every command, arguments, environment, stdin, and every file you wrote. * Bytes read from the network. With each sandbox, dvm.run also stores its spec (name, image, command, entrypoint, environment variables, vCPUs, memory, seed, and network) and output. Any secret you pass in, or private data the program fetches, becomes part of that record ([Environment and secrets](/guides/environment/)). ## What you can do with a recording * **Inspect a finished run.** After exit, seek (replay the recording to a chosen moment) to any point in the run, read its files there, and step through events ([Inspecting a finished run](/guides/inspect/)). * **View the timeline.** The panel shows each recording on a timeline: its threads, when each ran, and when output was written. A recording replays only on the dvm version that created it. Once dvm updates, older recordings report this and cannot be inspected: run the sandbox again to record anew. See [What replay promises](/concepts/replay/) for what replay does and does not promise.
# What replay promises
> What replaying a recording promises, what it does not, and what happens when a replay differs.
Inspecting a finished run replays its recording. This page explains what replay promises and what it does not. ## What replay promises * dvm aims to replay every run identically: same instructions, same thread order, same output and exit code. * A replay may differ from its recording, and dvm reports it when it does. A failed replay seek returns `409` with dvm’s reason. ## What replay does not promise * **Not every run is replayable.** Stopped sandboxes have incomplete recordings and cannot be inspected. Failed sandboxes cannot be inspected unless they failed at their time limit. * **Tied to the dvm version.** After dvm updates, older recordings return `... ran on an older dvm than its runner's now: run it again`. Run the sandbox again to record anew. * **Not a backup.** A sandbox, its output, or its recording may be lost. Keep your own copy of anything you need, such as files read from a point (a recorded moment in a run). * **No SLA.** Per dvm.run’s [Terms](https://dvm.run/terms/), there is no promise of uptime, support, or response time. ## What replay costs Replaying is free. Your plan limits concurrent replays ([Plans, limits and credit](/concepts/plans/)).
# Environment and secrets
> Set environment variables for a sandbox or a single command, and understand how secrets are stored in recordings.
Use this page to pass environment variables to a whole sandbox or to an individual command, and to see what happens to a secret you pass in, given that every run is recorded. ## Environment variables Setting `env` on a sandbox adds variables to the image’s environment for every process inside it. Setting `env` on a command adds variables for that command alone, overriding any sandbox variable with the same name. * Python python/examples/environment.py
```python
with Sandbox.create("alpine:3.20", env={"STAGE": "test", "LOG_LEVEL": "debug"}) as sandbox:
print(sandbox.run('echo "$STAGE $LOG_LEVEL"').stdout)
print(sandbox.run('echo "$STAGE"', env={"STAGE": "override"}).stdout)
print(sandbox.spec["environment"])
```
* TypeScript js/examples/environment.ts
```ts
await using sandbox = await Sandbox.create("alpine:3.20", {
env: { STAGE: "test", LOG_LEVEL: "debug" },
});
console.log(text((await sandbox.run('echo "$STAGE $LOG_LEVEL"')).stdout));
console.log(text((await sandbox.run('echo "$STAGE"', { env: { STAGE: "override" } })).stdout));
console.log(sandbox.spec.environment);
```
* Rust rust/dvm-run/examples/environment.rs
```rust
let sandbox = client
.create_sandbox("alpine:3.20")
.env("STAGE", "test")
.env("LOG_LEVEL", "debug")
.await?;
sandbox
.scope(async |sandbox| {
let both = sandbox.run(r#"echo "$STAGE $LOG_LEVEL""#).await?;
print!("{}", String::from_utf8_lossy(&both.stdout));
let one = sandbox
.run(r#"echo "$STAGE""#)
.env("STAGE", "override")
.await?;
print!("{}", String::from_utf8_lossy(&one.stdout));
println!("{:?}", sandbox.spec().environment());
Ok(())
})
.await?;
```
Sandbox variable names must contain only letters, digits, and `_`, cannot start with a digit, and must be unique; their values cannot contain a NUL byte. Command variable names cannot be empty or contain `=`. The sandbox’s spec, returned when you create or fetch the sandbox, includes its sandbox-level environment variables and their values. ## Secrets A secret becomes part of the recording Everything you pass into a sandbox is stored: in the sandbox’s spec (visible through the API and the panel) and in its recording. Environment variables, command arguments, stdin, and written files all enter the recording, and files can be read back at any point in the run. Data the program reads from the network, including private data it fetches, is recorded as well. Give a sandbox only revocable secrets: a key or token scoped to the minimum access needed, revoked once the run finishes. Never pass your dvm.run API key into a sandbox. When a single command needs a secret, pass it to that command from your own environment instead of setting it on the whole sandbox. That keeps it out of the sandbox’s spec, though it is still stored with the commands you sent and in the recording. * Python python/examples/environment.py
```python
token = os.environ.get("EXAMPLE_TOKEN", "not-a-real-token")
with Sandbox.create("alpine:3.20") as sandbox:
result = sandbox.run('test -n "$TOKEN" && echo has a token', env={"TOKEN": token})
print(result.stdout)
```
* TypeScript js/examples/environment.ts
```ts
const token = process.env.EXAMPLE_TOKEN ?? "not-a-real-token";
await using sandbox = await Sandbox.create("alpine:3.20");
const result = await sandbox.run('test -n "$TOKEN" && echo has a token', { env: { TOKEN: token } });
console.log(text(result.stdout));
```
* Rust rust/dvm-run/examples/environment.rs
```rust
let token = std::env::var("EXAMPLE_TOKEN").unwrap_or_else(|_| "not-a-real-token".to_owned());
let sandbox = client.create_sandbox("alpine:3.20").await?;
sandbox
.scope(async |sandbox| {
let result = sandbox
.run(r#"test -n "$TOKEN" && echo has a token"#)
.env("TOKEN", token)
.await?;
print!("{}", String::from_utf8_lossy(&result.stdout));
Ok(())
})
.await?;
```
Deleting a sandbox in the panel deletes its record, output, and recording. See the [privacy policy](https://dvm.run/privacy/) for what dvm.run retains and for how long.
# Agent harness (Harbor)
> Run Harbor tasks such as Terminal-Bench in dvm.run sandboxes using the Python SDK.
The Python SDK provides a Harbor environment (`dvm.harbor:DvmEnvironment`) for agent benchmarks such as Terminal-Bench. Each of a task’s environments runs in a recorded session (a sandbox accepting commands), so you can inspect what the agent did afterward. Python only. ## Run a task Install the SDK in the Python environment Harbor runs in, then pass the environment:
```sh
uv tool install harbor --with dvm-run
harbor run -p --agent oracle --env dvm.harbor:DvmEnvironment
```
Harbor is not a dependency of `dvm-run`, and there is no Harbor extra. Credentials resolve as in the SDK: `DVM_API_URL`, `DVM_API_KEY`, or a key saved by `dvm-run login` ([Getting in](/start/access/)). Tested with Harbor 0.26.0. ## What it supports * **Images.** Uses the task’s `docker_image` (must be a public, prebuilt Linux image with a POSIX shell and `tar`). Local Dockerfiles are not built. * **Size.** Applies task CPU and memory; storage uses dvm.run’s default (`storage_mb` is ignored). * **Commands.** Run in Harbor’s working directory with its environment and user. At a deadline, the process group is killed and `TimeoutError` is raised. * **Files.** Single files use SDK file calls; directories transfer as tar archives, preserving executable bits, internal links, and empty directories. * **Network.** Supports no network, internet, or an allowlist of hostnames, `*.domain` wildcards, IPv4 addresses, and IPv4 CIDR ranges; Harbor can change it between phases. No IPv6 ([Network](/guides/network/)). * **Grading.** Supports shared or separate grading, copying declared artifacts between sandboxes for separate grading. Sandboxes are named `-agent` and `-grading`, truncated to fit dvm.run’s rule for names. Rejects upfront: missing images, image builds (`force_build` included), Docker Compose, multiple containers, GPUs, TPUs, Windows, and host mounts. ## After a task Shutting down an environment closes session input and waits for clean exit so the sandbox stays inspectable. Only if that fails or exceeds 30 seconds is the sandbox force-stopped. Harbor’s `delete` keeps the sandbox either way. Use `sandbox_id` to open it in the panel or inspect it from the SDK ([Inspecting a finished run](/guides/inspect/)). ## Terminal-Bench Published `terminal-bench/terminal-bench@latest` tasks name prebuilt images for both agent and grader:
```sh
harbor download terminal-bench/terminal-bench@latest -o tasks
```
Source checkouts may omit image fields. Set `[environment].docker_image` and `[verifier.environment].docker_image` in `task.toml` to the published images, and `[verifier].environment_mode = "separate"`. The grader image must already contain its tests.
# Inspecting a finished run
> Seek to any point in a recorded sandbox run, read its files at that moment, and step through events.
Once a sandbox exits, you can replay its recording and seek (jump to a chosen moment in the execution) to any point in its run. At any point, you can read the sandbox’s files as they existed then and step forward to the next event you are watching for. * Python python/examples/inspect_run.py
```python
with Sandbox.create("alpine:3.20") as sandbox:
sandbox.run("echo first > /tmp/state; echo second > /tmp/state")
sandbox.end()
```
* TypeScript js/examples/inspect-run.ts
```ts
await using sandbox = await Sandbox.create("alpine:3.20");
await sandbox.run("echo first > /tmp/state; echo second > /tmp/state");
await sandbox.end();
```
* Rust rust/dvm-run/examples/inspect_run.rs
```rust
let sandbox = client.create_sandbox("alpine:3.20").await?;
sandbox
.scope(async |sandbox| {
sandbox
.run("echo first > /tmp/state; echo second > /tmp/state")
.await?;
Ok(())
})
.await?;
```
## Which runs can be inspected Any sandbox that exited can be inspected, regardless of exit code, as can one that reached its time limit. Seeking fails with `409` and the matching reason if the sandbox is: * still running: `sandbox N is still running`; * stopped: `sandbox N was stopped before exit`; * failed: `sandbox N failed before exit`; * recorded on an older dvm version than the runner now runs: `... ran on an older dvm than its runner's now: run it again`. A session (a sandbox that accepts commands) exits when you close its input with `end()`, or at the end of a `with` block, `await using`, or `scope`. ## Seek to a point Call `seek` with no target to jump to the end of the run. * Python python/examples/inspect_run.py
```python
end = sandbox.seek()
print(end.thread, end.event, end.ns, end.at.kind)
print(end.read_file("/tmp/state"))
```
* TypeScript js/examples/inspect-run.ts
```ts
const end = await sandbox.seek();
console.log(end.thread, end.event, end.ns, end.at.kind);
console.log(new TextDecoder().decode(await end.readFile("/tmp/state")));
```
* Rust rust/dvm-run/examples/inspect_run.rs
```rust
let end = sandbox.seek_end().await?;
println!(
"{} {} {:?} {:?}",
end.thread(),
end.event(),
end.ns(),
end.at()
);
println!(
"{:?}",
String::from_utf8_lossy(&end.read_file("/tmp/state").await?)
);
```
There are three seek targets: | Target | Python, TypeScript | Rust | Lands | | -------- | ---------------------------------------------------- | --------------------------- | ---------------------------------------------------------------- | | the end | `seek()` | `seek_end()` | where the run ended | | a time | `seek(at_ns=…)`, `seek({ atNs })` | `seek_at_ns(ns)` | near that time in the recording (progress is sampled 1 ms apart) | | an event | `seek(thread=…, event=…)`, `seek({ thread, event })` | `seek_event(thread, event)` | exactly at that thread and event | A point describes where execution stopped: * `thread`, `process`, and `event`: the thread where execution stopped, its process, and the thread’s event count. Together, a thread and an event identify a point uniquely; seek to them to return to it. * `ns`: approximate timestamp in the recording, if known. * `at`: what the thread was doing: a `syscall` (with its number, name, raw arguments, and values dvm decoded such as paths, strings, addresses, and bytes), a `page_fault` (with its address, whether it was a write, and whether the page was present), or an `arrival` (with the instruction address `rip`). * `operations` and `stats`: counters dvm tracks for the run up to that point. The first seek on a run starts its replay, which can take a while. Further points in the same run share that replay. Replaying a run is free ([Plans, limits and credit](/concepts/plans/)). ## Read files at a point * Python python/examples/inspect_run.py
```python
for entry in end.list_dir("/tmp"):
print(entry.name, entry.type)
status = end.stat("/tmp/state")
print(status.type, status.size, oct(status.mode), status.mtime)
```
* TypeScript js/examples/inspect-run.ts
```ts
for (const entry of await end.listDir("/tmp")) console.log(entry.name, entry.type);
const status = await end.stat("/tmp/state");
console.log(status.type, status.size, status.mode.toString(8), status.mtime);
```
* Rust rust/dvm-run/examples/inspect_run.rs
```rust
for entry in end.list_dir("/tmp").await? {
println!("{} {:?}", entry.name, entry.kind);
}
let status = end.stat("/tmp/state").await?;
println!(
"{:?} {} {:o} {:?}",
status.kind, status.size, status.mode, status.mtime
);
```
- `read_file(path)` returns a regular file’s bytes. - `list_dir(path)` returns a directory’s entries, each with its name and type. - `stat(path)` returns the type, mode, owner, size, link count, and modified and changed timestamps as seconds and nanoseconds. It follows symbolic links unless you opt out; a link’s own status includes its target. Paths must be absolute. Missing paths return `404`. File bytes that dvm cannot serve from the recording return `422`. Mounts not yet supported return `501`. ## Step through events Stepping moves forward from a point to the next matching event and returns that new point, or nothing once no more matching events remain. * Python python/examples/inspect_run.py
```python
point = sandbox.seek(at_ns=0, watch=["file-syscalls", "syscall:execve"])
marks = []
while point is not None and len(marks) < 20:
print(point.thread, point.event, point.at.kind, point.at.name)
marks.append((point.thread, point.event))
point = point.step()
```
* TypeScript js/examples/inspect-run.ts
```ts
let point: SandboxPoint | null = await sandbox.seek({ atNs: 0, watch: ["file-syscalls", "syscall:execve"] });
const marks: [number, number][] = [];
while (point !== null && marks.length < 20) {
console.log(point.thread, point.event, point.at.kind, point.at.name);
marks.push([point.thread, point.event]);
point = await point.step();
}
```
* Rust rust/dvm-run/examples/inspect_run.rs
```rust
let execve = SyscallName::try_from("execve".to_owned()).expect("a syscall's name");
let mut point = Some(
sandbox
.seek_at_ns(0)
.watch(WatchPoint::FileSyscalls)
.watch(WatchPoint::NamedSyscall { name: execve })
.await?,
);
let mut marks = Vec::new();
while let Some(here) = point.take() {
println!("{} {} {:?}", here.thread(), here.event(), here.at());
marks.push((here.thread(), here.event()));
if marks.len() < 20 {
point = here.step().await?;
}
}
```
On any seek or step, you can specify up to 32 watch points (the event categories you want stepping to stop on): | Watch point | Python, TypeScript | Rust (`WatchPoint::`) | | -------------------- | ------------------- | ----------------------- | | every syscall | `"syscall"` | `Syscall` | | one syscall, by name | `"syscall:execve"` | `NamedSyscall { name }` | | file syscalls | `"file-syscalls"` | `FileSyscalls` | | socket syscalls | `"socket-syscalls"` | `SocketSyscalls` | | processes | `"processes"` | `Processes` | | page faults | `"page-fault"` | `PageFault` | Python and TypeScript also accept each watch point as the raw API object, such as `{"kind": "named_syscall", "name": "execve"}`. A syscall name must be 1 to 64 letters, digits, or `_`. If a run’s first seek specifies no watch points, it defaults to file syscalls, processes, and socket syscalls. Later seeks or steps that omit watch points keep the current set; passing watch points replaces it. ## Return to a point Save a point’s thread and event number, then seek to them later to return to that exact moment. * Python python/examples/inspect_run.py
```python
thread, event = marks[-1]
again = sandbox.seek(thread=thread, event=event)
print(again.at.name, [argument.value for argument in again.at.decoded])
```
* TypeScript js/examples/inspect-run.ts
```ts
const [thread, event] = marks.at(-1)!;
const again = await sandbox.seek({ thread, event });
console.log(again.at.name, again.at.decoded?.map((argument) => argument.value));
```
* Rust rust/dvm-run/examples/inspect_run.rs
```rust
let (thread, event) = *marks.last().expect("a stop");
let again = sandbox.seek_event(thread, event).await?;
println!("{:?}", again.at());
```
## Seek errors * `409`: the run cannot be inspected (see above), or replay failed (with dvm’s reason). * `409` with `too many timeline seeks in progress; try again in a moment`: you reached your plan’s limit on concurrent replays. * `503` with `the sandbox is returning to that point`: the SDKs wait and retry automatically. A replay may differ from its recording, and dvm reports when it does ([What replay promises](/concepts/replay/)).
# Network
> Control where a sandbox can connect (the internet, nowhere, or an allowlist) and change it while the sandbox runs.
A sandbox’s network mode controls where its outbound connections can go. Inbound connections are never allowed; sandboxes publish no ports. | Mode | Allowed destinations | | ------------------ | -------------------------------------------- | | `public` (default) | the internet | | `none` | nothing, not even a DNS resolver | | `allowlist` | a DNS resolver and only the entries you list | In every mode, a sandbox is blocked from reaching the host machine, the host’s local network, and link-local addresses such as cloud metadata services. ## Allowlist mode Each allowlist entry is one of: * a hostname, such as `pypi.org`; * a wildcard subdomain, such as `*.pythonhosted.org`; * an IPv4 address, such as `8.8.8.8`; * an IPv4 CIDR range, such as `8.8.8.0/24`. A hostname permits the internet addresses returned by the DNS resolver. An allowlist holds at most 256 entries. IPv6 is not supported, and any address or network inside the blocked ranges above is rejected. In Python and TypeScript, passing `allow` selects allowlist mode automatically. In Rust, pass `SandboxNetwork::Allowlist { allow }`. * Python python/examples/network.py
```python
with Sandbox.create("python:3.12", allow=["pypi.org", "*.pythonhosted.org"]) as sandbox:
installed = sandbox.run(["pip", "install", "--quiet", "six"])
print(installed.exit_code)
sandbox.set_network("none")
refused = sandbox.run(["pip", "download", "--quiet", "--no-deps", "--dest", "/tmp", "idna"])
print(refused.exit_code)
print(sandbox.spec["network"])
```
* TypeScript js/examples/network.ts
```ts
await using sandbox = await Sandbox.create("python:3.12", {
allow: ["pypi.org", "*.pythonhosted.org"],
});
const installed = await sandbox.run(["pip", "install", "--quiet", "six"]);
console.log(installed.exitCode);
await sandbox.setNetwork("none");
const refused = await sandbox.run(["pip", "download", "--quiet", "--no-deps", "--dest", "/tmp", "idna"]);
console.log(refused.exitCode);
console.log(sandbox.spec.network);
```
* Rust rust/dvm-run/examples/network.rs
```rust
let allow = vec!["pypi.org".to_owned(), "*.pythonhosted.org".to_owned()];
let sandbox = client
.create_sandbox("python:3.12")
.network(SandboxNetwork::Allowlist { allow })
.await?;
sandbox
.scope(async |sandbox| {
let installed = sandbox.run(["pip", "install", "--quiet", "six"]).await?;
println!("{}", installed.exit_code);
sandbox.set_network(&SandboxNetwork::None).await?;
let refused = sandbox
.run([
"pip",
"download",
"--quiet",
"--no-deps",
"--dest",
"/tmp",
"idna",
])
.await?;
println!("{}", refused.exit_code);
println!("{:?}", sandbox.spec().network());
Ok(())
})
.await?;
```
## No network Block all outbound traffic, including DNS: * Python python/examples/network.py
```python
with Sandbox.create("alpine:3.20", network="none") as sandbox:
print(sandbox.run("wget -q -T 5 -O /dev/null http://example.com").exit_code)
```
* TypeScript js/examples/network.ts
```ts
await using sandbox = await Sandbox.create("alpine:3.20", { network: "none" });
console.log((await sandbox.run("wget -q -T 5 -O /dev/null http://example.com")).exitCode);
```
* Rust rust/dvm-run/examples/network.rs
```rust
let sandbox = client
.create_sandbox("alpine:3.20")
.network(SandboxNetwork::None)
.await?;
sandbox
.scope(async |sandbox| {
let fetched = sandbox
.run("wget -q -T 5 -O /dev/null http://example.com")
.await?;
println!("{}", fetched.exit_code);
Ok(())
})
.await?;
```
## Change the network while running Call `set_network` (`setNetwork` in TypeScript) to change where new connections can go from that point onward. Already open connections remain open, and the sandbox’s spec reflects the active network setting. Calling it on a sandbox that has ended raises the error for how it ended. A common pattern is to install dependencies with `public` or an allowlist, then switch to `none` before the part you want sealed, as shown above. dvm records the bytes transferred on every connection as part of the run ([What a recording holds](/concepts/recording/)).
# One-program sandboxes
> Run a single program in a sandbox, set size and seed, wait for exit, read output, and manage its lifecycle.
Pass `command` or `entrypoint` to run one program in a sandbox, like `docker run`. Unlike a session, it accepts no commands from your code and stdin is closed. Wait for exit, then read output. * Python python/examples/programs.py
```python
with Sandbox.create(
"alpine:3.20",
command=["sh", "-c", "echo out; echo err >&2; exit 3"],
name="exits-three",
cpus=2,
memory_mib=2048,
seed=7,
) as sandbox:
print(sandbox.wait())
output = sandbox.output()
print(output.stdout)
print(output.stderr)
print(sandbox.state().kind)
```
* TypeScript js/examples/programs.ts
```ts
await using sandbox = await Sandbox.create("alpine:3.20", {
command: ["sh", "-c", "echo out; echo err >&2; exit 3"],
name: "exits-three",
cpus: 2,
memoryMib: 2048,
seed: 7,
});
console.log(await sandbox.wait());
const output = await sandbox.output();
console.log(text(output.stdout));
console.log(text(output.stderr));
console.log((await sandbox.state()).kind);
```
* Rust rust/dvm-run/examples/programs.rs
```rust
let sandbox = client
.create_sandbox("alpine:3.20")
.command(["sh", "-c", "echo out; echo err >&2; exit 3"])
.name("exits-three")
.cpus(2)
.memory_mib(2048)
.seed(7)
.await?;
println!("{}", sandbox.wait().await?);
let output = sandbox.output().await?;
println!("{:?}", String::from_utf8_lossy(output.stdout.bytes()));
println!("{:?}", String::from_utf8_lossy(output.stderr.bytes()));
println!("{}", sandbox.state().await?.kind());
```
## What runs * `command` is argv, replacing the image’s `CMD`. * `entrypoint` replaces the image’s `ENTRYPOINT`, with `command` as its arguments. - Python python/examples/programs.py
```python
with Sandbox.create("alpine:3.20", entrypoint="sh", command=["-c", "uname -a"]) as sandbox:
sandbox.wait()
print(sandbox.output().stdout.decode(), end="")
```
- TypeScript js/examples/programs.ts
```ts
await using sandbox = await Sandbox.create("alpine:3.20", {
entrypoint: "sh",
command: ["-c", "uname -a"],
});
await sandbox.wait();
console.log(text((await sandbox.output()).stdout));
```
- Rust rust/dvm-run/examples/programs.rs
```rust
let sandbox = client
.create_sandbox("alpine:3.20")
.entrypoint("sh")
.command(["-c", "uname -a"])
.await?;
sandbox.wait().await?;
print!(
"{}",
String::from_utf8_lossy(sandbox.output().await?.stdout.bytes())
);
```
The program inherits the image’s environment, user, and working directory, plus any `env` you pass ([Environment and secrets](/guides/environment/)). Images must be public; pulls are anonymous. ## Size, seed, and name | | Default | Range | | ---------------------------------- | -------------- | --------------------------------------------------------------------------- | | `cpus` | 1 | 1 to 8 vCPUs | | memory (`memory_mib`, `memoryMib`) | 1024 MiB | 128 to 16384 MiB | | `seed` | 0 | 0 to 253 − 1 | | `name` | from the image | up to 63 lowercase letters, digits and `-`, not starting or ending with `-` | Your plan may cap resources below these ranges; larger requests fail with your plan’s limit ([Plans, limits and credit](/concepts/plans/)). The same image, command, and seed run the same way, except where the program reads something from outside that differs, such as the network ([What a recording holds](/concepts/recording/)). Name is a label for you. These options also apply to a [session](/guides/sessions/) (a sandbox accepting commands). ## Wait and read output * `wait` returns the exit code once the program exits, or raises the matching error if stopped or failed ([Errors](/reference/errors/)). * `output` returns stdout and stderr written so far, as bytes. For a [session](/guides/sessions/), `output` returns the session server’s response frames rather than command output ([The sandbox protocol](/reference/wire/)). Use `run` there. ## Pause, resume, stop, and reconnect * Python python/examples/programs.py
```python
with Sandbox.create("alpine:3.20", command=["sh", "-c", "while :; do :; done"]) as sandbox:
sandbox.pause()
print(sandbox.state().kind)
sandbox.resume()
elsewhere = Sandbox.connect(sandbox.id)
elsewhere.stop()
elsewhere.close()
print(sandbox.state().kind)
```
* TypeScript js/examples/programs.ts
```ts
await using sandbox = await Sandbox.create("alpine:3.20", {
command: ["sh", "-c", "while :; do :; done"],
});
await sandbox.pause();
console.log((await sandbox.state()).kind);
await sandbox.resume();
const elsewhere = await Sandbox.connect(sandbox.id);
await elsewhere.stop();
console.log((await sandbox.state()).kind);
```
* Rust rust/dvm-run/examples/programs.rs
```rust
let sandbox = client
.create_sandbox("alpine:3.20")
.command(["sh", "-c", "while :; do :; done"])
.await?;
sandbox.pause().await?;
println!("{}", sandbox.state().await?.kind());
sandbox.resume().await?;
let elsewhere = client.connect_sandbox(sandbox.id()).await?;
elsewhere.stop().await?;
println!("{}", sandbox.state().await?.kind());
```
- `pause` freezes the sandbox; `resume` continues it. - `stop` terminates it (no-op if already ended). Stopped sandboxes cannot be inspected; exited ones can. - `state` returns `queued`, `running`, or `paused`, then `exited` (with exit code), `stopped`, or `failed` (with reason). - `connect` attaches another handle by sandbox ID from any process using an API key on the same account. A sandbox that never exits runs until its time limit, then fails with that reason ([Plans, limits and credit](/concepts/plans/)). Exiting a `with` block, `await using`, or `scope` stops a running one-program sandbox.
# Sessions
> Run commands, stream stdin, send signals, transfer files, and end an interactive sandbox session.
A sandbox created without `command` or `entrypoint` is a session: an interactive sandbox that accepts commands and file operations until you end it. Its first process is the session server instead of the image’s default program. Pass a command or entrypoint to run a [one-program sandbox](/guides/programs/) instead. ## Run a command Call `run` to start a command, send its input, and wait for it to finish. * Python python/examples/sessions.py
```python
result = sandbox.run(
'echo "$GREETING from $(pwd) as $(whoami)"; cat',
env={"GREETING": "hello"},
cwd="/tmp",
user="nobody",
stdin=b"and this came in on stdin\n",
)
print(result.exit_code)
print(result.stdout.decode(), end="")
```
* TypeScript js/examples/sessions.ts
```ts
const result = await sandbox.run('echo "$GREETING from $(pwd) as $(whoami)"; cat', {
env: { GREETING: "hello" },
cwd: "/tmp",
user: "nobody",
stdin: bytes("and this came in on stdin\n"),
});
console.log(result.exitCode);
console.log(text(result.stdout));
```
* Rust rust/dvm-run/examples/sessions.rs
```rust
let result = sandbox
.run(r#"echo "$GREETING from $(pwd) as $(whoami)"; cat"#)
.env("GREETING", "hello")
.cwd("/tmp")
.user("nobody")
.stdin(b"and this came in on stdin\n")
.await?;
println!("{}", result.exit_code);
print!("{}", String::from_utf8_lossy(&result.stdout));
```
- **Shell vs. argv.** A string runs as a script via `/bin/bash -lc` if the image has `/bin/bash`, or `/bin/sh -c` otherwise. A list runs directly as argv with no shell, finding the executable on `PATH`. - **Result.** Returns the exit code plus stdout and stderr as bytes. A nonzero exit code is a result, not an error. A signal-killed command exits with `128 + signal`, a missing executable exits 127, and a non-runnable one exits 126 with the reason on stderr. - **Environment and directory.** Commands inherit the sandbox’s environment, with `env` overlaid. Without `cwd`, they run in the image’s working directory. - **User.** Commands run as root unless `user` sets another (same format as `docker exec --user`: name or UID, optionally `:group` or `:gid`, from `/etc/passwd` and `/etc/group`). An unknown user still starts the command, which writes the error to stderr and exits 126. - **Input.** `stdin` is sent and closed; without it, input is empty. Multiple commands can run concurrently in one session. ## Start and interact with a command Call `start` to launch a command and get a handle once it starts. Without `stdin`, input stays open so you can write and close it later. * Python python/examples/sessions.py
```python
cat = sandbox.start(["cat"])
cat.write_stdin(b"one ")
cat.write_stdin(b"two\n")
cat.close_stdin()
print(cat.wait().stdout)
sleeper = sandbox.start(["sleep", "600"])
sleeper.signal(15)
print(sleeper.wait().exit_code)
```
* TypeScript js/examples/sessions.ts
```ts
const cat = await sandbox.start(["cat"]);
await cat.writeStdin(bytes("one "));
await cat.writeStdin(bytes("two\n"));
await cat.closeStdin();
console.log(text((await cat.wait()).stdout));
const sleeper = await sandbox.start(["sleep", "600"]);
await sleeper.signal(15);
console.log((await sleeper.wait()).exitCode);
```
* Rust rust/dvm-run/examples/sessions.rs
```rust
let cat = sandbox.start(["cat"]).await?;
cat.write_stdin(b"one ").await?;
cat.write_stdin(b"two\n").await?;
cat.close_stdin().await?;
println!("{:?}", String::from_utf8_lossy(&cat.wait().await?.stdout));
let sleeper = sandbox.start(["sleep", "600"]).await?;
sleeper.signal(15).await?;
println!("{}", sleeper.wait().await?.exit_code);
```
- `write_stdin` queues bytes without waiting for the command to read them. - `signal(n)` sends signal `n` (1 to 64) to the command’s process group. The server sends no response; check the exit code. - `wait` returns the same result as `run`. Output is collected as it arrives, so a command that writes a lot holds it all in memory until then. ## Read and write files Call `write_file` to write a whole file and `read_file` to read one, as bytes. * Python python/examples/sessions.py
```python
sandbox.write_file("/tmp/hello.sh", b"#!/bin/sh\necho hello from a file\n", mode=0o755)
print(sandbox.run(["/tmp/hello.sh"]).stdout)
print(sandbox.read_file("/etc/os-release").decode().splitlines()[0])
```
* TypeScript js/examples/sessions.ts
```ts
await sandbox.writeFile("/tmp/hello.sh", bytes("#!/bin/sh\necho hello from a file\n"), { mode: 0o755 });
console.log(text((await sandbox.run(["/tmp/hello.sh"])).stdout));
console.log(text(await sandbox.readFile("/etc/os-release")).split("\n")[0]);
```
* Rust rust/dvm-run/examples/sessions.rs
```rust
sandbox
.write_file("/tmp/hello.sh", b"#!/bin/sh\necho hello from a file\n")
.mode(0o755)
.await?;
let hello = sandbox.run(["/tmp/hello.sh"]).await?;
println!("{:?}", String::from_utf8_lossy(&hello.stdout));
let release = sandbox.read_file("/etc/os-release").await?;
println!(
"{}",
String::from_utf8_lossy(&release)
.lines()
.next()
.unwrap_or("")
);
```
- New files get mode `0o644` minus the umask unless you pass a mode; existing files keep their mode. - The parent directory must exist; none is created. - Writes are not atomic; a failed write can leave a partial file. - `read_file` reads regular files only; directories and missing files fail with the reason. - Relative paths start from the image’s working directory. To read files after exit, seek to a point (a recorded moment in the run) ([Inspecting a finished run](/guides/inspect/)). ## End the session Call `end` to close session input and wait for exit. Running commands are killed. Returns the sandbox’s exit code (0 once the session server stops). * Python python/examples/sessions.py
```python
print(sandbox.end())
```
* TypeScript js/examples/sessions.ts
```ts
console.log(await sandbox.end());
```
* Rust rust/dvm-run/examples/sessions.rs
```rust
println!("{}", sandbox.end().await?);
```
Resume a paused sandbox before ending it, or stop it instead. A `with` block, `await using`, or `scope` handles cleanup automatically ([Python](/sdks/python/), [TypeScript](/sdks/typescript/), [Rust](/sdks/rust/)). Only sandboxes that exited (as `end` makes them) can be inspected. Stopped sandboxes cannot. Caution A session’s input becomes part of its recording. Every command, its arguments, environment, stdin, and every file you write are stored in the recording and readable by anyone who can inspect it. ## Pause, resume, stop These controls work on any sandbox; see [One-program sandboxes](/guides/programs/). * `pause` freezes the sandbox; `resume` continues it. * `stop` terminates it immediately. Stopped sandboxes cannot be inspected. * `state` returns `queued`, `running`, or `paused`, then `exited` (with exit code), `stopped`, or `failed` (with reason).
# Python
> Install the dvm-run Python package (3.12+), choose blocking or asyncio, and manage cleanup and errors.
Install the Python SDK and learn its conventions for blocking and async usage, cleanup, and errors.
```sh
pip install dvm-run
```
Published as `dvm-run` on PyPI and imported as `dvm`. Requires Python 3.12 or newer and depends only on `httpx`. Includes the `dvm-run` CLI, also runnable via `python -m dvm` ([Getting in](/start/access/)). ## Blocking and asyncio `Sandbox` and `SandboxPoint` block; `AsyncSandbox` and `AsyncSandboxPoint` provide the same methods as asyncio coroutines. `Command` and `AsyncCommand` are the corresponding handles for started commands. python/examples/asyncio_sandbox.py
```python
async def main() -> None:
async with await AsyncSandbox.create("python:3.12") as sandbox:
results = await asyncio.gather(
sandbox.run(["python", "-c", "print(1)"]),
sandbox.run(["python", "-c", "print(2)"]),
)
print([result.stdout for result in results])
await sandbox.end()
point = await sandbox.seek()
print(point.event)
asyncio.run(main())
```
## Create and end a sandbox `Sandbox.create(image, ...)` returns once the sandbox runs (or has exited). Keyword arguments: `command`, `entrypoint`, `cpus`, `memory_mib`, `seed`, `env`, `name`, `network`, `allow`, `api_key`, and `api_url`. Use a `with` block (`async with` for `AsyncSandbox`). When the block exits: * a session (a sandbox accepting commands) closes its input, and the block waits for exit; * a paused sandbox or one-program sandbox is stopped; * an ended sandbox is left unchanged. The handle then closes its connection. Outside a `with` block, call `end()` or `stop()`, then `close()`. `close()` alone leaves the sandbox running. Call `Sandbox.connect(sandbox_id)` to attach to a sandbox created elsewhere. ## Bytes and results `run` and `Command.wait()` return a `CommandResult` with `exit_code`, `stdout`, and `stderr` (`bytes`). File contents are also `bytes`. A command’s exit code is never an error. ## Errors All exceptions inherit from `DvmError`. HTTP errors raise `ApiError` (`status`, `message`), with subclasses for 400, 401, 404, and 409. Calling an ended sandbox raises `SandboxEndedError`, or `SandboxFailedError` (with `reason`) if dvm or the platform ended it. Sandbox-side rejections, such as a missing file, raise plain `DvmError` with the message. See [Errors](/reference/errors/). python/examples/errors.py
```python
try:
with Sandbox.create("alpine:3.20", command=["true"], cpus=64) as sandbox:
sandbox.wait()
except InvalidRequestError as refused:
print(refused.status, refused.message)
except SandboxFailedError as failed:
print("dvm ended it:", failed.reason)
except ApiError as refused:
if refused.status == 402:
print("out of credit:", refused.message)
elif refused.status == 403:
print("not let in yet:", refused.message)
else:
raise
```
Sending a command to a one-program sandbox raises `DvmError` locally before sending a request. ## Agent harness Includes a Harbor environment, `dvm.harbor:DvmEnvironment` ([Agent harness](/guides/harbor/)). Python only. ## Where next * [Sessions](/guides/sessions/): run commands and transfer files. * [Python reference](/reference/python/): every class and method. * [PyPI](https://pypi.org/project/dvm-run/) and [source](https://github.com/deterministic-machines/sdk/tree/main/python).
# Rust
> Install the dvm-run crate on tokio, use Client and builders, and clean up sandboxes with scope.
Add the Rust SDK to a tokio project and learn its conventions for builders, cleanup, and errors.
```sh
cargo add dvm-run tokio --features tokio/macros,tokio/rt-multi-thread
```
The `dvm-run` crate on crates.io targets Rust 1.88 or newer (edition 2024) with tokio futures. API types live in `dvm-api`, re-exported as `dvm_run::api`. Run `cargo install dvm-run` for the `dvm-run` CLI ([Getting in](/start/access/)). ## Client and builders Create one `Client`: `Client::from_env()` reads `DVM_API_URL` and `DVM_API_KEY` (or the key saved by `dvm-run login`); `Client::new(url, key)` takes them directly. Sandbox creation, commands, writes, seeks, and steps each return a builder: set what differs, then `.await` it. rust/dvm-run/examples/programs.rs
```rust
let sandbox = client
.create_sandbox("alpine:3.20")
.command(["sh", "-c", "echo out; echo err >&2; exit 3"])
.name("exits-three")
.cpus(2)
.memory_mib(2048)
.seed(7)
.await?;
println!("{}", sandbox.wait().await?);
let output = sandbox.output().await?;
println!("{:?}", String::from_utf8_lossy(output.stdout.bytes()));
println!("{:?}", String::from_utf8_lossy(output.stderr.bytes()));
println!("{}", sandbox.state().await?.kind());
```
`create_sandbox` resolves once the sandbox runs (or has exited). `connect_sandbox(id)` attaches to an existing sandbox. `Sandbox` is `Clone`, and clones share one session. ## End a sandbox Dropping a `Sandbox` leaves it running. Wrap work in `scope`, which cleans up when the closure returns, fails, or is dropped: * a session (a sandbox accepting commands) closes its input, and `scope` waits for exit; * a paused sandbox or one-program sandbox is stopped; * an ended sandbox is left unchanged. Or call `end()` or `stop()` directly. Dropping a `create_sandbox` future before startup stops the sandbox. ## Bytes and results `run` and `Command::wait` return a `CommandResult` with `exit_code`, plus `stdout` and `stderr` as `Vec`. A command’s exit code is never an error. Commands take `impl Into`: `&str` or `String` runs as a shell script; an array or `Vec` of strings runs as argv. ## Errors Every call returns `dvm_run::Result` with `dvm_run::Error`: * **HTTP statuses:** `InvalidRequest` (400), `Authentication` (401), `NotFound` (404), `Conflict` (409), and `Refused { status, reason }` for others (such as 402 and 403). * **Lifecycle:** `SandboxEnded` and `SandboxFailed` when the sandbox ended first. * **Session server:** `SandboxRequest` when the sandbox rejects a request. * **Client/transport:** `NoApiKey`, `Credentials`, `Network`, `Unexpected`. See [Errors](/reference/errors/). rust/dvm-run/examples/errors.rs
```rust
let made = client
.create_sandbox("alpine:3.20")
.command(["true"])
.cpus(64)
.await;
match made {
Ok(sandbox) => match sandbox.wait().await {
Err(Error::SandboxFailed { reason, .. }) => println!("dvm ended it: {reason}"),
waited => println!("{:?}", waited?),
},
Err(Error::InvalidRequest { reason }) => println!("400 {reason}"),
Err(Error::Refused {
status: 402,
reason,
}) => println!("out of credit: {reason}"),
Err(Error::Refused {
status: 403,
reason,
}) => println!("not let in yet: {reason}"),
Err(error) => return Err(error),
}
```
Calling a command, file call, or `end` on a one-program sandbox returns `Error::Conflict` locally (Python and TypeScript raise a plain `DvmError`). A signal outside 1 to 64 returns `Error::SandboxRequest`. ## Where next * [Sessions](/guides/sessions/): run commands and transfer files. * [Rust reference](/reference/rust/), plus docs on [docs.rs/dvm-run](https://docs.rs/dvm-run) and [docs.rs/dvm-api](https://docs.rs/dvm-api). * [crates.io](https://crates.io/crates/dvm-run) and [source](https://github.com/deterministic-machines/sdk/tree/main/rust).
# TypeScript
> Install the dvm-run npm package (Node 22.12+), clean up with await using, cancel calls with AbortSignal, and handle errors.
Install the TypeScript SDK and learn how it handles cleanup, cancellation, and errors.
```sh
npm install dvm-run
```
Published as `dvm-run` on npm: ES modules only, built-in types, Node 22.12 or newer, zero dependencies. Includes the `dvm-run` CLI ([Getting in](/start/access/)). ## Create and end a sandbox `Sandbox.create(image, options)` resolves once the sandbox runs (or has exited). Options: `command`, `entrypoint`, `cpus`, `memoryMib`, `seed`, `env`, `name`, `network`, `allow`, `apiKey`, `apiUrl`, and `signal`. Declare sandboxes with `await using`. When the scope exits: * a session (a sandbox accepting commands) closes its input, and the scope waits for exit; * a paused sandbox or one-program sandbox is stopped; * an ended sandbox is left unchanged. `await using` requires a runtime that supports it, such as Node 24. On Node 22, call `end()` or `stop()` in a `finally` block, or call `sandbox[Symbol.asyncDispose]()` there. An unended sandbox keeps running. Call `Sandbox.connect(sandboxId)` to attach to a sandbox created elsewhere. ## Bytes and results `run` and `Command.wait()` resolve to a `CommandResult` with `exitCode`, `stdout`, and `stderr` (`Uint8Array`). File contents are also `Uint8Array`. A command’s exit code is never an error. IDs, offsets, and seeds are JavaScript numbers kept below 253. ## Cancel a call Every call takes an `AbortSignal` via `signal`. Aborting rejects the call without undoing work already sent. Aborting a command’s `wait` leaves the command running: signal it to end it. Aborting `Sandbox.create` during startup stops the sandbox. js/examples/abort.ts
```ts
const server = await sandbox.start(["sleep", "600"]);
try {
await server.wait({ signal: AbortSignal.timeout(5_000) });
} catch (error) {
if (!(error instanceof DOMException && error.name === "TimeoutError")) throw error;
await server.signal(9);
console.log((await server.wait()).exitCode);
}
```
## Errors All errors inherit from `DvmError`. HTTP errors throw `ApiError` (`status`, `reason`), with subclasses for 400, 401, 404, and 409. Calling an ended sandbox throws `SandboxEndedError`, or `SandboxFailedError` (with `reason`) if dvm or the platform ended it. Connectivity errors throw `NetworkError`. Sandbox-side rejections throw plain `DvmError` with the message. See [Errors](/reference/errors/). js/examples/errors.ts
```ts
try {
await using sandbox = await Sandbox.create("alpine:3.20", { command: ["true"], cpus: 64 });
await sandbox.wait();
} catch (error) {
if (error instanceof InvalidRequestError) console.log(error.status, error.reason);
else if (error instanceof SandboxFailedError) console.log("dvm ended it:", error.reason);
else if (error instanceof ApiError && error.status === 402) console.log("out of credit:", error.reason);
else if (error instanceof ApiError && error.status === 403) console.log("not let in yet:", error.reason);
else throw error;
}
```
## Where next * [Sessions](/guides/sessions/): run commands and transfer files. * [TypeScript reference](/reference/typescript/): every class and method. * [npm](https://www.npmjs.com/package/dvm-run) and [source](https://github.com/deterministic-machines/sdk/tree/main/js).
# Errors
> HTTP error statuses returned by dvm.run, what each means, and how each SDK surfaces them.
When dvm.run rejects a request, it returns an HTTP status code and a JSON body with a `message` field explaining why. Each SDK surfaces that text on its error: `ApiError.message` in Python, `ApiError.reason` in TypeScript, and the `reason` of `dvm_run::Error` in Rust. A program’s exit code is never treated as an error. ## Statuses | Status | Means | Python, TypeScript | Rust | | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------ | ------------------------------------ | | `400` | The request isn’t one dvm.run takes: a bad image name, a value out of range, a sandbox larger than your plan allows, an input chunk over 64 KiB. | `InvalidRequestError` | `Error::InvalidRequest` | | `401` | No key, or a key that was revoked or isn’t one: `that API key was revoked, or isn't one: send Authorization: Bearer `. | `AuthenticationError` | `Error::Authentication` | | `402` | Your credit doesn’t pay for it: `your credit is used up: what's left pays for less than a minute of this sandbox`. | `ApiError`, `status` 402 | `Error::Refused { status: 402, .. }` | | `403` | Your account is on the waitlist: `you're on the waitlist: you can use dvm once we let you in`. | `ApiError`, `status` 403 | `Error::Refused { status: 403, .. }` | | `404` | No such sandbox, or not yours (`no sandbox N`); or, at a point of a run, no such file. | `NotFoundError` | `Error::NotFound` | | `409` | What you asked can’t be done in the state it’s in. | `ConflictError` | `Error::Conflict` | None of the SDKs defines a dedicated class for `402` or `403`; check the status code instead. ## `409` in detail * **Too many active sandboxes:** `you have N sandboxes going, the most the plan allows; stop one first`. * **Too many concurrent seeks:** `too many timeline seeks in progress; try again in a moment`. * **Session input errors:** `this sandbox runs a program and takes no input`, `the run has not started yet`, `the run already ended`, `input already ended at length N`. * **Concurrent run modification:** `run N changed meanwhile; reload it and try again`. * **Sandbox already ended:** `sandbox N has ended`. Instead of a conflict error, the SDKs raise `SandboxEndedError` (`Error::SandboxEnded`), or `SandboxFailedError` (`Error::SandboxFailed`) with the reason when dvm or the platform terminated the sandbox. * **Inspection errors:** `sandbox N is still running`, `sandbox N was stopped before exit`, `sandbox N failed before exit`, `… ran on an older dvm than its runner's now: run it again`, or the reason a replay failed ([Inspecting a finished run](/guides/inspect/)). ## Inspection statuses When inspecting a point in a run, an error’s body has, beside `message`, a `file_error` or `stop_error` field that names its kind, such as `{"message": "the sandbox is returning to that point", "stop_error": "returning"}`: | Status | Means | | ------ | ---------------------------------------------------------------------------------------------------------------------------------------- | | `400` | The path isn’t absolute, isn’t a directory for a list, or isn’t a regular file for a read. | | `404` | No such file there. | | `409` | `the sandbox isn't held at that point`. The routes seek there again first, so you see this only when that didn’t hold either: ask again. | | `422` | The bytes aren’t in the recording (`the sandbox never read the bytes from there`), or a number in the answer would reach 253. | | `500` | dvm couldn’t read the file. | | `501` | `dvm doesn't serve this mount's files yet`. | | `503` | `the sandbox is returning to that point`: it wasn’t there yet when the call’s wait ran out. The SDKs ask again, up to four times. | ## Other errors the SDKs raise | | Python | TypeScript | Rust | | ------------------------------------------------------------------------------- | -------------------- | -------------------- | ----------------------- | | Every error | `DvmError` | `DvmError` | `dvm_run::Error` | | dvm.run out of reach, or the connection dropped | `NetworkError` | `NetworkError` | `Error::Network` | | Another status | `ApiError` | `ApiError` | `Error::Refused` | | The sandbox ended first | `SandboxEndedError` | `SandboxEndedError` | `Error::SandboxEnded` | | dvm or the platform ended it | `SandboxFailedError` | `SandboxFailedError` | `Error::SandboxFailed` | | The session’s server refused a request, such as reading a file that isn’t there | `DvmError` | `DvmError` | `Error::SandboxRequest` | | A command sent to a sandbox running its own program | `DvmError` | `DvmError` | `Error::Conflict` | | No key found | `DvmError` | `DvmError` | `Error::NoApiKey` | | A credentials file that isn’t what `dvm-run login` writes | `DvmError` | `DvmError` | `Error::Credentials` | ## Retries The SDKs retry after 0.1, 0.25, 0.5, and 1 second on `408` and `429`, and on `502`, `503`, and `504` for requests that are safe to repeat. A `Retry-After` header is honored up to 5 seconds. They wait up to 60 seconds for a response.
# HTTP API
> HTTP routes called by the SDKs to manage sandboxes, stream session I/O, and inspect runs.
All three SDKs call this HTTP API. Use this page to call it directly; it lists only the routes the SDKs use. Rust types live in [`dvm-api`](https://docs.rs/dvm-api), and every JSON field below matches them. ## Request conventions * **Base URL:** `https://sandbox.dvm.run/api` plus the route. * **API key:** every route except login requires `Authorization: Bearer ` ([Getting in](/start/access/)). * **Bodies:** JSON (`Content-Type: application/json`), except input requests and output/file responses, which are raw bytes. * **Errors:** an HTTP error status and a JSON body with `message` ([Errors](/reference/errors/)). * **Numbers:** IDs, offsets, versions, and seeds are integers below 253. ## Sandboxes ### `POST /sandboxes` Creates a sandbox and returns `201` with it. Request body fields: | Field | Type | Left out | | ------------- | ---------------------------------------------------------------------------------- | ----------------- | | `image` | an image reference, as `docker run` takes it | needed | | `command` | argv | none | | `entrypoint` | a string | the image’s | | `cpus` | integer | 1 | | `memory_mib` | integer | 1024 | | `seed` | integer | 0 | | `name` | string | from the image | | `environment` | `[{"name": …, "value": …}]` | the image’s alone | | `network` | `{"mode": "public"}`, `{"mode": "none"}`, or `{"mode": "allowlist", "allow": […]}` | `public` | Omitting both `command` and `entrypoint` creates a [session](/guides/sessions/) (a sandbox that accepts commands). See [One-program sandboxes](/guides/programs/) for parameter ranges. Every sandbox route returns a sandbox object with these fields: | Field | | | ----------------- | -------------------------------------------------------------------------------------------------------- | | `id` | its id | | `spec` | the fields above, as the sandbox has them now | | `run.state` | `{"kind": …}`: `queued`, `running`, `paused`, `exited` with `code`, `stopped`, or `failed` with `reason` | | `run.version` | grows with every change to the run | | `run.inspectable` | whether its run can be inspected now | ### `GET /sandboxes/{id}` Returns the sandbox. With `?newer_than=`, waits until the run’s version passes that value or about 30 seconds elapse (how the SDKs wait for state changes). Returns `404` if missing or not yours. ### `POST /sandboxes/{id}/pause`, `/resume`, `/stop` Pauses, resumes, or stops the run and returns its `run`. Returns `409` if invalid in the current state (such as after ending). ### `PUT /sandboxes/{id}/network` Updates where outbound connections may go and returns the sandbox. Body is a `network` object as above. Returns `409` once ended. ## Session input and output Sessions run over byte streams: append frames (a JSON header line plus raw payload bytes) to input and read response frames from output ([The sandbox protocol](/reference/wire/)). ### `POST /sandboxes/{id}/input?offset=&end=` Appends the raw body (`application/octet-stream`, max 64 KiB) at byte `offset` from the start of input. Returns `{"length": , "ended": }`. * An `offset` below the current length skips already-received bytes (safe to retry); past the length is rejected. * `end=true` closes input after this chunk; the session server reads up to there and exits. * Waits while the sandbox has not consumed earlier input. * Returns `409` for a one-program sandbox (`this sandbox runs a program and takes no input`), unstarted or ended sandboxes, or already-ended input. ### `GET /sandboxes/{id}/output?offset=&stderr_offset=` Returns bytes written by the first process after stdout `offset` and `stderr_offset` as one frame ([Output frames](/reference/wire/#output-frames)). With `offset`, waits up to about 30 seconds for new bytes; without, returns immediately from the start. For a session, stdout holds session server response frames; for a one-program sandbox, its own output. ## Inspection Available once a sandbox exits ([Inspecting a finished run](/guides/inspect/)). ### `POST /sandboxes/{id}/points/seek` Body takes `target` and optional `watch_points` (events to stop on): * `target`: `{"kind": "end"}`, `{"kind": "at_ns", "ns": …}`, or `{"kind": "event", "thread": …, "event": …}`. * `watch_points`: up to 32 objects, each `{"kind": …}`: `syscall`, `named_syscall` with `name`, `page_fault`, `processes`, `file_syscalls`, or `socket_syscalls`. Returns the point reached: | Field | | | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------- | | `thread`, `process`, `event` | the thread it stopped in, its process, and the thread’s event count | | `recording_ns` | about when, in the recording’s time, if known | | `at` | one of `{"syscall": {number, name, args, decoded}}`, `{"page_fault": {address, write, present}}`, `{"arrival": {rip}}` | | `operations`, `stats` | counts up to there | ### `POST /sandboxes/{id}/points/step` Send `{"thread": …, "event": …, "watch_points": […]}` to advance from that point to the next watched event. Returns the new point, or `null` when no more watched events remain. ### `GET /sandboxes/{id}/fs/stat`, `/fs/list`, `/fs/read` Query parameters: `thread`, `event`, and an absolute `path`; `/fs/stat` also accepts `follow_symlinks=true|false`. At that point in the run: * `/fs/stat` returns the file’s metadata: `type`, `mode`, `uid`, `gid`, `size`, `links`, `mtime` and `ctime` as `[seconds, nanoseconds]`, a symlink’s `target` as hex bytes, and its `mount`. * `/fs/list` returns the directory’s entries: `name`, `raw_name` as hex bytes, and `type`. * `/fs/read` returns the raw file bytes. If the sandbox is not currently held at the named point, it seeks there again first. ## Login `dvm-run login` calls these endpoints without an API key: * `POST /cli-logins` with `{"machine": ""}` returns `approve_url`, `code`, `collect_token`, and `expires_at`. * `POST /cli-logins/key` with `{"collect_token": "…"}` waits up to 30 seconds and returns `null` until approved, then returns the new key once as `secret`. The CLI then calls `GET /me` with the new key to display who you are signed in as.
# Frames and the sandbox protocol
> Frame format, output frame headers, and the session server's request/response protocol.
Needed only when driving a session (a sandbox accepting commands) without an SDK. The SDKs handle all of this. ## Frames A frame is a single-line JSON object ending in LF, followed by the exact number of raw bytes in its `bytes` field. Omit `bytes` when the payload is empty. * JSON header line (without LF): at most 64 KiB. * Raw payload: at most 16 MiB. Each SDK ships a codec matching `dvm-api` (`encode_frame`, `FrameDecoder`). ## Output frames `GET /sandboxes/{id}/output` returns one frame with this header: | Field | | | -------- | ------------------------------------------------------------------------- | | `stdout` | how many of the payload’s bytes are stdout; the rest are stderr | | `stderr` | how many are stderr | | `more` | the run is still going, or more is held: ask again | | `cut` | the page stopped short, at 4 MiB a stream: ask again from the new offsets | | `bytes` | the payload’s length, left out when empty | The payload holds stdout bytes, then stderr bytes. Add each length to its offset and repeat until `more` and `cut` are both false. This standalone example decodes a frame locally without connecting to dvm.run: python/examples/output_frame.py
```python
def decode_output(body: bytes) -> tuple[dict, bytes, bytes]:
line_end = body.index(b"\n")
header = json.loads(body[:line_end])
payload = body[line_end + 1 :]
if len(payload) != header.get("bytes", 0):
raise ValueError("the frame's payload isn't the length its header counts")
stdout, stderr = payload[: header["stdout"]], payload[header["stdout"] :]
return header, stdout, stderr
```
python/examples/output_frame.py
```python
body = b'{"stdout":2,"stderr":4,"more":false,"cut":false,"bytes":6}\nhioops'
header, stdout, stderr = decode_output(body)
assert (stdout, stderr) == (b"hi", b"oops")
assert header["more"] is False and header["cut"] is False
```
## Session protocol A session’s first process is `sandbox-server`. Append request frames to its input ([`POST …/input`](/reference/http/#session-input-and-output)) and read response frames from its stdout via the output route. Stderr stays empty. Read responses while writing requests: the server writes as it goes, and a slow reader slows it down. ### Request IDs Each request has an unsigned integer `id`. A `run`, `read`, or the first chunk of a `write` starts an operation and must use an ID greater than all prior started IDs (gaps are allowed; 0 is valid). Lower IDs fail with an error naming the last started ID. Later write chunks, `stdin`, and `signal` reuse their operation’s ID. The SDKs use each request’s input byte offset as its ID. ### Requests | Request | Fields | Payload | | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- | | `{"id": n, "run": {…}}` | `argv` (a list) or `script` (a string), exactly one; `env` (an object), `cwd`, `user`, `stdin` (true to keep it open; false gives `/dev/null`) | none | | `{"id": n, "stdin": {"close": bool}}` | `close`, false if left out | bytes for the command’s stdin | | `{"id": n, "signal": s}` | a signal from 1 to 64, sent to the command’s process group | none | | `{"id": n, "write": {…}}` | `path`; `mode` (decimal, 420 if left out) on the first piece; `last`, false if left out | a piece of the file | | `{"id": n, "read": {"path": …}}` | `path` | none | A `script` runs under `/bin/bash -lc` if the image has `/bin/bash`, or `/bin/sh -c` otherwise. `stdin` and `signal` return no response when they succeed. Unknown fields, two operations in one frame, or specifying both `argv` and `script` are rejected. ### Responses | Answer | Means | | -------------------------------------------------------- | ------------------------------------------------------------------------------- | | `{"id": n, "started": {"pid": …, "argv": […]}}` | the command started; first for a command | | `{"id": n, "stdout": true}`, `{"id": n, "stderr": true}` | a chunk of the command’s output, in the payload | | `{"id": n, "exited": {"code": c}}` | the command’s process was reaped: its exit code, or 128 plus the killing signal | | `{"id": n, "written": true}` | a write’s last piece was written | | `{"id": n, "data": true}` | a piece of a read file, at most 256 KiB, in the payload | | `{"id": n, "end": true}` | a read is done | | `{"id": n, "error": "…"}` | a request refused, or a file operation failed | | `{"error": "…"}` | a frame that couldn’t be read at all | * A command’s stdout and stderr each preserve their own order. No ordering is guaranteed between the two streams or between different commands. * A child process started by a command can continue writing under that command’s ID after `exited`. * An error frame with no ID also fails every write in progress, each with its own error, because the lost frame may have carried a chunk of any of them. ### Ending a session When its input closes, the server kills every running command and exits 0, ending the sandbox.