Environments
Provisioning, running commands in, and tearing down microVMs
client.environments provisions, inspects, drives, and tears down microVMs.
Here’s a complete flow: create one, run a command inside it, then tear it
down.
const env = await client.environments.create({
task_id: "build-1",
spec: { cpus: 2, ram_mb: 2048, storage_gb: 10 },
});
const result = await client.environments.exec(env.id, { cmd: ["make", "test"] });
if (result.exit_code !== 0) {
throw new Error(`tests failed: ${result.stderr}`);
}
await client.environments.destroy(env.id);
createprovisions from aspec(CPUs, RAM, storage, and optionally GPU) and blocks server-side until the environment isrunningor provisioning fails, so the returnedEnvironmentInfoalready reflects the outcome. No separate poll-until-ready step is needed for the common case. Wire field names are snake_case throughout,task_id/ram_mb, nottaskId/ramMb.Speccarriesgpus,gpu_kind, andgpu_profile, so fractional MIG environments can be requested type-safely from this SDK. Any ofcpus,ram_mborstorage_gbleft unset (or0) defaults to 1 vCPU, 1024 MB or 4 GB; a negative value is a 400.execruns one command inside the guest and returns its exit code with stdout/stderr kept apart. A non-zeroexit_codeis a resolved call, not a thrown error, the command ran and failed, which is the answer you asked for. Only a thrown error means the command couldn’t run at all (VM not found, VM not running, or the provider has no guest to exec into).execrequires the master token, see Errors.destroytears the environment down from any state. A second call on an already-gone environment throws aFuseApiErrorwithcode === "not_found"rather than hanging or throwing something unrelated; a retry that passes the first call’sidempotencyKeygets the first call’s success back instead.
create, destroy, fork, migrate and drain run as operations: each
takes an idempotencyKey in its trailing options, and one that outlasts the
server’s attach bound is followed to the end for you. See
Operations.
Proxied egress
egress on the create request routes the environment’s outbound traffic
through a provider the orchestrator has registered; omit it for direct
egress. Every read carries the resolved policy back, with the proxy’s last
probe verdict under health:
const env = await client.environments.create({
task_id: "scrape-1",
egress: { mode: "proxy", provider: "cloudflare-warp" },
});
const info = await client.environments.get(env.id);
if (info.egress?.health?.state === "unhealthy") {
// the environment is still running, with no egress at all
console.warn(`proxy down: ${info.egress.health.reason}`);
}
mode, provider and state are plain strings rather than unions, so a
server that grows a new value does not turn into a compile error here. See
the egress guide for what proxy mode enforces.
A provider that takes a credential reads it from one of the request’s
secrets, named by secret. The value goes to the host’s egress backend and
is left out of the secrets the guest receives:
const env = await client.environments.create({
task_id: "scrape-1",
secrets: { WG_CONF: wgConfBase64 },
egress: { mode: "proxy", provider: "wireguard", secret: "WG_CONF" },
});
Egress allowlist
allow on a direct egress restricts outbound traffic to IPv4 cidrs, and
setEgressAllow replaces the list while the environment runs. It resolves to
the environment’s EgressStatus:
const env = await client.environments.create({
task_id: "agent-1",
egress: { mode: "direct", allow: ["10.0.0.0/8"] },
});
const st = await client.environments.setEgressAllow(env.id, ["10.0.0.0/8", "203.0.113.7"]);
console.log(st.allow); // ["10.0.0.0/8", "203.0.113.7/32"]
// an empty list lifts the restriction
await client.environments.setEgressAllow(env.id, []);
The server normalizes the list (a bare address is a /32, host bits are
dropped, duplicates go, at most 256) and the returned status carries the list
the host now enforces. An empty list lifts the restriction. A proxy
environment, or one that is not running or is being migrated, is a 409
conflict; a malformed or IPv6 entry is a 400. The call runs as an operation
(kind egress.allow) and takes an idempotency key like the other mutating
calls. See the egress guide for what
the list covers.
Watching state instead of exec
If you need to react to lifecycle transitions rather than run a one-shot
command, events returns an async iterable instead of a single call:
for await (const event of await client.environments.events(env.id)) {
console.log(event.state);
}
The stream yields the current state immediately on connect, then one item
per transition, and ends on its own after a terminal-state event
(destroyed/failed). There is no built-in timeout, pass { signal } to
cancel early. See the full walkthrough in
Quickstart.
Everything else
| Method | Purpose |
|---|---|
list({ taskId, state, hostId }) |
List environments, all filters optional. |
get(vmId) |
Fetch one environment by ID. |
drain(vmId) |
Phase one of teardown: signal the guest to stop gracefully without destroying the VM. |
fork(vmId, { reuse_snapshot_id, comment, live, count }) |
Create count new environments (default 1) seeded from one snapshot of this one; resolves to EnvironmentInfo[], every child in order. |
setEgressAllow(vmId, cidrs) |
Replace a running direct environment’s outbound IPv4 allowlist; resolves to its EgressStatus. See Egress allowlist. |
rotateToken(vmId) |
Re-issue the guest’s credentials without recreating the VM. |
doctor(vmId) |
Run the in-guest self-check; resolves to a DoctorReport with one DoctorCheck per piece (identity, dbus, disk, memory, each display piece, healthcheck, dns, egress, clock). A failing check is a "fail" line, not a rejection. |
The two option bags differ in case on purpose. list takes a client-side
filter object, so it is camelCase; fork sends its object straight through as
the JSON request body, so it uses the snake_case wire names.
fork always resolves to a list, even for one child, and a fork a hitl gate
held comes back as a one-element list once approved. live: true resumes every
child from a live snapshot’s memory image, see
Forking. If any child fails, fork
rejects with the first failure; the children that did fork keep running and the
error message names them.
const children = await client.environments.fork("fuse-abc123", { live: true, count: 3 });
Every method accepts a trailing { signal } for cancellation. Fork is
unavailable wherever snapshotting is, GPU/QEMU-backed environments can’t be
forked, see Providers. These mirror the
HTTP API one to one.
Lifecycle states
export const State = {
Provisioning: "provisioning",
Running: "running",
Draining: "draining",
Destroying: "destroying",
DestroyFailed: "destroy_failed",
Destroyed: "destroyed",
Failed: "failed",
} as const;
function isTerminalState(state: string): boolean;
isTerminalState reports whether state is Destroyed or Failed, the two
states after which an event stream ends.