---
name: kvbox
description: |
  Manage kvbox boxes (Firecracker microVMs) from the user's terminal with the `kvbox` CLI.
  Use when: creating, listing, connecting to, stopping/starting, hibernating or removing boxes;
  running commands inside a box; copying files in or out; snapshotting a box and starting warm
  clones; publishing ports or an HTTPS address (`https://<sub>.kvbox.app`); custom domains (`kvbox domain add`); deploying a React or Next.js app, a Node server, a
  Dockerfile or a plain static site to its own HTTPS address (`kvbox deploy`); a managed PostgreSQL
  database (`kvbox pg`) or a managed Redis (`kvbox redis`); S3 object storage (`kvbox bucket`: buckets and
  access keys); a private container registry for docker images (`kvbox registry`); a Kubernetes cluster (`kvbox k8s`); calling a box or running a command in it on a schedule (`kvbox cron`: cron triggers that wake a hibernated box); orgs; usage and credit.
  Also use when the user says "kvbox", "spin up a box", "run this in a VM", "sandbox this",
  "give the agent a machine", or mentions `*.kvbox.app` URLs.
---

# kvbox CLI

kvbox gives you real Linux VMs (Firecracker microVMs, each with its own kernel) that boot in
seconds. A box has a private IP, a persistent disk and your SSH key. A running box can be
snapshotted (memory + disk) and new boxes started from that snapshot already warm, in well under a
second. Ports can be published on the internet, and a box can claim `https://<sub>.kvbox.app`.

You are on the user's machine. `kvbox` talks either to the kvbox cloud (`api.kvbox.sh`, or the
user's own control plane) after `kvbox login`, or to a `kvbox-server` on this machine (`--local`,
or after `kvbox logout`).

> `kvbox <cmd> --help` is the authoritative reference for flags. This skill is about behavior:
> what commands do, when to use which, and the gotchas. Full docs: https://kvbox.cloud/docs
> (as text: https://kvbox.cloud/llms.txt).

## Rules for agents

- **Pass every argument and use `--json`.** Every listing or creating command takes `--json` and
  prints one object or an array. Parse that, never the table output.
- **`kvbox login` needs a person.** It prints a link and a code (`WDJB-MJHT`) on stderr and waits up to 10 minutes
  for the user to approve the code in the web app: show them both, and do not kill the command. With no person
  around use an API key in `KVBOX_TOKEN`, or `kvbox login -e <email> --password-stdin`.
- **Destructive commands need `-y` outside a terminal**: `rm`, `snapshots rm`, `vm proxy rm`,
  `vm proxy release`, `vm unlink`, `org rm`, `org members rm`. Never pass `-y` on something the user did not ask
  to delete.
- **Errors** are one line on stderr and a non-zero exit. Exit 2 means the feature is not built yet.
- **Don't use `connect` for scripted work**: it opens an interactive shell. Use `exec`.

## Install and log in

```bash
curl -fsSL https://kvbox.cloud/install.sh | bash     # or: npm install -g @kvbox/cli (Node >= 22)
irm https://kvbox.cloud/install.ps1 | iex           # Windows PowerShell
kvbox update                                      # later: upgrade the CLI (reruns the installer; asks on a TTY)
kvbox login                                       # prints a link + code; the user approves it in the web app
kvbox login --password                            # email + password prompt instead (a control plane with no web app)
kvbox login https://cp.example.com                # the user's own control plane
kvbox login -e you@example.com --password-stdin   # scripts
kvbox whoami --json                               # {user, url, sshCertExpires, apiKey} or null (local mode)
```

**API keys** (for a program: CI, an agent, a script). With `KVBOX_TOKEN` set to a key, every command
uses it instead of a login and no `kvbox login` is needed; `KVBOX_URL` names a control plane other
than api.kvbox.sh; `--local` still wins. `connect`, `exec` and `deploy` work under a key.

```bash
kvbox key create ci [--expires 30d|2027-01-31|never] [--json]   # stdout is the key alone (kvb_…), shown once; lives 90 days by default
kvbox key ls [--json]                                     # [{name, createdAt, lastUsedAt, expiresAt}], never the key
kvbox key rm ci -y                                        # whatever uses it is refused at once
```

- A key acts as its user everywhere, except that it cannot make, list or remove keys: the `key`
  commands need a real login, and fail under `KVBOX_TOKEN`. Up to 20 keys per account.
- If you are running under `KVBOX_TOKEN` and get "refused the API key in KVBOX_TOKEN", the key was
  removed or has expired: tell the user, you can't fix it.

A new account is inactive until a payment method is on file or the operator activates it: every
command but login/whoami answers "your account is not active yet". Tell the user; you can't fix it.

## Boxes

```bash
kvbox new dev --json                    # 2 vCPU / 4 GB / 8 GB disk; name defaults to box1, box2, ...
kvbox new dev --size m                  # xs: 1/2GB/8GB, s: 2/4GB/8GB, m: 4/8GB/16GB, l: 8/16GB/32GB
kvbox new dev --from warm               # warm clone from snapshot "warm"
kvbox new dev --auto-hibernate 30m      # hibernate after 30 min with no network traffic
kvbox new dev --location eu             # on a host inside that location: a country (DE, romania) or a region (eu, us); never elsewhere
kvbox ls --json                         # yours and your orgs' boxes; each with `country` (the PLACE column), where it runs
kvbox get dev --json                    # one box in full: Machine + `subdomains?` (its HTTPS names and routes, oldest first)
kvbox rm dev -y                         # disk deleted; snapshots made from it are kept
```

`--json` from `new`, `ls`, `start`, `stop`, ... is the Machine object:
`{id, name, owner, ip, vcpu, memMib, diskBytes, diskUsedBytes, diskHostBytes?, base, image?, createdAt, source, status,
ssh?: {host, port, user}, ports?, ownerKind?, autoHibernateSec?}`. `diskUsedBytes` is what the box uses
of its disk (like `df` inside it); `diskHostBytes` is what its disk file takes on the host, which only
grows while the box runs and comes down at `kvbox stop`. `image` is set for a box not on the
base image (e.g. `postgres`; `base` is then that image's version); `new` adds `connect` for an image that
has one (a `postgres://` URL with the password, shown once).
`status` is `running`, `standby` (paused), `hibernated`, `stopped` or `unknown` (the host did not
answer; it is not a box state). Through a control plane, `ls` answers from what the hosts last
reported: a command you ran shows at once, a change the host made by itself (auto-hibernate, a
crash) within about 30 seconds.

`new`, `start`, `wake` and a `rescale` that grows a running box are refused when the host has no
free RAM for the box (`--force` skips that check). Through the cloud a new box goes on the host with
the most free RAM; an existing box stays on its host.

## Run commands: exec

```bash
kvbox exec dev -- ls /app                         # -- separates the box from the command
kvbox exec dev -- 'cd /app && npm test'           # one string to the box's shell: quote pipes, &&, cd
kvbox exec dev -e API_KEY=xxx -e DEBUG=1 -- env   # env vars (repeatable)
kvbox exec dev --timeout 30 -- ./slow-thing       # killed after 30 s, exit 124
kvbox exec dev --json -- make                     # {"output": "...", "exit_code": N}
kvbox exec dev --tty -- htop                      # interactive tool (needs a real terminal)
```

`exec`'s exit status is the command's, so `kvbox exec dev -- 'test -f /app/ready' && deploy` works.
Stdin is forwarded when it is not a terminal, with its end of file.

**Start a server and come back.** `exec` returns when the command exits *and* nothing it started still
holds its output. Detach the server from both:

```bash
kvbox exec dev -- 'cd /app; setsid -f node server.js > server.log 2>&1 < /dev/null'
kvbox exec dev -- 'curl -s localhost:3000'        # a second exec checks on it
```

Trap: `cd /app && node server.js > server.log 2>&1 &` hangs `exec` forever. The `&` backgrounds the
whole `cd && node` pair as a subshell whose own output is still the session, and `exec` waits on it.
Use `;` or put the redirects on the group: `(cd /app && node server.js) > server.log 2>&1 &`.

`exec` and `connect` resume a paused box and wake a hibernated one on their own; `connect` also
starts a stopped one. `exec` refuses a stopped box: run `kvbox start <box>` first. A visit to a box's
`https://<sub>.kvbox.app` wakes a hibernated or paused box too (at most once a minute, not when out of
credit); a stopped box stays stopped.

## Copy files

`kvbox cp`, scp-style: exactly one side is `<box>:<path>`, a relative box path is under the box user's home.

```bash
kvbox cp data.json dev:/tmp/data.json     # one file in
kvbox cp -r ./src dev:/app                # a directory in (-r)
kvbox cp dev:/app/out.log .               # one file out
kvbox cp -r dev:/app/dist ./dist          # a directory out
```

Like `exec`, it wakes a sleeping box and refuses a stopped one; `--org` and `--direct` work as there. A local
name with a colon is written `./a:b`. Piping through `exec` still works for streams
(`kvbox exec dev -- 'cat /app/out.log' | grep x`; no `--json` or `--tty` when piping bytes).

## Shell: connect

```bash
kvbox connect dev          # interactive SSH shell (short: kvbox cn dev)
kvbox connect dev -- cmd   # one command over SSH with the user's terminal
```

Through the cloud, SSH access is a one-day certificate the CLI renews by itself. `ssh` from
`kvbox ls --json` (`host`, `port`, `user`) works for plain `ssh` too, with the key the CLI keeps.

`kvbox ssh-config` writes a block into `~/.ssh/config` so plain `ssh dev.kvbox`, `scp`, `rsync` and
VS Code Remote-SSH reach the user's boxes (`<box>.kvbox`; an org's box `<box>.<org>.kvbox`). Each
connection goes through kvbox: it renews the certificate and wakes or starts the box. Without a box it lists
every box for VS Code; `kvbox ssh-config dev api` adds only those to the list (any `<box>.kvbox` works with
ssh either way); `--remove dev` takes one off, `--remove` alone takes the block out;
`--json` prints `{file, removed, hosts: [<ssh name>]}`.

## Put a box away

| command | memory | host RAM | comes back with |
| --- | --- | --- | --- |
| `kvbox stop dev` | lost | freed | `kvbox start dev`: fresh boot, a few seconds |
| `kvbox pause dev` | kept in RAM | still used | `kvbox resume dev`: instant |
| `kvbox hibernate dev` | written to disk | freed | `kvbox wake dev`: under a second, processes intact |

Files are kept in all three. `stop` on a hibernated box throws the saved memory away.
`kvbox vm restart dev` stops and boots again in one step (credit and room are checked before the stop;
a boot that fails after it leaves the box stopped, and the error says so); a hibernated box loses its saved memory, a stopped one just starts. Hibernate is
usually what the user wants for "pause it for later". `stop` also gives the host back the disk space
the box freed (its disk file only grows while it runs), so a box with a big disk takes a few seconds
longer to stop.

Auto-hibernate: `kvbox vm set dev --auto-hibernate 4h` (or `off`). Only network traffic counts as
activity, so a CPU-only job with nobody connected looks idle: give it a longer timeout, or `off`.
`kvbox vm set dev --idle-check /home/kvbox/idle.sh` (or `off`): the host asks that script (exit 0 = idle,
runs as root, 10 s) instead of watching traffic; `get --json` has `idleCheck`. Needs base v0.12.0+.
`kvbox vm set dev --swap 2G` (or `off`): a swap file on the box's disk, for a box killed by memory spikes
(`npm install`, `next build` on `xs`) before reaching for a bigger size. Set up inside the box over SSH (wakes a
sleeping box, refuses a stopped one); `--json` adds `swap: {sizeMib, usedMib, zswap}`.

Wake hooks (kvbox.sh only): a URL that wakes a box when called, for GitHub webhooks, cron or any automation.

```bash
kvbox vm hook create ci --json   # {id, owner, box, url, secret, createdBy, createdAt, lastCalledAt}; the secret only here
kvbox vm hook ls ci --json       # the same without `secret`
kvbox vm hook rm ci <id> -y
curl -X POST -H "Authorization: Bearer <secret>" <url>   # or GitHub's X-Hub-Signature-256 (webhook secret = the secret)
```

A call answers 202 `{box, action: "wake"|"resume"|"keep"|"none", reason?}`: wakes a hibernated box, resumes a
paused one, keeps a running one awake for its full auto-hibernate time from the call (`keep`), never starts a
stopped one; at most one call a minute per hook acts; 402 when the slug may not spend.

Backups (kvbox.sh only): the box's disk and its own variables, encrypted, on one of the cloud's backup stores (another host than the box's when there is one). Not
its memory, not its volumes (those have `kvbox volume backup`, below). A running box is frozen for the moment its disk is cloned and keeps running; only what
changed since an earlier backup of the same slug on that store is uploaded. At most 2 backups per box in any 24 hours (failed
ones do not count); past that, `create` fails and says when the next one can start.

```bash
kvbox vm backup create dev --json          # returns at once, status `running`; --wait stays until ready or failed
kvbox vm backup ls --json                  # every box's backups (yours and your orgs'), newest first
kvbox vm backup ls dev --json              # one box's; failed ones with `error`
kvbox vm backup restore dev <id> -y        # the disk becomes the backup's; a running box restarts, a hibernated one is refused;
                                           # only a backup of that same box: a removed box's (`boxRemoved: true`) is refused
kvbox new dev2 --from-backup <id> --json   # a new box on a backup's disk, image, version and variables (a removed box's too);
                                           # its size unless --size (needed for a custom shape; never smaller than its disk);
                                           # waits for the download; not with --base, -e or --from
kvbox vm backup rm dev <id> -y             # delete for good (a removed box's too); a running one is refused; still counts toward the day's 2
kvbox vm backup schedule dev --on --json   # nightly backup of the box: OFF until turned on; BackupSchedule {enabled, hour (UTC), nextAt, lastAt, lastBackup, lastError}
kvbox vm backup schedule dev --at 3        # daily at 03:00 UTC (turns it on); --off stops it (hour kept); alone: shows it
# a nightly backup costs $0.10 a night once ready (a database's is included), outside the 2 a day, listed with `scheduled: true`; the same switch: `kvbox volume backup schedule <volume>`, `kvbox bucket backup schedule`
# a backup is kept 30 days, then deleted on its own
# a backup started by hand costs $1 once ready (box, volume, database, object storage alike); a failed one is free,
# a database's nightly backup is included; refused with 402 when the account has no credit; `kvbox usage` lists them
```

## Snapshots and warm clones

```bash
kvbox snapshots new dev warm --json    # freeze a running box; it keeps running (~1 s pause)
kvbox snapshots new dev warm --replace # retake an existing name; the old one stays until the new one is done
kvbox snapshots ls --json
kvbox new --from warm dev2             # clone: new name and IP, every process where it was
kvbox snapshots rm warm -y             # boxes made from it are not affected
kvbox vm fork dev dev2 --json          # one-step clone, no snapshot left; works on a stopped box too (cold)
kvbox vm fork dev --org acme           # copy into an org: how a box moves between slugs
```

The source box must be running (a fork also takes a stopped one; a hibernated one needs `kvbox wake` first). The pattern: boot a box, install everything, start the services,
snapshot it once, then `kvbox new --from <snap>` for each test run, agent or preview. A clone starts
with no published ports and no HTTPS address.

## Volumes: disks that outlive a box

```bash
kvbox volume create data --size 50GB --box dev --json   # an empty disk made on dev's host and attached: /mnt/data inside dev (a RUNNING box is restarted); {id, name, owner, sizeGib, usedBytes, attachedTo, createdAt}
kvbox volume attach data dev                  # attach again later (after a detach); a RUNNING box is restarted (a few seconds)
kvbox volume ls --json
kvbox volume detach data                      # from the box it is on (or name it: detach data dev); data kept
kvbox volume grow data 100GB --json           # larger, never smaller; a RUNNING box holding it is restarted once; Volume
kvbox volume rm data -y                       # deletes everything on it; must be detached
kvbox volume backup create data --json        # back the volume up like a box (kvbox.sh only): returns at once, status `running`; --wait stays until ready or failed; {id, owner, volume, status, error, diskBytes, dataBytes, uploadedBytes, createdBy, scheduled, createdAt, finishedAt}
kvbox volume backup ls --json                 # every volume's backups; `ls data` for one
kvbox volume backup restore data <id> -y      # the volume's data becomes the backup's; a RUNNING box holding it is restarted once; a hibernated one is refused; Volume
kvbox volume backup rm data <id> -y           # delete a backup for good
kvbox volume backup schedule data --on --json # nightly backup of the volume: off until turned on (--at <hour> UTC, --off; alone: shows it); BackupSchedule
```

- One box at a time per volume; sizes are whole GB (1-4096) and only occupy what is written.
- A volume backup is taken while the box runs (the box writes the volume out and holds writes for the clone, base v0.19.0+, so the filesystem is clean; a database on it still recovers as after a crash, no dump needed). At most 2 per volume in any 24 hours. A box's `vm backup` never includes its volumes.
- A hibernated box refuses attach/detach: `kvbox wake` first.
- Snapshots and forks never carry volumes: a box made from a snapshot comes up with no volume
  attached (the old mount is dropped), attach one if it needs it. Destroying a box keeps its volumes.
- `kvbox get dev` lists a box's volumes with their mount paths.
- A volume lives on one host and attaches only to a box on that host, so on kvbox.sh `--box <box>`
  is required at create: it is made where that box runs and attached to it. Attaching to a box on
  another host is refused (the error names both hosts). With `--local` (one host) `--box` is optional.
- Price on kvbox.sh: $1/month per volume + $0.06/GB/month of its size, by the hour, attached or not.
  A box's own disk: free up to 8 GB, $0.06/GB/month above (`vm rescale --disk` is not free).
  `kvbox usage --json` has them under `volumes` ({id, name, owner, sizeGib, status, volumeHours,
  volumeGibHours, cost?}) and `totals.cost` covers boxes and volumes; with `--by-user` the shape is
  { window, users, volumes?, totals }: volumes are never per user, they are listed as they are.

## Managed Postgres: `kvbox pg`

A PostgreSQL 18 database kvbox runs (kvbox cloud only, not `--local`). No box to manage: it never
shows in `kvbox ls`, and box commands refuse its name. Prefer it over a `--base postgres` box when the
user just wants a database.

```bash
kvbox pg create orders --json                 # only the name is needed; waits until it accepts connections
# Managed + secret {password, urls: {private, public?}} + ready (bool). The one time the password comes unasked.
# options: --database <name> --user <name> --password <pw> --storage <GB, default 10> --near <box> --location <country or region> --from-backup <id>
kvbox pg ls --json                            # Managed[]; `kvbox managed ls --json` lists every kind
kvbox pg info orders --json                   # + health {ready, accepting, version, storageUsedBytes, storageTotalBytes, facts: [{title, value}]} | null (facts: Connections)
kvbox pg password orders --json               # {password, urls}; --reset makes a new one (the old stops working)
kvbox pg link orders api                      # box api reaches it at orders.<slug>.kvbox:5432 (any host; same host is fastest)
kvbox pg unlink orders api
kvbox pg public orders on --json              # open to the internet: public {host, port}, urls.public (…?sslmode=require)
kvbox pg public orders off                    # closed again; `on` later gives the SAME host and port
kvbox pg grow orders 50                       # storage to 50 GB; only grows; a running database restarts once
kvbox pg stop orders ; kvbox pg start orders  # stopped: data kept, only storage is charged
kvbox pg backup create orders --json          # returns at once, status `running`; --wait stays until ready or failed
# ManagedBackup {id, owner, kind, name, version, status, error, diskBytes, dataBytes, uploadedBytes, createdBy, scheduled, createdAt, finishedAt}
kvbox pg backup ls orders --json              # its backups (a removed db's too, by its name); `backup ls` alone: every pg's
kvbox pg backup restore orders <id> -y --json # data becomes the backup's, it restarts, keeps its password; a stopped db is refused (start it); Managed
kvbox pg backup rm orders <id> -y             # delete a backup for good (a removed database's too); same for kvbox redis backup
kvbox pg backup schedule orders --json        # its nightly backup: BackupSchedule {enabled, hour (UTC), nextAt, lastAt, lastBackup, lastError}
kvbox pg backup schedule orders --at 3        # daily at 03:00 UTC (turns it on); --off stops it, --on starts it again
kvbox pg rm orders -y                         # deletes the data (its backups stay)
kvbox pg create shop --from-backup <id> --json # a new database on a backup's data (a removed one's); + fromBackup
```

- Managed: `{kind, name, owner, ownerKind, status, version, settings: {database, user}, storageGib, private:
  {host, port}, public: {host, port} | null, links: [box…], host, createdBy, createdAt, urls:
  {private, public?} (password as ****), price: {perMonth, storagePerMonth, currency}, backupSchedule: BackupSchedule}`.
- Nobody reaches a new database. A box needs a link. A link works across hosts (the two hosts carry it
  over an encrypted tunnel between them, and the database sees the box's own address); for the shortest path create the database with `--near <box>`, or the box with
  `kvbox new <box> --near <database>`.
- Names: 1-12 chars like a box, and a database and a box of one account cannot share a name. The
  database and user default to the name with `-` as `_`; `postgres` is refused as a user. The user
  owns its database, may create more, is never a superuser.
- The public string needs `sslmode=require` (self-signed certificate: do not use `verify-full`).
- Every database is backed up nightly on its own from creation (hour 00-04 UTC; `backup schedule` shows or changes it; skipped
  while the account may not spend). By hand: `kvbox pg backup create`, 2 per 24 h, scheduled ones not counted. Crash-consistent,
  no dump needed; kept 30 days. A restore onto another major version is refused. `create --from-backup` takes the backup's
  database and user (no --database/--user), a new password, and at least the backup's storage; it is refused
  while the backup's own database still exists (use `backup restore`). It waits for the download (up to 2 h).
  An org's backup needs `--org <org>` on `create` (`backup ls` shows the owner then).
- `--org <slug>` works on every command; an org member may read (password included), stop and
  start, and change or remove only what they created.
- About $7.60/month with 10 GB while it runs, $0.06 per further GB, storage only when stopped.

## Managed Redis: `kvbox redis`

A Redis kvbox runs, served by Valkey 9 (Redis protocol; every Redis client works). Same commands and
the same rules as `kvbox pg` (cloud only, hidden box, `--near`, links from a box on any host, `--org`), with these
differences:

```bash
kvbox redis create cache --json               # only the name; options: --password <pw> --storage <GB, default 5> --near <box> --location <country or region>
# Managed (settings: {}) + secret {password, urls: {private, public?}} + ready (bool)
kvbox redis info cache --json                 # health.facts: Clients, Memory ("3.2 MB of 1.5 GB")
kvbox redis link cache api                    # box api reaches redis://default:<pw>@cache.<slug>.kvbox:6379 (plain)
kvbox redis public cache on --json            # urls.public: rediss://default:****@<host>:<port> (TLS only)
kvbox redis password cache --reset --json     # new connections need the new one; open ones stay open
# ls, unlink, public off, grow, stop, start, rm -y, backup create|ls|restore, create --from-backup: as for pg
```

- One login: user `default` with the password. No databases or users to name; no ACL users.
- Two addresses, two schemes: private is plain `redis://` on 6379 (linked boxes only), public is
  `rediss://` (TLS) and refuses a plain connection. The certificate is self-signed: the client must
  skip verification (`redis-cli --tls --insecure`, ioredis/node-redis `tls: {rejectUnauthorized: false}`,
  redis-py `ssl_cert_reqs=None`).
- A box has no `redis-cli`: `sudo apt-get install -y redis-tools`, or use the app's Redis library.
- Memory: about 1.5 GB for data, one size. Full means writes fail (`OOM command not allowed`), keys
  are never evicted: set a TTL on cache keys. Data survives restart and stop/start (append-only file,
  synced every second, on its storage).
- Backups as for pg (`kvbox redis backup …`). About $7.30/month with 5 GB while it runs, storage only when stopped.

## Object storage: `kvbox bucket`

S3-compatible buckets (uploads, images, exports). Cloud only. An account (or an org, `--org`) has ONE
object storage shared by all its buckets: made with the first bucket (about a minute), removed with the
last. No box to manage; it never shows in `kvbox ls`.

```bash
kvbox bucket create uploads --json            # first bucket only: --size <GB, default and minimum 10> --region <ro-west-1…, the S3 region> --near <box> --location <country or region>
# Bucket {name, owner, endpoint, region, keys, createdBy, createdAt} + storage (ObjectStorage) + storageCreated (bool)
kvbox bucket key create uploads --name web --json   # add --read-only for a key that cannot write
# {id (the S3 access key id), name, bucket, readOnly, secret, endpoint, region}: the secret is shown ONLY here
kvbox bucket ls --json                        # Bucket[]
kvbox bucket info uploads --json              # + objects, bytes, storage {sizeGib, usedBytes, totalBytes, price}
kvbox bucket key ls uploads --json            # keys without secrets
kvbox bucket key rm uploads <access-key-id> -y
kvbox bucket public assets on --json          # anyone reads every object at <publicUrl>/<key>; --sub <name> picks the address
kvbox bucket public assets off                # private again, address freed
kvbox bucket grow 50 --json                   # the whole storage to 50 GB (only grows, restarts once)
kvbox bucket rm uploads -y                    # must be empty; the last bucket also removes the storage
kvbox bucket rm uploads --force -y            # the LAST bucket only: with everything in it
kvbox bucket backup create --json             # the WHOLE storage (all buckets + keys): returns at once, status `running`; --wait stays
# {id, owner, status, error, diskBytes, dataBytes, uploadedBytes, buckets: [name], keys, createdBy, scheduled, createdAt, finishedAt}
kvbox bucket backup ls --json                 # its backups, newest first
kvbox bucket backup schedule --on --json      # nightly backup of the whole storage: off until turned on (--at <hour> UTC, --off; alone: shows it); BackupSchedule
kvbox bucket backup restore <id> -y --json    # the whole storage goes back to the backup; it restarts
# {backup, storage, buckets: {kept, returned, removed}, keys: {dropped, revoked}, checked, warnings}
kvbox bucket backup rm <id> -y                # delete a backup for good
```

- Endpoint: the one `kvbox bucket info <name> --json` prints (usually `https://s3-<slug>.kvbox.app`, but a slug
  with `.` or `_` gets a random part; never build it by hand), the storage's own `region` from the same output (kvbox's
  regions, like `de-center-1`; never a guessed one: a wrong region fails every signature), and **path-style addressing is required**:
  AWS SDK for JS `forcePathStyle: true`; boto3 `Config(s3={"addressing_style": "path"})`; AWS CLI
  `aws configure set default.s3.addressing_style path` plus `--endpoint-url <endpoint>` on every command.
- A key opens one bucket (read and write, or read only). Save the secret when it is printed (put it in
  the app's variables: `kvbox env set S3_SECRET <secret> --secret`); a lost secret means a new key.
- A box reaches it at the same HTTPS endpoint as anything else.
- Buckets are private unless made public (`kvbox bucket public <bucket> on`): then every object is read with no
  key at `<publicUrl>/<key>` (`publicUrl` in `bucket info --json`, e.g. `https://assets-<slug>.kvbox.app`; never
  build it by hand), with the Content-Type it was uploaded with, never listed, `index.html` for `/` (static sites),
  any origin may GET. Public is the whole bucket: put public files (site images) in their own bucket. At most 10
  public buckets per account. A 409 `storage-outdated` means the storage needs its newer image. No CORS rules of
  your own (a page of yours cannot upload from the browser: upload through your app's server). The kvbox web app has a Files tab per bucket
  (browse, upload, download, share links, move, delete). Use multipart for large files (SDK upload helpers and `aws s3 cp` do).
- A full storage refuses uploads: `kvbox bucket info` shows used/size, `kvbox bucket grow <GB>` adds room.
- Backups are manual (`kvbox bucket backup create`, 2 per 24 h) and always of the whole storage. While one runs,
  `bucket key create|rm` and `bucket rm` are refused: wait for `bucket backup ls` to show it done. A restore
  REMOVES buckets made since the backup (with their files), brings back buckets removed since (without keys),
  and keys made since STOP WORKING (`keys.dropped`: give the app a new key); keys removed since stay removed.
  Tell the user this before restoring.
- $6/month for the storage with 10 GB, $0.06 per further GB, charged while it exists whatever it holds.

## Container registry: `kvbox registry`

A private place for docker images, at an HTTPS name, behind one login. Cloud only. An account (or an
org, `--org`) has at most ONE; no command takes a name. It never shows in `kvbox ls`.

```bash
kvbox registry create --json                  # a minute or two: --size <GB, default 20> --near <box> --location <country or region>
# Registry {owner, address, user, sizeGib, status, host, price, createdBy, createdAt} + secret {address, user, password} + ready (bool)
kvbox registry info --json                    # + usedBytes, totalBytes, repositories [{name, tags}], version (when it answers)
kvbox registry password --json                # {address, user, password}: the login, any time
kvbox registry password --reset --json        # a NEW password: every docker login and pull secret with the old one stops working
kvbox registry grow 50 --json                 # to 50 GB (only grows, restarts once: pushes fail for a few seconds)
kvbox registry rm -y                          # with every image in it
kvbox registry backup create --wait --json    # every image, encrypted, off its host; RegistryBackup {id, owner, status, error, diskBytes, dataBytes, uploadedBytes, createdBy, scheduled, createdAt, finishedAt}
kvbox registry backup ls --json               # newest first; a removed registry's too (kept 30 days)
kvbox registry backup restore <id> -y --json  # DESTRUCTIVE: {backup, registry, ready}; images pushed since are gone
kvbox registry backup rm <id> -y
kvbox registry backup schedule --on --json    # nightly (--at <hour UTC>, --off; alone: shows it); off until turned on
```

- Log in and push with the `address` from the output (usually `cr-<slug>.kvbox.app`, but never build it by hand):
  `docker login <address> -u kvbox` (password on stdin: `--password-stdin`), `docker tag myapp <address>/myapp:1.0`,
  `docker push <address>/myapp:1.0`. A Kubernetes cluster pulls with an image pull secret made from the same login.
- Seeing the password takes what changing the registry does: an org member sees it only for a registry they made.
- A full registry refuses pushes: `registry info` shows used/size, `registry grow <GB>` adds room. Images are removed
  with docker/OCI tools against the registry; kvbox does not list or delete repositories.
- Names starting `cr-` (like `s3-`) are kvbox's: a box, a cluster or a public bucket cannot claim one.
- Backups: 2 by hand in any 24 hours ($1 each once ready), kept 30 days; the nightly one costs $0.10 a night. A
  restore restarts the registry, keeps its address and its CURRENT password (the login is in no backup), and only
  goes into the registry the backup was taken of: after `registry rm` its backups can no longer be restored.
- $6/month with 20 GB, $0.06 per further GB, charged while it exists whatever it holds.

## Cron: `kvbox cron`

Call a box, or run a command in it, on a schedule. Cloud only. A crontab inside a box is slept through
when the box hibernates; a cron trigger is kept outside the box: when due, kvbox wakes the box if needed
and either sends an HTTP request to a port in it (`--port`) or runs a command in it (`--run`).

```bash
kvbox cron create nightly --json              # a cron service: a named set of triggers (--org for an org's)
# CronService {owner, ownerKind, name, keepRuns, triggers, createdBy, createdAt, price?: {perMonth, currency}}
kvbox cron trigger add nightly api "0 6 * * *" --port 3000 --path /tasks/embed --tz Europe/Bucharest --json
kvbox cron trigger add nightly api "30 2 * * *" --run "node ~/app/cleanup.js" --timeout 30m --json
# CronTrigger {id (ct_…), service, owner, box, expr, timezone, enabled, nextRunAt, lastRunAt, lastOutcome}
#   + {kind: "http", method, port, path}  or  {kind: "command", command, timeoutSec}
kvbox cron trigger run nightly <id>           # fire it now, once (sent within a few seconds)
kvbox cron trigger runs nightly <id> --json   # CronRun[] newest first: {scheduledFor, startedAt, durationMs, status, exitCode, output, outcome, error, woke}
kvbox cron trigger ls nightly --json          # CronTrigger[]
kvbox cron trigger pause|resume nightly <id>
kvbox cron trigger rm nightly <id> -y
kvbox cron ls --json                          # CronService[]
kvbox cron info nightly --json                # the service + triggerList
kvbox cron rm nightly -y                      # the service, its triggers and their runs
```

- Price: $1 a month per cron service while it exists (up to 50 triggers, any number of runs); `cron rm`
  stops it. `kvbox usage --json` lists them under `cron` ({name, owner, status, hours, cost}).
- Expression: five fields in quotes (`minute hour day-of-month month day-of-week`), one minute at the
  least; a sixth (seconds) field is refused. UTC unless `--tz <IANA zone>`.
- The request: `POST` (or `--method GET`) to `<box>:<port><path>`, no body, `user-agent: kvbox-cron/<version>`.
  It comes over kvbox's own network: the port needs no `proxy claim` and no HTTPS address. The box is one
  of the same account's or org's, on any host.
- The app has 55 s to answer (plus the wake). For longer work, answer `202` and carry on in the background.
  Auto-hibernate watches network traffic, not processes: a long silent job can be hibernated half-way.
- A command (`--run "<cmd>"`, instead of `--port`): run as user `kvbox` in its home through a login shell,
  with the box's variables. Stopped after `--timeout` (90s, 10m, 1h; default 10m, at most 1h). One at a time
  per trigger: a slot that comes while the previous command is still going is skipped (`still-running`).
  The box is not auto-hibernated while it runs. Needs a box made from base image v0.15.0 or later
  (else `box-outdated`). `exitCode` is on the run; the output is never sent to kvbox: it is the files
  `output` in the box (`kvbox exec <box> -- cat /var/log/kvbox/runs/cron-<n>.*`, newest 50 cron runs kept).
- `outcome`: `ok` (2xx, or exit code 0), `failed` (another status, nothing listening, or another exit code),
  `timeout`, `no-credit` (not sent), `box-stopped` (not sent: a stopped box is never started), `host-down`,
  `host-outdated`, `running`, `lost` (also: the box restarted or slept before the command ended),
  `still-running`, `box-outdated`. A failed run is not retried; the next slot is.
- Only the status or exit code is kept, never what the app answered or the command printed. The last 100 runs per trigger.
- To change a trigger, remove it and add it again. A removed box takes its triggers with it.
- After `trigger run`, wait about 10 s before reading `trigger runs`.

## Kubernetes: `kvbox k8s`

A Kubernetes cluster (k3s 1.37) kvbox runs. Cloud only, `--org` like boxes. The master is hidden and
kvbox's to run; the nodes are boxes of yours named `<cluster>-<3 hex>` (`kvbox ls` shows them, each
costs what a box of its size costs). A cluster starts on one host; a pool grown later spills onto
other hosts when that one is full.

```bash
kvbox k8s create prod --size m --json         # options: --nodes <1-9, default 2> --near <box> --location <country or region> --no-wait
# waits until the API answers and every node is Ready (a few minutes)
# Cluster: {name, owner, status, version, api: {host, port}, host, country?, pools: [{name, size, nodes, boxes, elsewhere?}],
#           price, health: {ready, ingress, version, nodes: [{name, ready, schedulable, roles, volumes}]}}
kvbox k8s kubeconfig prod > prod.yaml         # stdout is the file alone: the cluster's admin
kubectl --kubeconfig prod.yaml get nodes
kvbox k8s ls --json                           # Cluster[] without health
kvbox k8s info prod --json                    # with health, asked of the cluster now, and room: {s, m, l} more nodes that fit now
kvbox k8s pool add prod --size l --nodes 3 --name big --json   # one more pool (name defaults to the size); waits for the nodes (--no-wait)
kvbox k8s pool ls prod --json                 # [{name, size, nodes, boxes, elsewhere?: [{name, host, country?}]}]
kvbox k8s pool resize prod big --nodes 5      # more nodes; the same number again makes a missing node
kvbox k8s pool resize prod big --nodes 2 -y   # fewer: the newest nodes are drained (pods move away), then removed; waits (--no-wait)
kvbox k8s pool rm prod big -y                 # every node of the pool drained and removed, then the pool
kvbox k8s proxy claim prod app1 --json        # https://app1.kvbox.app → the cluster's Traefik; {cluster, subdomain, url}
kvbox k8s proxy ls prod --json                # [{cluster, subdomain, url}]
kvbox k8s proxy release prod app1 -y
kvbox k8s domain add prod shop.example --json # your own domain → the cluster; prints the DNS records to set
kvbox k8s domain ls prod --json               # [{domain, cluster, status: "pending"|"live", www, url, error, records}]
kvbox k8s domain rm prod shop.example -y
kvbox k8s link prod mydb --json               # every pod may reach a database (kvbox pg / redis) on its own port; {cluster, to, owner, kind, port, host, boxes}
kvbox k8s link prod api --port 8080           # or one port of a box
kvbox k8s links prod --json                   # [{cluster, to, owner, kind: "postgres"|"redis"|"box", port, host}]
kvbox k8s unlink prod mydb -y                 # from every box of the cluster (--port when it reaches several ports of one box)
kvbox k8s backup create prod --wait --json    # what the cluster knows, to the kvbox cloud; {id, owner, kind: "k8s", name, version, status, …, scheduled}
kvbox k8s backup ls prod --json               # its backups, newest first (no name: every cluster's, removed ones' too)
kvbox k8s backup restore prod bk_… -y --json  # {backup, cluster, nodes: {forgotten, restarted}, checked, warnings}
kvbox k8s backup rm prod bk_… -y
kvbox k8s backup schedule prod --json         # nightly from creation; --at <hour UTC> | --off | --on
kvbox k8s start prod                          # master and nodes back up after they stopped (out of credit, a host reboot)
kvbox k8s node restart prod prod-3f2          # one node stopped and booted again; `prod prod` restarts the master
kvbox k8s rotate prod -y --json               # new credentials: every kubeconfig so far stops working; master then nodes restart
kvbox k8s rm prod -y                          # master, nodes and everything in the cluster
```

- Names: 1-8 chars. Node sizes: `s`, `m`, `l` (2/4/8 vCPU, 4/8/16 GB). The host must have room for
  all of it at create, or nothing is made.
- Your pods run on the nodes only; the master runs the API and the system's pods.
- Price: a cluster costs what its boxes cost. `price` on a Cluster is `{perMonth, nodesPerMonth, totalPerMonth,
  currency}`: the master (about $7), its nodes as they are now (each a box of its size), and both. `kvbox usage
  --json` lists it under `clusters` ({id, name, owner, status, hours, master: {…hours, cost}, nodes: [box rows with
  `pool`], cost}); a cluster's master and nodes are never in `boxes`. Out of credit, the whole cluster is hibernated
  with the account's other boxes; after a top-up `kvbox k8s start <cluster>` brings it back.
- Is it healthy: `kvbox k8s info prod --json` has `condition: {state, problems}`. `state` is `ready`, `starting` (a box
  booted under five minutes ago and has not answered), `degraded` (a node or a pool is named), `down` (the master) or
  `unknown` (the master's host does not answer). Each problem is `{what, fix?, node?, pool?}` and `fix` is the command to run:
  `kvbox k8s start` for a stopped or sleeping box, `kvbox k8s node restart <cluster> <node>` for one that runs but does not
  answer or whose state its host cannot tell, `kvbox k8s pool resize` with the same number for a pool short of a node,
  `kubectl delete node <node>` for a node the cluster still lists that is no box of it, `kvbox k8s rm` when no host has
  the master any more. A problem "certificates end on … (in N days)" (Kubernetes' own, a year long, renewed only at a
  restart) has the `node restart` that renews them as its `fix`; it shows from 30 days before. An org's cluster is named `<org>/<cluster>` in them. No `fix`: wait (a box that just booted, a
  node whose box is gone and is leaving its pool, a node on another host that does not answer or that has left:
  nothing can be done to it until that host is back). Nothing repairs a cluster by itself. After a host restarts, the
  cluster's boxes on it come back on their own.
- Ingress is Traefik on the cluster's ports 80 and 443; `local-path` volumes live on a node's own disk.
- Public HTTPS: a cluster has no address until you give it one. Each `kvbox k8s proxy claim` name
  (`https://<name>.kvbox.app`, as many per cluster as a box may have, names are first come first served) and each
  `kvbox k8s domain add` domain (at most 10 domains per account, boxes' included) reaches the cluster's Traefik on
  port 80 with the visitor's host name; an `Ingress` with that `host` picks the app (with the optional `www` record,
  `www.<domain>` arrives under that name: list it as a second host). kvbox ends TLS and makes
  the certificate: write plain-HTTP Ingresses (`ingressClassName: traefik`, no `tls:` block, no cert-manager).
  One cluster can serve many apps: `app1.kvbox.app` → service A, `shop.example` → service B. WebSockets work.
  `kvbox k8s info prod --json` lists them as `addresses`. `kvbox vm proxy` and `kvbox domain` are for boxes
  and do not list or change a cluster's.
- The kubeconfig is made when asked and stored nowhere; treat the file as a secret (it is cluster-admin). It is one
  certificate for everyone who asks, good for a year at most; a saved file that is refused means ask again.
- `kvbox k8s rotate <cluster> -y` when somebody who had the kubeconfig or could connect to a node should no longer have
  the cluster: new certificate authorities and join tokens, the master restarts (API away about a minute), then every
  node together: apps on the cluster are down for a few minutes. Every box must be running (`kvbox k8s start` first). It waits until
  done unless `--no-wait`; a failure names what could not be done and the same command starts over. Then fetch the
  kubeconfig again. Not ended: service account tokens and anything else made inside the cluster. A backup from before
  a rotation is refused at restore. For whoever may remove the cluster.
- A node is a box you open and read like any other: `kvbox connect prod-3f2`, `exec`, `cp`, `vm get`, usage,
  resources, `vm backup` and its nightly switch. `kvbox ls --json` marks it with `cluster: {name, pool}`.
  A node that is down is woken or started by `connect` like any box (`kvbox k8s start prod` brings them all up).
  Everything that would change it is refused with "is a node of cluster prod: change its pool with
  kvbox k8s pool resize …": `rm`, `stop`, `restart`, `pause`, `hibernate`, `rescale`, `vm update`,
  `vm set`, `vm fork`, a snapshot, a backup's restore, variables, `vm proxy` (ports, HTTPS names), domains,
  links (`vm link`, `pg|redis link`), volumes, wake hooks and cron triggers. To take a node away, shrink its pool;
  to restart one, `kvbox k8s node restart prod <node>` (the message names it too).
  What a node already has (a port, link, HTTPS name, domain, wake hook, integration) can still be taken off it.
- Private links: `kvbox k8s link <cluster> <database or box>` links the whole cluster, the master and every node,
  and a node added later is linked by itself. In a pod, connect to `host` from the answer (`mydb.<slug>.kvbox`)
  on `port`; the name resolves inside the cluster. Never `kvbox pg|redis link <db> <cluster>` or
  `kvbox vm link`, which are for boxes and refuse a cluster or a node. Running the same link again repairs it.
  The database's `links` (`kvbox pg info`) and `kvbox vm links` show the cluster once, by its name.
  The owner of what a cluster of another account reaches may take it away too:
  `kvbox k8s unlink <slug>/<cluster> <slug>/<name>` (the refusal of `vm unlink` / `pg unlink` names it).
- Backups: a cluster's backup is what it knows (deployments, services, secrets, config, its list of nodes), taken
  every night on its own from creation and included in its price (`kvbox k8s backup schedule`), and by hand at a
  backup's price (`kvbox k8s backup create`); kept 30 days. Not in it: what pods keep in `local-path` volumes, which
  live on a node's disk. A node's own backup (`kvbox vm backup create <node>`) is never restored into the node
  (refused: it is a node); it only becomes a new box (`kvbox new <name> --from-backup <id>`) to copy data from.
  `restore` is destructive (`-y`) and only into the same, running cluster: everything applied since is gone, the
  API is away for a minute or so while the master restarts, the kubeconfig, addresses and links stay. A node
  removed since the backup is taken out of the cluster's list again (`nodes.forgotten`); a node added since is
  restarted so it joins again (`nodes.restarted`); `warnings` names what you must finish by hand. One restore or
  pool change at a time (409 `cluster-busy`). A removed cluster's backups stay listed (`kvbox k8s backup ls`) but
  cannot make a new cluster yet. Never `kvbox volume backup` or `kvbox pg backup` for a cluster.
- Pools: a pool's size never changes (add another pool); at most 9 nodes each. New nodes go on the
  cluster's host, then, once it is full, on other hosts (same country first, another only when none there has
  room), or are refused with what fits ("room for 2 more `m` nodes"). Nothing to do differently. A node on another
  host joins up to a minute later; `elsewhere` on its pool names it, and `info` / `pool ls` print its country when
  it is not the cluster's (`prod-a41 (DE)`). Capacity, not availability: one master, so with its host down the API
  and the cluster's addresses are down, though pods on other hosts keep running. A cluster made before this keeps
  every node on its own host (refused with that reason when full). One pool change at a time (409 `cluster-busy`).
- Fewer nodes / `pool rm`: a node keeping `local-path` volumes on its own disk is refused with its claims
  (409 `node-has-data`); a drain that does not end (a PodDisruptionBudget, a pod that will not stop) stops
  there, the node left cordoned: the command fails with the reason, and the same command goes on
  (`kubectl uncordon <node>` puts a node you keep back to work).
  `--force -y` removes nodes undrained, their data lost; on a cluster made before k3s image v0.1.2 the master
  cannot take the node out itself, so the command fails naming the `kubectl delete node` to run. A cluster
  keeps at least one node. The work goes on in the control plane whether you wait or not: `kvbox k8s info prod --json` has `operation` while it
  runs and `operationError` when the last change could not finish.
- A new node that has not joined after 5 minutes is removed again (`operationError` says so); the pool
  still wants it: the same `pool resize` tries again.

## Databases: images

```bash
kvbox new db --base postgres -e POSTGRES_PASSWORD=pw -e POSTGRES_USER=app -e POSTGRES_DB=app --json
# Machine + connect: "postgres://app:pw@db.kvbox:5432/app" (password generated when not given;
# a generated one is a secret: keep it from `connect`, `env ls --box` never shows it again)
# `kvbox get db --json` has `url`: the same string, password masked as ****
kvbox new api --near db && kvbox vm link api db --port 5432   # boxes reach each other only through a link
```

- `--base <image>`: `base` (default) or an image the host has; through kvbox.sh the box goes on a host
  that has it, else "no host has image <name>". `vm update` keeps a box on its own image.
- POSTGRES_* are read once, at the box's first boot; changing them later does not change the database.
- A postgres box does not auto-hibernate unless `--auto-hibernate` is given.

## GitHub runners: the gh-runner image

```bash
kvbox new ci --base gh-runner --size m -e GITHUB_URL=https://github.com/<owner>/<repo> -e GITHUB_RUNNER_TOKEN=<t> --json
# Machine + connect: "<GITHUB_URL>/settings/actions/runners"; the runner is online there within a minute
```

- `GITHUB_RUNNER_TOKEN` is the registration token from the repo's (or org's) Settings → Actions → Runners →
  New self-hosted runner: single-use, valid one hour, read once at first boot. Optional: `GITHUB_RUNNER_NAME`
  (default the box name), `GITHUB_RUNNER_LABELS` (default `kvbox`; workflows use `runs-on: [self-hosted, kvbox]`).
- Registration failed (expired token): `kvbox exec ci -- journalctl -u kvbox-gh-runner-init`, then
  `kvbox env set GITHUB_RUNNER_TOKEN <t> --box ci` and restart the box.
- It hibernates 10 min after its last job (its idle check, not network traffic; `vm set --auto-hibernate`
  changes the time); `kvbox vm hook create ci` + a GitHub webhook (event Workflow jobs) wakes it on a queued job.
  Without the hook a queued job waits until GitHub cancels it (24 h): set one up with every runner (`new` prints the two steps).
- `kvbox rm` leaves the runner listed offline on GitHub; never fork a registered runner.

## Android app tests: the android image

```bash
kvbox new phone --base android --size l --json   # Android 14 (Redroid) starts at boot, adb on localhost:5600
kvbox exec phone -- adb devices                  # localhost:5600  device (the first boot pulls ~1 GB, a few minutes)
kvbox cp app.apk phone:app.apk
kvbox exec phone -- adb install -r app.apk
```

- Android runs as a container on the box's own kernel, nothing emulated, so it is fast; no GPU (drawn in
  software), x86_64 only (an APK with ARM-only native libraries does not run), no Google Play services
  (Google sign-in, FCM push, Maps fail).
- Appium (UiAutomator2 driver) runs in the box on port 4723 as a service; capabilities `platformName: Android`,
  `appium:automationName: UiAutomator2`, `appium:udid: localhost:5600`. It has no login: publish 4723 only if
  the tests run outside the box. Java 17, Maven and the Android SDK (`adb`, build-tools) are on PATH.
- `kvbox exec phone -- journalctl -u kvbox-android` when Android does not come up. `REDROID_IMAGE` /
  `REDROID_ARGS` box variables change the Android version or screen, at the next start.
- Boot Android once, install the app, snapshot it: `kvbox new --from <snap>` gives a fresh device in a second.

## Environment variables and secrets

```bash
kvbox env set NODE_ENV production --json       # {owner, name, boxes}: boxes = how many get it at their next start
kvbox env set DATABASE_URL 'postgres://…' --secret   # write-only: never shown again (ls shows (sealed))
kvbox env ls --json                            # [{name, value?, secret, updatedAt}], value absent for a secret
kvbox env rm NODE_ENV OLD_KEY -y                # each on its own: a name not found is reported, exit 1, the rest removed
kvbox env set REGION eu --org acme             # the org's list: every acme box gets it
kvbox env set NODE_ENV staging --box api --json   # one box's own, over the account's: {box, name, running}
kvbox env rm NODE_ENV --box api -y
kvbox env ls --box api --json                  # {box, vars, inherited}: its own, and the owner's it does not override
```

- A list belongs to the account or an org (`--org`); every box of that owner gets all of it. kvbox.sh only.
  `--box <box>` (or `new -e NAME=value`) sets a box's own instead: kept on its host, wins over the
  owner's of the same name, follows the box into snapshots and forks, works with `--local` too.
- A box takes the list when it STARTS (new, start, a restore from a snapshot or fork). A running box
  keeps its old values: `kvbox vm restart <box>` to apply a change. Waking a
  hibernated box does not reload them.
- Inside the box they are in every SSH session (`kvbox exec <box> -- printenv NAME` works) and in
  `/etc/kvbox/env` (systemd EnvironmentFile form; the `kvbox deploy` app reads it and restarts).
- Names: letters, digits, `_`, not starting with a digit; PATH, HOME, USER, SHELL, KVBOX_* refused.
  Values: one line, ≤ 4 KB, literal (no quoting needed). ≤ 100 per owner. Needs base v0.10.0+.

## Integrations: GitHub and Claude Code in a box without a login

```bash
kvbox integration ls --json                    # [{owner, integration, connected, account, status, kind, connectedAt, lastUsedAt, canManage}]
kvbox new web --integration github,claude --json  # a new box with GitHub and Claude Code on; `integrations` in the Machine JSON
kvbox vm set web --integration github --json   # replace a box's list; at once, no restart
kvbox vm set web --integration off             # none
```

- An integration is the user's GitHub account or Claude Code credential (a `claude setup-token` token or an API key), connected ONCE by them in the web app
  (https://app.kvbox.cloud/integrations). You cannot connect or disconnect from the CLI or with an
  API key: when `integration ls` says not connected, ask the user to connect it there.
- Off by default, per box. In a box with it on: `git clone/pull/push` against github.com (SSH-style
  `git@github.com:me/repo` too), `gh`, and a commit name and email, with nothing to set up inside.
  `kvbox-credential --token github` inside the box prints the token for a script. With `claude` on,
  `claude` starts logged in (base v0.18.0+).
- No token is stored in the box: it is fetched per command. Disconnecting stops every box at once;
  a fork, a box from a snapshot or from a backup keeps the source's list (`--integration off` for none); a copy into another slug has none.
- The user's account only, in their own boxes; an org's boxes get only what an owner connected for the org (Claude Code with an API key; GitHub as the kvbox GitHub App an owner installs on a GitHub org, so org boxes push as `kvbox[bot]` and reach only the repositories picked there). Not in managed
  databases or storage, not with `--local`. Needs base v0.17.0+ (`kvbox vm update <box>`).
- Turning it on gives every program in that box the user's GitHub access (or Claude credential): do it only when asked, or
  when the task needs a private repo and the user agreed.

## Publish ports and HTTPS names

```bash
kvbox vm proxy add dev 3000 8080 --json     # random public port on the host: [{box, guestPort, hostPort, proto, address?}]
kvbox vm proxy add dev 9999 --udp
kvbox claim dev myapp --port 3000           # https://myapp.kvbox.app -> box port 3000 (= vm proxy claim)
kvbox vm proxy add dev 8080 --name api      # https://api.myapp.kvbox.app (after claim)
kvbox claim dev blog --port 5173            # a second address for the same box: https://blog.kvbox.app (up to 5)
kvbox vm proxy set-port dev 4000            # point https://myapp.kvbox.app at another port (--sub myapp once the box has several)
kvbox vm proxy ls --json
kvbox vm proxy rm dev 3000 -y               # one raw port
kvbox vm proxy rm dev --name api -y         # one HTTPS name
kvbox vm proxy release dev -y               # give up the subdomain and every name under it (--sub <name> when several)
```

- The server inside the box must listen on `0.0.0.0`, not `127.0.0.1`.
- A box claims up to 5 subdomains, each serving its own port. Names are global and first come,
  first served. On "taken", pick another. With more than one, `set-port`, `release` and `add`/`rm --name`
  need `--sub <name>`; without it they fail and list the box's subdomains.
- The first `--name` under a subdomain waits about a minute for its TLS certificate.
- WebSockets work. Only HTTPS goes under names; raw TCP/UDP stays on `ip:port`.
- While the box is not running, its HTTPS address shows a "box is stopped" page, and its ports
  close. They reopen on the same public ports when it runs again.
- Anyone with the address can reach it. Say so when publishing something private.

## Box to box: names and links

```bash
kvbox new db --near api                     # same host as api: optional, the shortest path for a link
kvbox vm link api db --port 5432            # api may reach db:5432; inside api: db.kvbox:5432
kvbox vm links --json                       # [{from, box, port}]
kvbox vm unlink api db --port 5432 -y
```

- Inside a box, `<name>.kvbox` is the same owner's box; another slug's is `<name>.<slug>.kvbox`
  (resolves only once linked). Base image v0.11.0+.
- Boxes are closed to each other until linked: one port per link, one way, TCP, never public.
- Different hosts: the same command and the same `db.kvbox` name (`db`'s own address); the two hosts are
  joined by an encrypted tunnel, only the linked port crosses it, and `db` sees `api`'s own address.
  A box from before its host had a range of addresses is refused until restarted (`kvbox vm restart`).
  Removing either box removes its links.

## Custom domains

```bash
kvbox domain add example.com dev [--port 3000] --json   # {domain, box, port, status, www, url, error, records: [{type, name, value}]}
kvbox domain ls --json                                  # status "pending" (DNS not pointing here yet, see error) or "live"
kvbox domain rm example.com -y
```

- `--port` defaults to the port of the box's `https://<sub>.kvbox.app` address; without one, give it.
- The user sets `records` at their DNS provider: an A record to the edge, a TXT record `_kvbox.<domain>`
  that proves the domain is theirs (keep it set), plus an optional `CNAME www` (then `www.` serves the same site).
  In a DNS editor the host field takes the name without the zone: `@`, `_kvbox`, `www` for example.com (the CLI prints them so).
  You cannot set them; tell the user exactly what to add. An AAAA record on the name keeps it pending (IPv4 only): it must go. A domain pending for 3 days is removed; add it again once the records are set.
- Checked every minute; `live` once the A record points here and the TXT record is set, certificate on the first visit.
- "claimed by another account": the error names the TXT record; once the user sets it, `domain add` again takes the domain over.
- At most 10 per user or org. Needs `kvbox login` (not `--local`).

## Deploy a site

`kvbox deploy` puts a React app (Vite or Create React App), a Next.js app, a Node server (Express, Fastify,
Koa, NestJS, Hono with `@hono/node-server`; else `--template node`), a project with a `Dockerfile` or a static
site (an `index.html` and nothing to build) on a box with its own HTTPS address.
It makes a box if there is none, builds the app, ships it in and claims the address. Running it
again redeploys: build, ship, done, same box, same URL.

```bash
cd my-react-app
kvbox deploy -y --json           # first run: defaults (box and address named after the directory), writes kvbox.json
kvbox deploy --name site --sub mysite --size xs -y --json   # or say it all
kvbox deploy -y --json           # later runs: no questions, kvbox.json has the answers
```

- The first run on a terminal asks template, box name, address, size and (Next.js, Node) port, each with a default; off
  a terminal it needs `-y` or the flags. Answers go to `kvbox.json` next to `package.json`:
  `{template, name, subdomain, size, dist, port}`. Edit it or pass a flag to change one thing. The box
  is `xs` (React, Node) or `s` (Next.js) and hibernates after an hour without traffic (a visit wakes it);
  `kvbox vm set` changes that.
- React is built here and served by nginx on 80. Next.js ships the source (no node_modules, .next,
  .git) and the box installs, builds and runs it (`npm run start`, systemd unit `kvbox-app`, `PORT=3000`
  or `--port`, log in `journalctl -u kvbox-app`); a deploy then takes a minute or two. `size` defaults to `s`.
- Docker (a `Dockerfile` in the directory) ships the source (no node_modules, .git); the box runs `docker build`
  and one container `kvbox-app` (`--restart unless-stopped`), box port 3000 or `--port` mapped to the Dockerfile's
  `EXPOSE` port (without one the container gets `PORT` and must listen on it). Log: `docker logs kvbox-app`.
  `size` defaults to `s`. A Dockerfile wins over a framework (a Next.js app with one deploys with Docker); on
  `-y` a stderr line names the other match, pass `--template nextjs|node|react` to take it instead. One container
  per box: no compose; `kvbox env` variables do not reach the container yet.
- Static ships the directory as it is (no node_modules, .git, kvbox.json), nginx serves it on 80 like React.
  Detected by an `index.html` at the top and no `build` script in package.json; a site a tool builds into a
  folder is `--template static` with `dist` in kvbox.json set to that folder (only it is shipped).
- Node ships the source (no node_modules, .git), installs, runs `build` only if the script exists,
  then `start` as `kvbox-app` with `PORT=3000`. Needs a `start` script (`dev` is never used). The app
  must listen on `process.env.PORT`; one on another port: `--port 8080` (saved as `port`).
- Next.js, Node and Docker: the deploy waits 30 s for the app to answer on its port; if it never does, it
  fails with the last lines of its log (`journalctl -u kvbox-app`, or `docker logs kvbox-app`): a crash, or the wrong port.
- `--json`: `{box, created, template, url, dist, files, bytes}`. The URL is `https://<sub>.kvbox.app`.
  On a host's own socket (no `kvbox login`, or `--local`) there is no address: no Address question,
  no `subdomain` in `kvbox.json`, and `url` is `http://<box ip>`, reachable from that host only.
- The box is yours, or the `--org` org's (`--org acme`, saved as `"org"` in `kvbox.json`); a bare
  name never takes an org's box here. `--name` to another box drops the saved address (it was the
  old box's); a `subdomain` the box does not have yet is claimed next to its others (refused when the
  box already has 5).
- A failed build deploys nothing. "image too old": the box predates base v0.8.0; `kvbox vm update <box>` or deploy under another `--name`.
- The box is a normal box: `kvbox connect`, `exec`, `stop`, and `--auto-hibernate` all apply; a visitor
  wakes a hibernated one.

### Several services on one box

A `kvbox.json` with `services` deploys a frontend and an API (or more) to one box behind one address.
Write the file yourself at the project's top; there is no detection:

```json
{
  "services": {
    "web": { "template": "react", "dir": "apps/web", "paths": ["/"] },
    "api": { "template": "node",  "dir": "apps/api", "port": 8000, "paths": ["/api"] }
  }
}
```

```bash
kvbox deploy -y --json          # all services; first run fills name, subdomain, size (default s) into the file
kvbox deploy --only api --json  # one service (repeatable)
```

- Service fields: `template` (`react`, `static`, `node`, `nextjs`, `docker`), `dir` (relative to kvbox.json),
  `paths`, `port` (servers only, unique, never 80; default 3000, for docker the Dockerfile's EXPOSE first),
  `context` (docker only: build context holding `dir`, e.g. `"."` for a Dockerfile that copies from the repo
  root; ships it without node_modules, .git, .venv), `dist`, `release`. Unknown fields are refused. Names: lowercase
  letters, digits, `-`; not `app`, `agent`, `init`, `volumes`.
- A docker service runs as `docker run --network host` under the unit `kvbox-<key>`: no port mapping, it must
  listen on `PORT` (= its `port`); box variables are passed at every start; log `journalctl -u kvbox-<key>`.
- nginx on box port 80 routes by path, prefix kept (`/api/users` reaches the API as `/api/users`), WebSocket
  and SSE pass. `react`/`static` need `paths`. One origin: the frontend calls `/api/...`, no CORS.
- In the box: `/srv/app/<key>/`, a server is the systemd unit `kvbox-<key>` (`journalctl -u kvbox-<key>`),
  services reach each other on `127.0.0.1:<port>`. Box variables (`kvbox env set … --box`) are shared by every
  server; to apply a change: `kvbox vm restart <box>` (a box on a base image older than v0.13.0
  also needs `kvbox deploy` after it; the database is never restarted for a variable).
- `release` (node, nextjs, docker; one line, e.g. `"release": "alembic upgrade head"`): run on every deploy after
  the build and before the swap, in the new version (docker: `sh -c` in a container of the new image, entrypoint
  kept) with the box variables and `PORT`. Non-zero: that service's deploy fails (exit 1, the command's last lines),
  nothing replaced, the old version keeps running. It runs while the old version serves, and on every deploy:
  migrations must be safe to rerun and compatible with the old code.
- With a postgres service, every server's unit starts after it and waits up to 60 s for its port at each start
  (cold boot, wake); a database that never answers shows in `journalctl -u kvbox-<key>`.
- All services are built before any is shipped. `--template` and `--port` are refused: say them in the file.
- `--json`: `{box, created, url, services: [{key, template, files, bytes, dist?, port?, release?, paths}]}` (the ones shipped); a postgres entry is `{key, template: "postgres", image, volume, env, port, paths: []}`, listed first.
- A service removed from the file keeps running until stopped in the box
  (`sudo systemctl disable --now kvbox-<key>`). A stack takes over a box that held a single deploy.
- Postgres: `"db": {"template": "postgres", "env": "DATABASE_URL", "image": "postgres:17"}` (no `dir`/`paths`;
  `image` and `env` optional, port 5432). First run (`-y`: volume `<box>-db`, 10 GB) writes
  `"volumes": {"<name>": "10GB"}` and the service's `"volume"`, sets the env var as a box secret
  (`postgres://kvbox:<pw>@127.0.0.1:5432/app`), makes and attaches the volume: **the box restarts once**. Listens on
  127.0.0.1 only; redeploys never restart it unless image/port changed (a new port gets a new URL and one box restart; a box variable of that name holding another value is refused, not overwritten); data at `/mnt/<volume>/<key>`; refuses
  to start without the volume mounted. A volume attached to another box is refused. **`vm backup` and snapshots skip the volume**:
  back it up with `kvbox volume backup create <volume>`, or nightly with `kvbox volume backup schedule <volume> --on` (off until turned on; tell the user). psql: `kvbox exec --tty <box> -- docker exec -it kvbox-db psql -U kvbox app`.

## Locations: where new things go

A location is a country (`DE`, `romania`) or a region: `eu` (the 27 EU member states, not the continent:
GB, CH and NO are outside) or `us`. An account and each org has one default location; none set means any host.
Codes come back as kept: a region in lower case (`eu`), a country in upper case (`DE`); `us` is the
region, `US` the country (the same hosts today).

```bash
kvbox location --json                   # your default: {slug, location: "eu"|"DE"|null, kind?, name?, countries?: [{code, name}]}
kvbox location ls --json                # what has a host now: [{kind: "region"|"country", code, name, countries}]
kvbox location set eu                   # what you make from now on goes only to hosts in the EU
kvbox location set DE --org acme        # an org's default: its owners only
kvbox location unset                    # any host again
kvbox new dev --location us             # this one box elsewhere; the default stays
kvbox pg create orders --location DE    # the same flag on: pg create, redis create, bucket create, registry create, k8s create
```

- A default refuses rather than places elsewhere: with `eu` set, a create with no flag fails when no EU
  host has room. Do not retry it elsewhere on your own; tell the user, or ask before adding `--location`.
- The default decides only where **new** things go (boxes, databases, object storage, the container
  registry, clusters); nothing that exists moves. Check it (`kvbox location`)
  before telling a user where their data will be.
- `--location` on a create wins over the default. With no host inside the location, or none with room,
  the create is refused and the error names the location and where there is room: it is never placed
  elsewhere, with `--force` neither.
- `--near <box>` (every create) and `--from <snapshot>` (`kvbox new`) name the host themselves, so they win over the default; together
  with a `--location` that does not contain that host they are refused.
- The JSON of what was made says where it landed: `country` (`RO`) on a box, a database, the registry and
  a cluster, `storage.country` on a bucket. `kvbox new --country <c>` is the older spelling of `--location <c>`.
- Object storage is one per account: the location counts for the first bucket, which makes it. A later
  bucket goes into that storage wherever it is, and `--location` is refused when it does not contain it.
  `--region` on `bucket create` is the S3 region (`ro-west-1`), another thing: with both, a host must be in
  both or the create is refused.
- What moves by itself stays inside: a backup of a thing made under a location is kept only on a backup
  store inside it, and fails with "no backup store in eu (European Union) has room" (free of charge, never
  sent elsewhere) when none there can take it; `kvbox k8s pool resize|add` grows a cluster only onto hosts
  inside the location it was made under and names it when refused. A volume goes by the box it is attached to.
- Moving a box to another location: `kvbox vm backup create <box> --wait`, `kvbox new <name> --from-backup <id> --location <l>`,
  then `kvbox rm <box>`. A fork, and `kvbox new --from <snapshot>` without `--location`, keep the
  location their source box was made under, and their backups stay inside it.
- Not covered, say so when asked where data is: account data (names, emails, the list of boxes, usage, billing)
  is in the control plane's database, one place for everyone; traffic to `*.kvbox.app` passes through the edge,
  and to a host behind a relay through the relay, either possibly in another country; a host's country is what
  its operator said. Guide: https://kvbox.cloud/docs/guides/locations

## Orgs

```bash
kvbox org new acme --name "Acme Inc"           # you are its owner
kvbox org members add bob --role admin --org acme
kvbox new lab1 --org acme                      # creates acme/lab1
kvbox connect lab1                             # bare name: your box, else the one org box with that name
kvbox connect acme/lab1                        # when two orgs have a lab1 (or --org acme)
kvbox ls --org acme
```

`--org` is per command (before or after it), and nothing is remembered between commands. Without
it, `new` creates a personal box. Members can use any box in the org but remove or rescale only the
ones they created.

## Resize, update, inspect

```bash
kvbox vm rescale dev --vcpu 4 --mem 16GB --disk 32GB   # or --size m; disk only grows; running box restarts
kvbox vm update dev        # move onto the current base image; files kept, running box restarts
                           # a box behind shows `v0.12.0 → v0.16.0` under BASE in ls (`latestBase` in --json)
kvbox vm top --json        # load, memory, disk of each running box as the box sees them
kvbox vm usage dev --json  # hours running/paused/hibernated/stopped, vCPU-h, GiB-h, cost
kvbox vm traffic dev --since 1h --json  # requests by 2xx-5xx, p50/p95, bytes, wakes through its HTTPS names (7 days kept; --host one name; ports/SSH not counted)
kvbox vm resources dev --since 1h --json  # CPU % (average, busiest minute), memory, disk, network bytes over time, measured while it runs (7 days kept; `totals` + `points`; memory/disk null if the box gave no answer)
kvbox usage --json         # this month across your boxes and volumes (--since/--until, --org; --by-user: boxes per maker, volumes as they are)
kvbox credit --json        # prepaid credit left, yours and each org's; `promo` is the part from a code, gone on `promoExpiresAt`; `added`, `welcome`, `transferredIn`, `transferredOut` split `topUps`
kvbox redeem KV-XXXX-XXXX-XXXX   # a promo code into credit that is used first and expires; --org <slug> gives it to an org you own (it cannot be moved later)
```

## From code: the TypeScript SDK

Running kvbox yourself, use the CLI. When the user is writing a program that drives boxes (an agent
harness, a test runner, a preview service in TypeScript/JavaScript), point them at `@kvbox/sdk`
instead of shelling out to `kvbox`: boxes, snapshots, volumes and `exec`, with typed answers and errors.

```ts
import { Kvbox } from "@kvbox/sdk";                 // npm install @kvbox/sdk; Node 22+, Bun, Deno
const kvbox = new Kvbox();                          // KVBOX_TOKEN (an API key), KVBOX_URL
const box = await kvbox.machines.create({ name: "job1", size: "s" });
await kvbox.machines.waitUntilReady(box.name);
const { exitCode, stdout, stderr, timedOut } = await kvbox.machines.exec(box.name, "npm test");
```

`exec` there has no stdin or tty, returns the first MiB of each stream, and needs a box from base
image v0.16.0+ (`BoxOutdatedError` otherwise). `kvbox.integrations.list()` and
`machines.set(name, { integrations: ["github"] })` cover integrations; `machines.traffic(name)` a box's HTTPS traffic, `machines.resources(name)` its CPU, memory, disk and network over time. `kvbox.k8s` covers clusters: `create({name, size, nodes})`, `waitUntilReady(name)`, `kubeconfig(name)` (the file's text), `list`, `get` (with `condition`), `start`, `restartNode(name, node)`, `rotate(name)` (new credentials; then `waitUntilSettled`), `remove`, `pools.add|resize|remove|list` and `waitUntilSettled(name)` after a shrink (throws what it could not do); a cluster's addresses, links and backups are the CLI's. `kvbox.registry` covers the container registry: `create`, `get`, `list`, `password`, `resetPassword`, `grow`, `remove` and `backups.list|get|create|restore|remove|schedule|setSchedule`. Locations: `kvbox.locations.list()` (what has a host now), `kvbox.location.get({org?})` and `kvbox.location.set("eu" | null, {org?})` (the default), and `location` on `machines.create`, `k8s.create` and `registry.create`; an API key obeys the default with nothing sent. Not in the SDK: files, HTTPS names, env, pg/redis,
buckets, cron (the CLI, or `kvbox.request` on the route). Reference: https://kvbox.cloud/docs/reference/typescript-sdk

## Troubleshooting

- **Every box shows `unknown`**: the control plane can't reach the host. Nothing to do on the
  client; tell the user.
- **SSH refused**: the CLI renews the certificate and retries once by itself. If it still fails,
  `kvbox whoami` and log in again.
- **"not active yet"** (account or org): needs a payment method or the operator.
- **No route to the box from the internet**: publish the port (`vm proxy add` or `claim`); a box's
  `ip` is private to its host.
