TypeScript SDK
@kvbox/sdk: create boxes, run commands in them, snapshot them and give them volumes from a program.
@kvbox/sdk is the kvbox API from TypeScript and JavaScript: the same boxes, snapshots and volumes as the CLI, as plain function calls that return typed objects. Use it when kvbox is a part of your program (an agent that hands each task a fresh VM, a test runner, a preview service) rather than something you type.
import { Kvbox } from "@kvbox/sdk";
const kvbox = new Kvbox(); // the API key in KVBOX_TOKEN
const box = await kvbox.machines.create({ name: "job1", size: "s" });
await kvbox.machines.waitUntilReady(box.name);
const run = await kvbox.machines.exec(box.name, "uname -a && nproc");
console.log(run.exitCode, run.stdout);
await kvbox.machines.remove(box.name);Install
npm install @kvbox/sdkIt is an ES module with its types included. Its one dependency is zod, which checks every answer the API gives.
Authentication
The SDK acts with an API key: make one with kvbox key create, or in the web app under API keys, and give it to the program as KVBOX_TOKEN:
kvbox key create my-app # prints kvb_..., once
export KVBOX_TOKEN=kvb_...new Kvbox() reads KVBOX_TOKEN and KVBOX_URL from the environment, the same two variables the CLI reads, so one key serves both. KVBOX_URL is for a control plane other than the kvbox cloud (https://api.kvbox.sh). Both can be given in code instead:
const kvbox = new Kvbox({
apiKey: process.env.MY_KVBOX_KEY,
baseUrl: "https://cp.example.com",
});A key acts as you, in your account and in every org you belong to, except that it cannot manage API keys. Give each program its own key, so you can remove that one alone.
Client options
new Kvbox(options?: {
apiKey?: string; // default: KVBOX_TOKEN
baseUrl?: string; // default: KVBOX_URL, else https://api.kvbox.sh
org?: string; // the org every call acts in; default: your own account
fetch?: typeof fetch; // default: the global fetch
timeoutMs?: number; // how long one request may take; default 300000 (5 minutes)
})kvbox.baseUrl says which API the client talks to.
Boxes: kvbox.machines
A box name is bare (web) or slug/name (acme/web, a box of the org acme). A bare name is your own box, else the one box of that name in an org you belong to. See Orgs.
| Method | What it does |
|---|---|
list({ org?, all? }) | Every box you can read, yours and your orgs', as Machine[] |
get(name, { org? }) | One box; NotFoundError when there is none |
create(request?, { org? }) | Make a box and boot it |
waitUntilReady(name, { timeoutMs?, intervalMs?, org? }) | Resolve once the box is running |
exec(name, command, { timeoutMs?, pollMs?, org? }) | Run a command, resolve with its exit code and output |
startExec(name, command, opts?) / getExec(name, id, { org? }) | Start a command without waiting, look at it later |
start(name, { force?, org? }) | Boot a stopped box |
stop(name, { org? }) | Shut it down; its disk stays |
restart(name, { force?, org? }) | Stop and boot again in one step: credit and room are checked before the stop |
pause(name) / resume(name) | Freeze it in memory, and back |
hibernate(name) / wake(name, { force? }) | Write its memory to disk and free it, and back |
fork(name, request?, { org? }) | A copy of the box as it is now, on the same host |
ports.add(name, { ports }) / ports.remove(name, { ports, keep? }) | Publish box ports on the host's public address, or stop |
traffic(name, { since?, until?, stepMin?, host?, org? }) | What reached the box through its HTTPS names: requests by status class, latency, bytes, wakes |
resources(name, { since?, until?, stepMin?, org? }) | The box's CPU, memory, disk and network over time, measured while it runs |
remove(name, { org? }) | Remove the box and its disk |
Every method that acts on a box answers with the box as it is after, a Machine:
{
id, name, owner, status, // status: "running" | "standby" | "hibernated" | "stopped" | "unknown"
ip, vcpu, memMib, diskBytes, diskUsedBytes, base, image?, createdAt, source,
ssh?: { host, port, user }, ports?, volumes?, host?, country?, ownerKind?, autoHibernateSec?,
cluster?: { name, pool }, // a Kubernetes cluster's node: its cluster and pool
clusterId?, // the id of the cluster the box is in on its host
connect?, // create only, for an image that serves something: its URL with the password
}standby is a paused box. unknown is not a state of the box: its host has not answered lately. See Stop, pause, hibernate.
A box with cluster is a node of a Kubernetes cluster: it is read, started and woken, and exec runs in it, like any box, but whatever would change it (remove, stop, set, ports, links…) answers a 400 KvboxApiError naming its pool: kvbox k8s pool resize <cluster> <pool> --nodes <n>.
Create a box
const box = await kvbox.machines.create({
name: "web", // default: box1, box2, ...
size: "m", // xs, s (default), m, l: see Sizes
autoHibernateSec: 1800, // hibernate after 30 minutes without network traffic; 0: never
env: [{ name: "NODE_ENV", value: "production" }],
});The other fields are from (a snapshot to start a warm copy from), fromBackup (a box backup's id, a removed box's too: the box starts on its disk, image and variables, and the call waits for the download), image (postgres, and the other images), near (a box whose host the new one goes on, to link them), location (a country or a region, DE or eu: see Locations; country is its older spelling) and force (start even when the host is short of RAM). See Sizes for what each size is.
Wait until it is ready
create, start and fork answer once the VM has started. The system inside it boots for a few seconds more, and the box's listing has no word for that moment, so waitUntilReady waits for what it does say: status running. It looks every intervalMs (1 s) and gives up after timeoutMs (2 minutes) with a KvboxTimeoutError. A moment without the API (a redeploy) is waited through; a box that does not exist is a NotFoundError at once.
const ready = await kvbox.machines.waitUntilReady("web", { timeoutMs: 60_000 });So running does not yet mean that sshd and kvbox-agent listen: an exec sent in the first seconds after a cold boot can be refused with its kvbox-agent is not answering. Wait a few seconds more, or try the exec again on that error.
Run a command
const run = await kvbox.machines.exec("web", "cd /app && npm test", { timeoutMs: 120_000 });
if (run.timedOut) throw new Error("tests took over 2 minutes");
if (run.exitCode !== 0) console.error(run.stderr);The command is one string, as you would type it after kvbox exec web --: it runs in a login shell (bash -lc) as the box's user kvbox, in its home, with your environment variables. Pipes, && and redirects work. There is no terminal and no stdin: to put a small file in the box, write it with the command (a heredoc), or pipe it in with the CLI's kvbox exec.
exec resolves once the command is over:
{
exitCode: number | null, // null when it was killed at its time limit
timedOut: boolean,
stdout: string, // the first MiB, as UTF-8 text
stderr: string, // the same
truncated: boolean, // either stream was longer than its MiB
durationMs: number, // how long the command ran, by the box's clock
}timeoutMsis the command's own time limit: 10 minutes when not given, at most 24 hours, in whole seconds on the box. At the limit the command and everything it started are killed. The SDK waits a minute past it for the answer before aKvboxTimeoutError.- A command that exits non-zero is not an error: read
exitCode. Only a command that could not be run throws. - A paused or hibernated box is woken first. A stopped box is refused with a
ConflictError:startit first. pollMs(1 s) is how often the SDK asks whether the command is over.
For a command you do not want to wait on, startExec answers at once with its id (and woke, whether the box was asleep); getExec tells how it stands, running, then exited or timeout with the output:
const { id } = await kvbox.machines.startExec("web", "./build.sh", { timeoutMs: 3_600_000 });
// later
const job = await kvbox.machines.getExec("web", id);
if (job.state !== "running") console.log(job.exitCode, job.stdout);To start a server and leave it running, detach it as with the CLI: setsid -f node server.js > server.log 2>&1 < /dev/null. See Connect and exec.
Traffic
traffic reads what kvbox's edge counted for the box's HTTPS names (*.kvbox.app and custom domains), the last 24 hours by default:
const { totals, points, hosts } = await kvbox.machines.traffic("web", { since: new Date(Date.now() - 3_600_000) });
console.log(totals.requests, totals.s5xx, totals.p95Ms); // p50Ms / p95Ms read "at most", in mstotalsand each ofpoints(oldest first, only steps with a request) haverequests,s2xxtos5xx,bytesIn,bytesOut,wakes(requests that woke the box),wakeWaitMs(their average wait),p50Msandp95Ms.stepMinis 5, 15, 60, 360 or 1440 minutes (5 up to a day, 60 beyond);hostkeeps one of the names inhosts.- Kept 7 days. Published ports and SSH do not pass the edge and are not counted; paths, addresses and headers are never stored.
Resources
resources reads what the box's host measured of it once a minute while it ran, the last 24 hours by default:
const { totals, points, vcpu } = await kvbox.machines.resources("web", { since: new Date(Date.now() - 3_600_000) });
console.log(totals.cpuPct, totals.cpuMaxPct, totals.memUsedMib); // CPU as a percent of the box's vCPUstotalsand each ofpoints(oldest first, only steps in which the box ran) havecpuPct(average) andcpuMaxPct(the busiest minute),memUsedMib(average),memMaxMibandmemTotalMib,diskUsedBytesanddiskTotalBytes(as last seen),netInBytesandnetOutBytes.- CPU and network are measured from outside the box. Network is everything on the box's network interface: HTTPS names, published ports, SSH and what the box sends out.
- Memory and disk are the box's own answer:
nullwhen it gave none (a box on an old base image, or one too busy to answer). stepMinis 5, 15, 60, 360 or 1440 minutes (5 up to a day, 60 beyond). Kept 7 days. A box that is paused, hibernated or stopped has no points for that time.
Put a box away and bring it back
await kvbox.machines.hibernate("web"); // memory to disk, RAM freed: only the disk is billed
await kvbox.machines.wake("web"); // processes and all, where they were
await kvbox.machines.stop("web"); // processes gone, files kept
await kvbox.machines.start("web");
await kvbox.machines.restart("web"); // stop and boot as one call: what start costs, checked before the stopFork and publish ports
const copy = await kvbox.machines.fork("web", { name: "web-try" }); // warm when web runs, cold when stopped
const withPort = await kvbox.machines.ports.add("web", { ports: [{ guestPort: 8080 }] });
console.log(withPort.ports); // [{ guestPort: 8080, hostPort: 23817, proto: "tcp", address: "..." }]A hibernated box cannot be forked: wake it first. The copy keeps the source's size; published ports and HTTPS names stay with the source.
An HTTPS name (https://<sub>.kvbox.app) is not in the SDK yet: use kvbox vm proxy claim, see Ports and HTTPS names.
Snapshots: kvbox.snapshots
| Method | What it does |
|---|---|
list({ org?, all? }) | Every snapshot you can read, as Snapshot[] |
create({ box, name, replace? }, { org? }) | Freeze the box's memory and disk; it is paused while it is taken |
remove(name, { org? }) | Remove a snapshot; boxes started from it keep running |
A snapshot starts warm copies: machines.create({ from }) boots one in well under a second, every process still running.
await kvbox.snapshots.create({ box: "web", name: "web-warm" });
const clone = await kvbox.machines.create({ name: "web2", from: "web-warm" });replace: true takes a snapshot again under a name that exists. See Snapshots.
Volumes: kvbox.volumes
| Method | What it does |
|---|---|
list({ org?, all? }) | Every volume you can read, as Volume[] |
create({ name, sizeGib, box }, { org? }) | Make a volume on the host of box |
attach(name, box) / detach(name, box) | Attach it to a box, or take it off; answers the box |
grow(name, sizeGib) | Make it bigger; it never shrinks |
remove(name, { org? }) | Remove a detached volume and its data |
A volume is a disk that outlives a box, mounted at /mnt/<name> inside the box it is attached to. create needs the box it is for, since a volume attaches only to a box on its own host, and does not attach it:
await kvbox.volumes.create({ name: "data", sizeGib: 20, box: "web" });
await kvbox.volumes.attach("data", "web"); // a running box restarts to take it
await kvbox.machines.exec("web", "df -h /mnt/data");Attaching, detaching and growing restart a running box that holds the volume, and are refused for a hibernated one. See Volumes.
Kubernetes: kvbox.k8s
A cluster kvbox runs: a master you never see, and nodes that are boxes of yours, in pools of one size each.
const made = await kvbox.k8s.create({ name: "prod", size: "m", nodes: 2 }); // answers once its boxes are made
const cluster = await kvbox.k8s.waitUntilReady("prod"); // the API answers, every node is Ready
console.log(cluster.price.totalPerMonth, cluster.pools[0]?.boxes); // ["prod-3f2", "prod-a41"]
const kubeconfig = await kvbox.k8s.kubeconfig("prod"); // the file's text: cluster-admin, keep it secret
await kvbox.k8s.list(); // every cluster you can read
await kvbox.k8s.get("prod"); // one, with health, condition, room, addresses and the change going on
await kvbox.k8s.start("prod"); // master and nodes back up (after the account ran out of credit)
await kvbox.k8s.restartNode("prod", "prod-3f2"); // one node stopped and booted again; "prod" itself is the master
await kvbox.k8s.rotate("prod"); // new credentials: every kubeconfig handed out so far stops working
await kvbox.k8s.waitUntilSettled("prod", { timeoutMs: 30 * 60_000 }); // its master and nodes have restarted (throws what could not be done)
await kvbox.k8s.remove("prod");createtakesname(1 to 8 characters),size(s,morl: what each node is sized at),nodes(2 by default, at most 9)near(a box whose host it should share) andlocation(a country or a region to make it in, in place of the account's default). A new cluster goes on one host with room for all of it, or nothing is made; a pool grown later goes onto other hosts when that one is full, and never outside the location the cluster was made under.waitUntilReadygives a new cluster 5 minutes (timeoutMs) and looks every 3 seconds (intervalMs).rotateis for when somebody who had the kubeconfig, or could connect to a node, should no longer have the cluster. It answers once the master has stored its new certificate authorities and tokens; the master then restarts and every node after it, together, so apps on the cluster are down for a few minutes. The control plane gives the master and then the nodes up to 5 minutes each to come back, so givewaitUntilSettledmore than its 15-minute default (the CLI waits 30). Every box must be running, askkubeconfigagain afterwards, and a backup from before it can no longer be restored. Tokens made inside the cluster (a service account's) are not ended.- Only
getanswershealth(ready,ingress,version,certificatesEndAt: when the master's own certificates end, and per nodename,ready,schedulable,volumes,claims;nullwhen the master is not running),room({s, m, l}: how many more nodes fit now on the hosts it may use),addresses,operationandoperationError.listleaves them out. - A node is a box:
kvbox.machines.list()has it withcluster: {name, pool}, andexecruns in it. What would change it is refused; change its pool.
Pools
await kvbox.k8s.pools.add("prod", { size: "l", nodes: 3, name: "big" }); // name defaults to the size
await kvbox.k8s.pools.resize("prod", "big", 5); // more: made before the answer
await kvbox.k8s.pools.resize("prod", "big", 2); // fewer: only begun when this answers
await kvbox.k8s.waitUntilSettled("prod"); // drained and removed, or throws why not
await kvbox.k8s.pools.remove("prod", "big");
await kvbox.k8s.pools.list("prod"); // [{ name, size, nodes, boxes, elsewhere? }]- Fewer nodes, and removing a pool, go on after the answer: the newest nodes are drained one at a time, then removed.
waitUntilSettledresolves when the change is over (15 minutes by default; passtimeoutMsfor several nodes) and throws aKvboxSdkErrorwith what it could not do, such as a node that would not drain. Afterpools.addor a grow it waits for the new nodes to join. - A node that keeps volumes on its own disk is a
ConflictErrorwith codenode-has-databefore anything changes.{ force: true }onresizeorremovetakes nodes away at once, undrained, their data lost. elsewhere(typeClusterNodePlace[]) lists a pool's nodes that are on another host than the cluster's master, each{ name, host, country? }; absent when none is. A pool grows there only when the master's host is full, in its country first, and only inside the location the cluster was made under.- One change per cluster at a time: a second is a
ConflictErrorwith codecluster-busy.
Addresses, links and backups of a cluster are not in the SDK yet: use kvbox k8s proxy|domain|link|backup, or kvbox.request on the /k8s/<name>/… routes.
Container registry: kvbox.registry
The container registry kvbox runs for your account: one per account (or per org, { org } on any call), so no method takes a name.
const made = await kvbox.registry.create({ sizeGib: 50 }); // 20 GB without it; answers in about a minute
console.log(made.address, made.secret.password, made.ready); // "cr-you.kvbox.app", the login, whether it answers yet
const registry = await kvbox.registry.get(); // + usedBytes, totalBytes, repositories [{ name, tags }]
const { address, user, password } = await kvbox.registry.password();
await kvbox.registry.resetPassword(); // a new one; the old stops working at once
await kvbox.registry.grow(100); // only grows; it restarts once
await kvbox.registry.remove(); // with every image in it| Method | What it does |
|---|---|
list({ org?, all? }) | The registry of every account you can read that has one, as Registry[] |
get() | Yours, with how full it is and its repositories when it answers; a NotFoundError when there is none |
create({ sizeGib?, near?, location? }) | Make it (location: a country or a region, in place of the account's default); the answer carries secret (the login) and ready |
password() / resetPassword() | The login as it is, or a new generated password |
grow(sizeGib) | Make it bigger; it never shrinks |
remove() | Remove it and every image |
backups.list() / backups.get(id) | Its backups, newest first; a removed registry's too, for the 30 days they are kept |
backups.create() | Start one; it runs in the background, backups.get(id) says how it ended |
backups.restore(id) | Every image becomes the backup's; the address and password stay. Answers { backup, registry, ready } |
backups.remove(id) | Delete a backup for good |
backups.schedule() / backups.setSchedule({ enabled?, hour? }) | The nightly backup: off until turned on, hour 0-23 UTC |
addressis whatdocker loginand an image's name take;nullonly while no address could be claimed. Never build it by hand.createanswers once the registry is made.ready: falsemeans it did not answer within the wait: it is there, give it a minute.backups.restorewaits for the whole download (it may take a while for a large registry) and only goes into the registry the backup was taken of.
Locations: kvbox.locations and kvbox.location
A location is a country (DE) or a region (eu, us). An account and each org has one default, and every create obeys it: with an API key too, and with no field sent.
await kvbox.locations.list(); // what has a host now: [{ kind, code, name, countries }]
await kvbox.location.get(); // { slug: "you", location: null }: none, any host
await kvbox.location.set("eu"); // { slug, location: "eu", kind: "region", name: "European Union", countries: [...] }
await kvbox.location.set("DE", { org: "acme" }); // an org's: its owners only
await kvbox.location.set(null); // none again
await kvbox.machines.create({ name: "edge", location: "us" }); // this one box elsewhere; the default stays| Method | What it does |
|---|---|
kvbox.locations.list() | The regions, then the countries, with a host answering now, as AvailableLocation[]: kind ("region" or "country"), code, name, countries ([{ code, name }]: where those hosts are) |
kvbox.location.get({ org? }) | The default of your account, or of an org you can read, as SlugLocation: slug, location (its code, or null for none) and, when there is one, kind, name and countries (everything it covers) |
kvbox.location.set(location | null, { org? }) | Set it or clear it; answers the same shape. location is a code or a country's English name |
location on machines.create, k8s.create, registry.create | That one thing inside this location, in place of the default |
- A code comes back as it is kept: a region in lower case (
eu), a country in upper case (DE).usis the region andUSthe country. setmoves nothing that exists. It decides where new things go.- With a location, from the call or the default, a create is never placed elsewhere: no host inside it with room is a 400
KvboxApiErrorwhose message names the location and where there is room.forcedoes not change that. nearandfromname the host themselves and win over the default; with alocationin the same call that does not contain that host, the call is refused.- Backups and a cluster's pools stay inside the location their thing was made under. A backup with no store there ends
failed, at no cost.
Integrations: kvbox.integrations
| Method | What it does |
|---|---|
kvbox.integrations.list({ org? }) | Each of your slugs' state for each integration, as Integration[]; never a credential |
kvbox.machines.create({ integrations: ["github"] }) | A new box with integrations on |
kvbox.machines.set(name, { integrations: ["github"] }) | Replace a box's list; [] turns every one off |
An integration is an account (github, claude) connected once by a person in the web app and turned on per box: git, gh and claude then work in that box with no login. The SDK lists what is connected and sets a box's list; it cannot connect or disconnect.
const [github] = (await kvbox.integrations.list()).filter((i) => i.integration === "github");
if (github?.connected) {
await kvbox.machines.set("web", { integrations: ["github"] }); // at once, no restart
await kvbox.machines.exec("web", "git clone git@github.com:me/private.git");
}machines.set also takes the other box settings (autoHibernateSec, idleCheck); anything left out stays as it is. See Integrations.
Wake hooks: kvbox.hooks
| Method | What it does |
|---|---|
kvbox.hooks.list({ org? }) | The wake hooks of every box in your slugs (org: one org's), as WakeHook[]: id, owner, box, url, createdBy, createdAt, lastCalledAt; never a secret |
A wake hook is a URL that wakes or resumes one box when called (a GitHub webhook, a cron job). Making and removing one is kvbox vm hook create|rm; the secret is shown only then.
const hooked = new Set((await kvbox.hooks.list()).map((h) => `${h.owner}/${h.box}`));Orgs
By default every call acts in your own account, and a listing shows your boxes and every org's you belong to. Three ways to point at an org:
const acme = new Kvbox({ org: "acme" }); // every call of this client
await kvbox.machines.create({ name: "ci" }, { org: "acme" }); // this call only
await kvbox.machines.stop("acme/ci"); // a slug/name names it outrightorg decides where a new box, snapshot or volume goes, and which box a bare name means. Two orgs with a box of the same name, and no org: the call is refused and asks which one. See Orgs.
Errors
Every error the SDK throws is a KvboxSdkError. The API's refusals are KvboxApiError, with the HTTP status, the API's own message (box web: not found) and, for some, a code; one subclass per status a program usually handles:
| Class | When |
|---|---|
UnauthorizedError (401) | No API key, or one that was removed or has expired |
PaymentRequiredError (402) | The account or org may not spend; code is account-inactive, org-inactive or out-of-credit |
NotFoundError (404) | No such box, snapshot, volume or org, or one you cannot see |
ConflictError (409) | The name is taken, or the box is in a state that does not allow it (exec on a stopped box) |
BoxOutdatedError (409) | A ConflictError with code box-outdated: the box's image is too old for exec |
KvboxApiError | Any other status of 300 or more |
KvboxConnectionError | Nothing answered; code is the system's (ECONNREFUSED, ENOTFOUND) |
KvboxTimeoutError | No answer within timeoutMs, or waitUntilReady or exec gave up waiting |
KvboxResponseError | An answer that is not the API's JSON |
import { Kvbox, NotFoundError, PaymentRequiredError } from "@kvbox/sdk";
try {
await kvbox.machines.start("web");
} catch (err) {
if (err instanceof NotFoundError) await kvbox.machines.create({ name: "web" });
else if (err instanceof PaymentRequiredError) console.error("top up:", err.message);
else throw err;
}Any other route
The namespaces cover boxes, snapshots and volumes. For the rest of the API, request sends any route with the same key, org and errors, and checks the answer with a zod schema you give:
import { z } from "zod";
const me = await kvbox.request("GET", "/me", z.object({ username: z.string(), email: z.string() }));request(method, path, schema, { body?, org?, timeoutMs? }): body is sent as JSON, an empty answer is undefined (pass z.undefined()).
Runtimes
The SDK needs only fetch, AbortSignal.timeout and JSON: Node 22 or later, Bun, Deno, and serverless and edge functions. KVBOX_TOKEN and KVBOX_URL are read where there is a process.env; elsewhere pass apiKey and baseUrl. fetch takes your own (a proxy's, a test's fake).
Keep it on a server. An API key in a web page is a key anyone can read, and the API answers browsers only from the kvbox web app.
Limits
execneeds a box made from base image v0.16.0 or later; an older box is aBoxOutdatedError. Make the box again (snapshot what you need, or keep its data on a volume), or run the command withkvbox exec, which goes over SSH.execreturns the first MiB of stdout and of stderr. For more, have the command write to a file in the box, and read it in parts.- A command runs at most 24 hours;
exechas no stdin and no terminal. - Not in the SDK yet: copying files, HTTPS names (their traffic is
machines.traffic; CPU, memory, disk and network aremachines.resources), environment variables, managed databases, object storage, cron, backups of boxes and volumes, orgs and usage. The CLI does all of them, andrequestreaches their routes.