# guplet API reference

guplet runs isolated Linux microVMs, called **gups**, that your code or your agents create
through a REST API. You can run commands and background processes in a gup, read and write its
files, open its ports as HTTPS URLs, and pause, snapshot or resize it.

## Quickstart

1. **Create an account** at [console.guplet.com](https://console.guplet.com). guplet is in beta,
   so a new account waits for activation before it gets a team.
2. **Add credits** on the console's Usage & billing page. A team without credits can sign in and look
   around, but creating a gup answers `402`.
3. **Create an API key** on the API keys page. The full key is shown only once, so copy it then.
4. **Create a gup and run a command.**

With the CLI, on Linux or macOS (amd64 or arm64):

```bash
curl -fsSL https://guplet.com/install | sh       # installs guplet in ~/.local/bin, no sudo
guplet login --api-key-file /path/to/team-api-key
guplet gup create --os toolbox --size s --ttl 600s --wait
guplet gup exec <id> -- python3 -c 'print(6*7)'
```

Run the same command again to upgrade. `GUPLET_INSTALL_DIR` picks another directory.

With the Python SDK (`pip install guplet-sdk`, Python 3.9 or later):

```python
import guplet

client = guplet.Client()                 # reads the key from GUPLET_TOKEN
with client.create(os="toolbox", size="s", ttl=600) as gup:   # deleted at the end of the block
    gup.wait()                                                 # until the gup is Running
    r = gup.run("python3 -c 'print(6*7)'")
    print(r.stdout, r.exit_code)                               # "42\n" 0
```

With the TypeScript SDK (`npm install guplet-sdk`, Node.js 22 or later, ESM):

```ts
import { Client } from "guplet-sdk";

const client = new Client();             // reads the key from GUPLET_TOKEN
await using gup = await client.create({ os: "toolbox", size: "s", ttl: 600 });
await gup.wait();
const r = await gup.run("python3 -c 'print(6*7)'");
console.log(r.stdout, r.exitCode);       // "42\n" 0
```

`await using` needs TypeScript 5.2 or later, or Node.js 24 in plain JavaScript. On Node.js 22 in
plain JavaScript, call `await gup.kill()` in a `finally` block instead.

With the CLI (Linux and macOS):

```bash
curl -fsSL https://guplet.com/install | sh
guplet login --api-key-file ~/guplet-key.txt
guplet gup create --os toolbox --size s --ttl 10m --wait   # prints the gup, its id first
guplet gup exec <id> -- 'python3 -c "print(6*7)"'
guplet gup delete <id>
```

With plain HTTP:

```bash
export GUPLET_TOKEN=guplet_...           # your API key

curl -s "https://api.guplet.com/v1/gups?wait=true" \
  -H "Authorization: Bearer $GUPLET_TOKEN" -H "Content-Type: application/json" \
  -d '{"os": "toolbox", "size": "s", "ttlSeconds": 600}'
# -> {"id": "…", "phase": "Running", "token": "…", "endpointBase": "https://<port>-….guplet.com", …}

ID=…                                     # the "id" from the answer above

curl -sN "https://api.guplet.com/v1/gups/$ID/exec" \
  -H "Authorization: Bearer $GUPLET_TOKEN" -H "Content-Type: application/json" \
  -d '{"cmd": "echo hello"}'
# -> {"t":"stdout","d":"hello\n"}
#    {"t":"exit","code":0}

curl -s -X DELETE "https://api.guplet.com/v1/gups/$ID" -H "Authorization: Bearer $GUPLET_TOKEN"
```

## Concepts

- **Gup.** One isolated Linux microVM with its own kernel, disk and network. It belongs to a
  team and has an `id`.
- **Image.** What the gup runs, given as `os` on create, for example `ubuntu-24.04` or
  `toolbox`. `toolbox` is meant for agent tool calls: it has Python with numpy, pandas,
  matplotlib and requests, Node.js, git and GCC. You can also build your own image as a
  [template](#templates). `GET /v1/microvm/catalog` lists the images you can use.
- **Size.** vCPUs, memory and disk, given as a named size such as `s`, `m`, `m4` or `l`, or as
  custom values. The catalogue lists the sizes.
- **Launch mode.** `workstation` (the default) boots the image. `fast_spawn` (Pro plan) gives
  you a pre-started gup in well under a second, for the images the catalogue lists in
  `fastSpawnImages`.
- **Lease.** Every gup has a time to live (`ttlSeconds`). When the lease runs out, the gup is
  paused and later deleted. `keepalive` extends the lease.
- **Plan.** A team is on **Developer** (the default, prepaid credits) or **Pro**, which adds Fast
  Spawn, team templates and warm pools (see [Plans](#plans)).
- **Team and roles.** API keys, gups, templates and secrets belong to a team. Team members have
  one of four roles: `viewer < member < admin < owner`. The tables below give the lowest role a
  route needs.

A gup's `phase` is one of `Pending`, `Provisioning`, `Booting`, `Running`, `Pausing`, `Paused`,
`Stopped` and `Failed`. Treat any other value as transitional.

## Authentication

Send your team API key as a bearer token on every request:

```http
Authorization: Bearer guplet_<secret>
```

A key belongs to one team and acts with the admin role in it. Create and revoke keys on the
console's API keys page; the API itself cannot create keys. Keys that start with `shelter_` or
`sbx_`, issued under earlier names, keep working.

Keep the key on your server or in your agent's environment, never in a browser. Browsers cannot
call `api.guplet.com` directly: the API has no CORS policy.

The SDKs read the key from the `api_key` / `apiKey` argument, else `GUPLET_TOKEN`, else the file
named by `GUPLET_API_KEY_FILE`.

## Conventions

- The base URL is `https://api.guplet.com`.
- Requests and responses are JSON (`Content-Type: application/json`) unless a route says
  otherwise. A `204` has no body.
- Timestamps are RFC 3339 strings. Sizes and durations carry their unit in the field name
  (`memoryMiB`, `diskGiB`, `ttlSeconds`).
- Field names are case-sensitive. Most are camelCase; catalogue sizes and a few list records use
  snake_case.
- List routes return a bare array without pagination. Events are the exception.
- An empty list can come back as `null` instead of `[]`; treat both the same.
- URL-encode path segments and query values.
- Commands, logs and process output stream as NDJSON (`application/x-ndjson`): one JSON object
  per line. Network chunks can split a line or hold several, so parse complete lines only.
- Ignore fields, frame types and error codes you do not know. New ones are added without notice
  (see [API versioning](#api-versioning)).
- A feature that is not enabled answers `501`.

## Account and catalogue

| Method and route | Role | Response |
| --- | --- | --- |
| `GET /healthz` | none | Plain text `ok` |
| `GET /v1/me` | any | `{kind, userId, email, team, role, teams}`; `kind` is `apikey` for an API key |
| `GET /v1/microvm/catalog` | viewer | `{os, sizes, gallery, cpuBurstVcpu, fastSpawnImages, teamTemplates, containers}` |
| `GET /v1/locations` | viewer | `{default, locations: [...]}` |
| `GET /v1/limits` | viewer | `{maxActiveGups, activeGups, maxWarmSlots, warmSlots, maxDiskGiB, maxSnapshots, snapshots, snapshotRetentionSeconds, maxKeptGups, keptGups}` |

**Catalogue.** `os` lists the images you can create, including your team's ready templates.
`sizes` maps each size name to `{vcpu, memory_mib, disk_gib}`. `gallery` groups images by
purpose (`id`, `name`, `description`, `packages`, `recommended_size`, `variants`) and by agent
harness. `fastSpawnImages` lists the images that take `launchMode: "fast_spawn"`.
`teamTemplates` lists your team's ready templates (also included in `os`); it is empty or `null`
on the Developer plan. `containers` is `false`: every gup is a microVM. Read these
choices from the API rather than hard-coding them.

`cpuBurstVcpu` is how many vCPUs every gup may use, whatever its size (a size with more keeps
its own). Each size has a CPU floor that is billed whatever the use; CPU used above the floor is
billed by use (see [Billing](#billing)). `0` means burst is off and a gup uses only its size's
vCPUs.

**Locations.** `GET /v1/locations` answers, for example:

```json
{"default": "hel1", "locations": [{"id": "hel1", "name": "Helsinki", "country": "Finland", "kinds": ["container", "microvm"], "available": true}]}
```

`kinds` is what a location's ready nodes take now; a gup can be created where it lists `microvm`.
Pass a location `id` as `location` on create; without it the gup goes to `default`.

**Limits.** `maxActiveGups` is how many gups your team may have running at once (`0` = no limit).
Paused and stopped gups do not count. At the limit, create, start and resume answer `429` with
code `team_limit`. `maxWarmSlots` is your team's warm pool allowance (see
[Warm pools](#warm-pools)).

**Storage limits.** `maxDiskGiB` is the largest disk one gup may have, `maxSnapshots` how many
snapshots your team may keep (`snapshots` is how many it keeps now), and
`snapshotRetentionSeconds` how long an unused snapshot is kept; `0` = no limit, or kept until you
delete it. A create, a restore or a resize to a larger disk, and a snapshot past the count, answer
`403` with code `storage_limit`. Snapshots you already have are never removed when a limit
applies; only new ones are refused. See [Plans](#plans) for the values.

**Kept gups.** `maxKeptGups` is how many paused or stopped gups your team keeps (`keptGups` is how
many it keeps now; `0` = no limit). A paused or stopped gup is free, but it holds its disk and
memory on our servers. When a pause or stop takes your team over the limit, the least recently
paused or stopped gup is deleted within a few minutes, and a notification says why. Running gups,
and gups still pausing, are never deleted. When a Pro or Scale subscription ends, your team keeps
that plan's limit for 7 more days before the lower limit applies. Delete gups you no longer need to
keep the ones you do.
*For now the limit is shown but not enforced: nothing is deleted yet. This changelog will say when
that changes.*

## Create a gup

`POST /v1/gups` (member) creates a gup and answers `201` with the gup.

```json
{
  "os": "ubuntu-24.04",
  "size": "m",
  "ttlSeconds": 3600,
  "env": {"APP_ENV": "development"},
  "metadata": {"workspace-id": "example-workspace"}
}
```

| Field | Type | Meaning |
| --- | --- | --- |
| `os` | string | Required. An image from the catalogue's `os`, or one of your team's ready templates (Pro plan) |
| `size` | string | A catalogue size. Instead of a size, you can give custom resources |
| `vcpu`, `memoryMiB`, `diskGiB` | integers | Custom resources, within server limits |
| `launchMode` | string | `workstation` (default) or `fast_spawn` (Pro plan; `403` `pro_required` on Developer). `fast_spawn` takes only an image in `fastSpawnImages` at a catalogue size without overrides; any other image answers `400`. When no pre-started gup is free, it boots like a workstation |
| `ttlSeconds` | integer | Lease length. Omit it for the platform default |
| `location` | string | A location `id`; the default location when omitted |
| `env` | string map | Environment variables in the guest |
| `metadata` | string map | Your own labels, returned on get and list |
| `sshPublicKeys` | string array | Public keys authorized for SSH (never send a private key) |
| `restoreFrom` | string | Create from one of your team's ready snapshots (see [Snapshots](#snapshots)) |
| `models` | boolean | Give the gup your team's model gateway (see [Model connections](#model-connections)) |
| `secrets` | array | Team secrets as placeholders, for example `[{"name": "gh", "env": "GITHUB_TOKEN"}]` (see [Secrets and egress](#secrets-and-egress)) |
| `egress` | object | `{"allow": ["api.github.com", "*.amazonaws.com"]}` limits outbound traffic to these hosts; `{"allow": []}` allows DNS only |
| `autoResume` | boolean | Default `true`: calls to a paused or stopped gup wake it. `false`: such calls answer `409` |
| `idleTimeoutSeconds` | integer | Pause after this long without use. `0` means never, otherwise at least 60. The default is 900 |

**Wait for it.** `?wait=true&timeout=60` holds the response until the gup is `Running` or
`Failed`, up to the server's limit (60 s by default). `201` means created, not ready: check
`phase` in the response. Without `wait`, poll `GET /v1/gups/{id}`.

**Retry safely.** Send `Idempotency-Key: <a unique string of up to 255 characters>`. Within
24 hours, a repeat with the same key and body returns the first answer, with
`Idempotent-Replayed: true`, instead of creating a second gup. While the first request is still
running, a repeat answers `409` `idempotency_in_progress` with `Retry-After`. The same key with a
different body answers `422` `idempotency_key_reused`. A create that failed does not keep its key.
The SDKs send a key on every create. Without a key, never retry a create that timed out: it may
have succeeded, so list your gups first.

**Size limits.** The body is at most 64 KiB. `env` holds at most 64 variables with POSIX names
and values of at most 4096 bytes, 16 KiB in total. `metadata` holds at most 32 entries; keys match
`^[a-z0-9]([a-z0-9._-]{0,61}[a-z0-9])?$` and values are at most 1024 bytes. Metadata is not
secret.

### The gup object

```json
{
  "id": "v1a2b3",
  "team": "acme",
  "os": "ubuntu-24.04",
  "size": "s",
  "vcpu": 2, "memoryMiB": 2048, "diskGiB": 20,
  "phase": "Running",
  "desiredState": "running",
  "location": "hel1",
  "runningSeconds": 7,
  "createdAt": "2026-09-15T12:00:00Z",
  "expiresAt": "2026-09-15T12:10:00Z",
  "endpointBase": "https://<port>-v1a2b3.guplet.com",
  "ssh": {"host": "22-v1a2b3.guplet.com", "user": "user", "hostKey": "ssh-ed25519 AAAA…"},
  "token": "…",
  "resizable": true,
  "autoResume": true,
  "idleTimeoutSeconds": 900,
  "metadata": {"workspace-id": "example-workspace"}
}
```

`token` is returned only by create (and by token rotation): store it if you need it for
[ports](#ports-and-preview-urls). Optional fields include `message` (why a gup failed),
`launchMode`, `ttlSeconds`, `pausedAt`, `deleteAt`, `expired` (paused by its lease),
`lastActivityAt`, `resize` (see below), `pause` (see below) and `egress`. `kind` is always
`microvm`; you do not need to read it.

## Gup lifecycle

| Method and route | Role | Success |
| --- | --- | --- |
| `GET /v1/gups` | viewer | 200 array of gups |
| `GET /v1/gups/{id}` | viewer | 200 gup |
| `DELETE /v1/gups/{id}` | member | 204; the gup and its disk are removed |
| `POST /v1/gups/{id}/stop` | member | 200 gup; shuts the VM down, keeps its disk |
| `POST /v1/gups/{id}/start` | member | 200 gup; boots a stopped gup |
| `POST /v1/gups/{id}/pause` | member | 202 while pausing, 200 when done; keeps memory and disk |
| `POST /v1/gups/{id}/resume` | member | 200 gup; continues where it paused |
| `POST /v1/gups/{id}/resize` | member | 200 gup; `{"size": "l"}` or `{"vcpu": 2}` |
| `POST /v1/gups/{id}/keepalive` | member | 200 gup; optional `{ttlSeconds}` |
| `PUT /v1/gups/{id}/lifecycle` | member | 200 gup; `{autoResume?, idleTimeoutSeconds?}` |
| `POST /v1/gups/{id}/token` | member | 200 `{token}`; a new port token, the old one stops working |

The lifecycle actions and resize also take `?wait=true&timeout=…`. Check the result either way.

- **Pause** is asynchronous. `pause.frozenAt` means the gup has stopped running and compute
  billing has stopped. `phase: "Paused"` means its state is saved and its memory released.
  Resume, or a snapshot, during an unfinished pause answers `409`. A failed pause answers `500`
  with the gup in the body; `pause.error` says why.
- **Resize** works on a running gup, without a restart. vCPUs can go up or down; memory and disk
  can only grow. Omitted dimensions keep their value. Follow `resize.state`: `Pending`, `Granted`,
  `Applied`, `Refused` or `Failed`. A node without room answers `503` with `Retry-After: 60`.
- **Lease.** `expiresAt` is when the lease ends. The gup is then paused (`expired: true`) and
  deleted at `deleteAt`. `keepalive` extends the lease from now; it does not start or resume the
  gup. A gup paused by its lease comes back only through an explicit `resume`.
- **Wake on use.** Exec, files, terminal, logs, desktop and port requests wait for a gup that is
  starting (up to 60 s). If the gup is paused or stopped and `autoResume` is on, they resume it
  first. A request that arrives while a pause or stop is still in progress waits for it to finish,
  then wakes the gup. A gup that is being deleted answers `404` at once, and `start` or `resume`
  on it answers `409`.
- **Interrupted streams.** When a gup is paused, stopped or deleted, its open exec and logs streams
  end at once with an `interrupted: …` error frame naming the cause (see
  [When exec fails](#when-exec-fails)), and a terminal closes. Background-process output, file
  transfers and port connections are not cut: reopening them would wake the gup again. A wake is billed and limited like a resume (`402` without credits, `429` at the team
  limit). A gup that is still not running after the wait answers `503` `starting` with
  `Retry-After`.
- **Idle pause.** A running gup is paused after `idleTimeoutSeconds` without use. Use means
  exec, files, terminal, logs, desktop, port requests, open sessions and streams, and lifecycle
  calls. Listing or getting gups, metrics, usage, cost, events and the gup's own background
  processes are not use. `lastActivityAt` shows the last use.
- **Delete** cannot be undone. Stop and delete also discard the state of an unfinished pause.

## Run commands

`POST /v1/gups/{id}/exec` (member) runs a command and streams its output.

```json
{"cmd": "pwd && printf 'hello\\n'", "cwd": "/tmp", "env": {"EXAMPLE": "value"}, "timeoutSeconds": 30, "callId": "tool-call-81"}
```

`cmd` is a shell string run with `/bin/sh -c`. `cwd` must exist. `user` is `"root"` or empty (the
gup's normal user). `timeoutSeconds` defaults to 5 minutes; above the server's maximum (1 hour by
default) the request is refused. `"cost": true` adds [cost frames](#cost-of-a-command) to the
stream. `callId` is your own id for this command (at most 255 characters), kept with its
[record](#exec-records).

The response is a `200` NDJSON stream. Its first frame names the exec: `id` is also in the
`X-Exec-Id` response header, so you have it even if the stream breaks before any frame. `since` is
when the command started, the start of its [cost window](#cost-of-a-command): pass it to
`GET /v1/gups/{id}/cost?since=` without waiting for a cost frame. The SDKs keep it as
`result.since` and `stream.since`, and the exact string as `since_raw` / `sinceRaw`.

```jsonl
{"t":"start","id":"ex_0a1b2c3d4e5f60718293","since":"2026-12-01T10:00:00.123456789Z","callId":"tool-call-81"}
{"t":"stdout","d":"/tmp\nhello\n"}
{"t":"stderr","d":"a diagnostic\n"}
{"t":"ping"}
{"t":"exit","code":0}
```

A `200` does not mean the command succeeded: read `code` in the `exit` frame. A stream can end
with `{"t":"error","message":"…"}` instead, and a stream that ends with neither is incomplete.
Closing the connection stops the command. Exec has no stdin; use a
[background process](#background-processes) for that, or for a command that should outlive the
request.

### When exec fails

**An exec refused with one of the codes below never started its command.** Every refusal comes
before the `200`, as a JSON error with `error.code`; after one you can run the command again, here
or on another gup. Anything else may have run: a network error, a `5xx` without our JSON body (a
proxy's own page), or a stream that has begun. Do not repeat those.

Exec wakes a paused gup itself. An exec sent after a pause was asked for waits for the pause to
finish, then wakes the gup and runs: it never answers `busy`, and it costs the time of the pause
plus the wake (about 5 seconds, measured). A command that is already running when the gup is
paused, stopped or deleted is stopped, and its stream ends at once with an error frame that says
why, for example:

```jsonl
{"t":"error","message":"interrupted: the gup was paused (a pause request)"}
```

The cause in parentheses is `a pause request`, `a stop request` or `a delete request` (yours,
through the API, the console, the CLI or an SDK), `its lease ran out`, or `the team ran out of
credits`; without parentheses it is not known. The exec's [record](#exec-records) keeps the same
text as its `error`. So pause a gup only when none of your commands is running on it. Exec does not
answer `410` or `location_unavailable`.

| Status, code | What happened | What to do |
| --- | --- | --- |
| `400` `bad_request` | Invalid body, `timeoutSeconds` above the maximum, or `callId` too long | Fix the request |
| `401` `unauthorized` | Missing, revoked or invalid API key | Check the key |
| `402` `insufficient_credits` | The gup was paused or stopped, and waking it needs credits | Add credits; the gup and its files are intact |
| `403` `forbidden` | Your role is viewer | Use a member's key |
| `404` `not_found` | The gup was deleted or is being deleted, or belongs to another team | Create a new gup |
| `409` `not_running` | The gup is not running and was not woken: paused by its lease (`expired: true`), `autoResume` off, or failed | Read `GET /v1/gups/{id}`: `Paused`, `resume` it; `Stopped`, `start` it (files are kept in both); `Failed`, `message` says why: replace it with a new gup |
| `429` `team_limit` | Waking it would go over your running gups | Pause, stop or delete another gup, or retry after `Retry-After` |
| `429` `rate_limited` | Too many requests | Retry after `Retry-After` |
| `501` `not_enabled`, `agent_unavailable` | `"cost": true` where costs are off; a gup without the in-guest agent | Drop `cost`; recreate the gup |
| `502` `bad_gateway` | The gup did not answer (gups created before the in-guest agent) | Retry |
| `503` `starting`, `unavailable` | The gup took more than 60 s to wake, or a dependency is down | Retry after `Retry-After`; the gup is intact |
| `500` `internal` | Our failure | Read the gup's state, then retry |

Inside the `200`, a stream ends with `exit` (the command finished; `code` is its exit code),
`error` (`timed out after …` at `timeoutSeconds`, `interrupted: …` when the gup stopped running
under it, or a broken session), or neither (the connection broke). In the last two cases the
command ran at least in part.

## Background processes

A background process keeps running after the request that started it. You can come back to its
output, write to its stdin, and stop it. Its output is kept on the gup's disk, up to the newest
64 MiB of each stream.

| Method and route after `/v1/gups/{id}` | Body or query | Success |
| --- | --- | --- |
| `POST /processes` | `{cmd, cwd?, env?, user?: "root", stdin?: bool}`; optional `Idempotency-Key` header | 201 process |
| `GET /processes` | | 200 `{processes: [...]}`, oldest first |
| `GET /processes/{pid}` | | 200 process |
| `GET /processes/{pid}/output` | `stdoutOffset`, `stderrOffset` (bytes, default 0), `follow=1` | 200 NDJSON |
| `POST /processes/{pid}/stdin` | `{data?: string, dataBase64?: string, eof?: bool}` | 204; 409 when stdin is not open |
| `DELETE /processes/{pid}` | `signal=KILL` (default), `TERM`, `INT`, `HUP`, `QUIT`, `USR1` or `USR2`, sent to the process group | 200 process |

A process is `{id, pid, cmd, cwd, state, exitCode?, startedAt, finishedAt?, stdoutSize,
stderrSize, stdoutStart, stderrStart, stdinOpen}`. `state` is `running`, `exited`, `killed` (by a
signal sent through the API) or `lost` (it was running when the gup's agent restarted).
`exitCode` is 128 + the signal number for a process killed by a signal. `stdoutSize` is the next
offset; `stdoutStart` is the oldest offset still kept. The last 100 finished processes are kept,
for at most 7 days.

Output frames are `{"t": "stdout"|"stderr", "d": text, "o": offset, "n": bytes}`, `{"t": "ping"}`
while waiting, and, with `follow=1`, a final `{"t": "exit", "process": {...}}`. Without `follow`
the stream ends once it has caught up.

- **Reconnect** with `stdoutOffset = o + n` of the last stdout frame (likewise for stderr). You
  get no gap and no repeat.
- **Dropped bytes.** If a frame's `o` is past the offset you asked for, the bytes in between were
  dropped by the 64 MiB cap.
- A process alone does not keep a gup from its idle pause; following its output does.

## Files

Every file route takes the file's path as the `path` query parameter: absolute, or relative to
the gup user's working directory.

| Method and route after `/v1/gups/{id}` | Extra query or body | Success |
| --- | --- | --- |
| `GET /files` | `path`; optional `Range: bytes=a-b`, `bytes=a-` or `bytes=-n` | 200 raw bytes; 206 for a range; 416 past the end |
| `PUT /files` | `path`, optional octal `mode`; raw bytes as the body | 201 `{path, bytesWritten}` |
| `DELETE /files` | `path`, optional `recursive=1` | 204 |
| `GET /files/list` | `path` | 200 `{entries: [...]}` |
| `GET /files/stat` | `path` | 200 entry |
| `POST /files/mkdir` | `path`, optional `parents=1` and octal `mode` | 201, empty body |
| `POST /files/rename` | body `{from, to}`; replaces the target and creates its parents | 200 `{from, to}` |
| `POST /files/uploads` | `path`, optional octal `mode` | 201 `{uploadId, path, partSize, received}` |
| `PUT /files/uploads/{uploadId}` | `path`, `offset`; raw bytes, at most `partSize` | 200 `{…, received}` |
| `GET /files/uploads/{uploadId}` | `path` | 200 `{…, received}`; 404 once completed or aborted |
| `POST /files/uploads/{uploadId}/complete` | `path`, optional `sha256` (hex) | 201 `{path, bytesWritten}`; 422 `checksum_mismatch` |
| `DELETE /files/uploads/{uploadId}` | `path` | 204; aborts the upload |

An entry is `{name, path, size, mode, mtime, isDir, isSymlink}`; `mode` is a string such as
`0644`. Uploads are raw bytes, not multipart or base64.

**Large files.** A single `PUT /files` body is cut at 100 MB on the way in. Upload anything larger
in parts:

1. `POST /files/uploads` to start.
2. `PUT` each part at its `offset`, at most `partSize` (16 MiB) each. After a dropped connection,
   `GET` the upload, read `received` and continue from there. Sending a part again is safe.
   An offset past `received` answers `409` `upload_offset`; a part over `partSize` answers `413`.
3. `POST …/complete`, with the file's `sha256` to have it checked.

Parts go to a hidden temporary file next to the target, which completion renames into place.
Every call names the target `path` again. Downloads have no size cap; resume one with `Range`.
The SDKs' `upload` and `download` do all of this for you.

## Logs and terminal

**Logs.** `GET /v1/gups/{id}/logs` (member) streams the gup's system journal as NDJSON frames
`{"t": "log", "d": "…", "ts"?, "level"?, "unit"?}`, with `ping`, `exit` and `error` frames. Query
parameters: `follow` (keep streaming), `tail` (default 100 lines), `since` (RFC 3339 or a duration
such as `10m`), `level` (a journald level) and `search` (a substring).

**Terminal.** `GET /v1/gups/{id}/terminal?cols=80&rows=24` (member) is a WebSocket upgrade, not a
JSON request. Send the `Authorization` header on the upgrade.

- Binary frames, both ways, carry the terminal's raw bytes.
- Send `{"t":"resize","cols":120,"rows":30}` as a text frame to resize.
- The server sends `{"t":"exit","code":0}` as a text frame, then closes.

## Ports and preview URLs

Any port a program listens on inside the gup is reachable over HTTPS. Take the gup's
`endpointBase`, for example `https://<port>-v1a2b3.guplet.com`, and replace `<port>` with the
port number. HTTP and WebSockets both work.

Authenticate in one of these ways:

- the gup's port token in an `X-Gup-Token: <token>` header;
- `?token=<token>` on the first browser visit, which then sets an HttpOnly cookie;
- your API key as `Authorization: Bearer …`.

The port token is returned by create. `POST /v1/gups/{id}/token` issues a new one; the old token
then stops working for new connections. Do not log tokens or put them in analytics.

## SSH

Nothing listens on a public port 22. SSH runs as raw TCP inside a WebSocket to
`wss://22-<id>.guplet.com/`, authenticated like any [port](#ports-and-preview-urls). Use a client
that carries raw TCP over binary WebSocket frames as your `ssh` `ProxyCommand`.

Two ways to log in:

- **Certificate (no key to manage).** Send a public key you just generated to
  `POST /v1/gups/{id}/ssh-cert` (member) as `{publicKey}`. The answer is `201 {certificate, user,
  host, hostKey?, keyId, validBefore}`: a certificate for that one gup, valid 24 hours. Connect as
  `user@<id>` with the key and the certificate, and pin `hostKey` in your known hosts. Keep the
  private key on your side.
- **Your own key.** Pass `sshPublicKeys` on create and authenticate the WebSocket with the gup's
  port token.

## Snapshots

| Method and route | Role | Body | Success |
| --- | --- | --- | --- |
| `POST /v1/gups/{id}/snapshots` | member | Optional `{name, includeMemory}` | 201 snapshot |
| `GET /v1/gups/{id}/snapshots` | viewer | | 200 array of snapshots |
| `DELETE /v1/snapshots/{name}` | member | | 204 |

A snapshot is `{name, gupId, includeMemory, ready, message?, createdAt, lastUsedAt, deleteAt?}`. Creating one is
asynchronous: poll the list until `ready` is true. To restore, create a new gup with
`"restoreFrom": "<name>"` and no size or resource fields: the gup gets the snapshot's resources.
A restore takes no `location`. With `includeMemory`, the restored gup continues with its programs
running.

**Retention and limits.** A snapshot you have not restored for 14 days is deleted. Restoring it
into a gup restarts the 14 days; `lastUsedAt` is the last restore (or the creation) and
`deleteAt` the deletion. A console notification warns 24 hours before. Your plan sets how many
snapshots your team may keep ([Plans](#plans)); past it, a new snapshot answers `403`
`storage_limit` until you delete one. Snapshots outlive the gup they were taken from.

## Desktop

Images with a desktop (their names start with `desktop-`, and a few purpose-built ones) can show
it in a browser.

| Method and route | Role | Success |
| --- | --- | --- |
| `GET /v1/gups/{id}/desktop` | viewer | 200 `{available, running, streaming}` |
| `POST /v1/gups/{id}/desktop` | member | 200 the same status; starts the desktop |
| `DELETE /v1/gups/{id}/desktop` | member | 204; stops the desktop and its stream |
| `POST /v1/gups/{id}/desktop/stream` | member | 200 `{url, expiresAt}`; optional `{ttlSeconds}` |
| `DELETE /v1/gups/{id}/desktop/stream` | member | 204; stops the stream |

The stream URL is a signed, expiring noVNC page for that gup; ask for a new one when it expires.
It starts the desktop if needed. `view_only=true` is a noVNC display setting, not a permission. An
image without a desktop answers `409`.

The Python SDK adds screenshots, clicks and typing on top of exec (`gup.desktop`).

## Templates

A template is your own image, built from a Dockerfile that starts from a catalogue image. Once
it is ready, its name works as `os` on create. Templates need the Pro plan: on Developer, a build
answers `403` `forbidden` and a create from a template answers `403` `pro_required`. Listing, getting and
deleting templates work on either plan.

| Method and route | Role | Contract |
| --- | --- | --- |
| `POST /v1/templates` | member | Multipart `name`, `dockerfile` (text or file), optional `context` (tar.gz) -> 202 template |
| `GET /v1/templates` | viewer | 200 array of templates, without build logs |
| `GET /v1/templates/{name}` | viewer | 200 template with its build `log` and `goldens` |
| `DELETE /v1/templates/{name}` | member | 204; 409 while a gup created from it exists |

A template is `{name, base, status, log?, goldens?, createdAt, updatedAt}`; `status` is
`building`, `ready` or `failed`. Poll until it is `ready`. Too many builds answer `429`, and a
busy builder `503` with `Retry-After: 60`.

The first gup of a template at a named size boots from disk and records a memory image of the
booted gup (a golden). Later gups of that template and size start from it, in about 2 s instead
of 7 to 9 s. `goldens` lists them as `{size, status, message?}`. Custom sizes always boot from
disk.

## Model connections

Connect an OpenAI-compatible model endpoint once, then give gups access to it without handing
them your provider key.

| Method and route | Role | Contract |
| --- | --- | --- |
| `POST /v1/models` | admin | `{name, baseUrl, model, apiKey}` -> 201 model |
| `GET /v1/models` | viewer | 200 array of models; stored keys are never returned |
| `DELETE /v1/models/{name}` | admin | 204 |

A model is `{name, baseUrl, model, modelId, keyPrefix, checkedAt?, checkOk?, checkMessage?,
createdBy?, createdAt}`. Create a gup with `"models": true` and it gets `OPENAI_BASE_URL`,
`OPENAI_API_KEY`, `OPENAI_MODEL` and `SBX_MODELS` in its environment, pointing at a gateway with
a key scoped to that gup. Do not set those names in `env` yourself. A team with no model answers
`409`.

## Secrets and egress

A gup never holds your secrets. Its environment carries a placeholder such as
`guplet.secret.gh.ph`; a proxy outside the gup swaps in the real value only on requests to the
hosts the secret is bound to, and only in the place you declared. It can also sign AWS SigV4
requests. A placeholder sent anywhere else is refused with `403`.

| Method and route | Role | Contract |
| --- | --- | --- |
| `PUT /v1/secrets/{name}` | admin | The whole secret -> 201 (new) or 200 (replaced); the value is always required |
| `GET /v1/secrets` | viewer | 200 array of secrets, never with values |
| `DELETE /v1/secrets/{name}` | admin | 204; running gups stop using it within 30 s |
| `PUT /v1/gups/{id}/egress` | member | `{"allow": [...]}` replaces the gup's allow-list -> 200 gup |
| `DELETE /v1/gups/{id}/egress` | member | Removes the allow-list; secrets stay -> 200 gup |
| `GET /v1/gups/{id}/egress/audit?hours=N` | viewer | Counts per minute (default 24 h, or `?since=<RFC 3339>`) |

A static secret:

```json
{"type": "static", "value": "ghp_…", "hosts": ["api.github.com"],
 "placement": {"in": "header", "name": "Authorization"}}
```

`placement.in` is `header`, `query` or `path`; the default is the `Authorization` header, with
Basic credentials decoded. An AWS secret:

```json
{"type": "aws_sigv4", "aws": {"accessKeyId": "…", "secretAccessKey": "…", "sessionToken": "…"},
 "hosts": ["*.amazonaws.com"], "regions": ["eu-west-1"], "services": ["s3"]}
```

`sessionToken`, `regions` and `services` are optional. Hosts are lower-case DNS names, optionally
with one leading `*.`; IP addresses are not accepted.

Use a secret in a gup with `"secrets": [{"name": "gh", "env": "GITHUB_TOKEN"}]` on create (no
`env` for an `aws_sigv4` secret). The gup also gets `SSL_CERT_FILE`, `REQUESTS_CA_BUNDLE`,
`NODE_EXTRA_CA_CERTS`, `AWS_CA_BUNDLE` and `CURL_CA_BUNDLE` so that its tools trust the proxy;
setting one of these in `env` answers `400`.

**Egress allow-list.** `"egress": {"allow": [...]}` on create, or `PUT /egress` later, limits the
gup to those hosts on ports 80 and 443, plus DNS. `{"allow": []}` allows DNS only.

A secret is `{name, type, version, hosts, placement?, regions?, services?, placeholder, createdBy?,
createdAt, updatedAt}`. The gup shows `egress: {restricted, allow?, platformAllow?, secrets?, state,
message?}`, where `state` is `Enforced`, `Pending` (applied once the gup runs) or `Failed`. An audit
row is `{minute, kind, secret?, host, count}`, with `kind` one of `secret_used`, `secret_refused`
and `egress_denied`.

## Warm pools

On the Pro plan, a team can keep pre-started gups of a Fast Spawn image at a named size, so its
`fast_spawn` creates of that image and size start in well under a second. Each idle slot is billed
at the rate of a waiting gup of that size (its memory and CPU floor) until a create takes it; the
pool then refills. A `fast_spawn` create takes your team's slots first, then the platform's shared
ones.

| Method and route | Role | Contract |
| --- | --- | --- |
| `GET /v1/warm-pools` | viewer | 200 array of pools |
| `PUT /v1/warm-pools/{image}/{size}` | admin | `{count, location?}` -> 200 pool |
| `DELETE /v1/warm-pools/{image}/{size}` | admin | 204; its idle slots go within seconds |

`PUT` answers `400` for a custom size, `402` without credits, `403` `pro_required` without the Pro or
Scale plan or for an image that is not a Fast Spawn image, and `409` `warm_pool_limit` above your
allowance (`maxWarmSlots` in `GET /v1/limits`: 10 slots on Scale; ask us for an allowance on Pro).

A pool is `{template, size, count, ready, location?, ratePerHour, costPerHour, status, message?}`.
`ready` slots can be taken now; `ratePerHour` is one idle slot and `costPerHour` the whole pool.
`status` is `ready`, `filling` or `limited`, with `message` saying why. Without credits, a pool is
emptied and refills once the balance is positive again. To use a slot, create with
`launchMode: "fast_spawn"` and the pool's image and size.

## Metrics, events and usage

All routes here need the viewer role.

**Metrics.** `GET /v1/gups/{id}/metrics?window=15m&step=15s`:

```ts
type Metrics = {
  id: string; kind: string; source: string; window: string; step: string;
  current: null | {
    at: string; cpuCores: number | null; cpuLimitCores: number | null; cpuFloorCores?: number;
    memUsedBytes: number | null; memLimitBytes: number | null;
    diskUsedBytes: number | null; diskLimitBytes: number | null;
  };
  series: Array<{ t: string; cpuCores: number | null; memUsedBytes: number | null; diskUsedBytes: number | null }>;
};
```

`window` defaults to 15 minutes (24 hours at most) and `step` to 15 seconds (5 at least). `null`
means unknown, not zero. Values are measured from the host, so memory and disk are not what
`free` or `df` report inside the gup. `cpuLimitCores` is what the gup may use; `cpuFloorCores` is
what is billed whatever the use.

**Events.** `GET /v1/events?limit=50&before=<id>&gup=<gup id>` returns
`{events: [{id, gupId?, kind?, type, severity, message, actor?, createdAt}]}`, newest first, 1 to
200 per page (default 50). Page back with `before` set to the oldest id; fetch new events with
`after` set to the newest. Ids are numeric cursors.

**Usage.** `GET /v1/usage?from=<RFC 3339>&to=<RFC 3339>` (default: the last 30 days; `YYYY-MM-DD`
also works):

```ts
type Usage = {
  team: string; from: string; to: string; runningSeconds: number; cost: number;
  cpuSeconds: number; burstCpuSeconds: number; warmSeconds: number; warmCost: number;
  days: Array<{ day: string; runningSeconds: number }>;
  gups: Array<{
    id: string; kind: string; tier: string; runningSeconds: number; cost: number;
    cpuSeconds: number; burstCpuSeconds: number; firstStartedAt: string; lastEndedAt?: string;
  }>;
};
```

`cpuSeconds` is the CPU measured (vCPU-seconds) and `burstCpuSeconds` the part billed above the
floor. Idle warm pool slots appear as rows of kind `warm` with id `warm-<gup id>`. Team usage
includes deleted gups. `GET /v1/gups/{id}/usage` takes the same window and returns `{id, from, to,
runningSeconds, cost, cpuSeconds, burstCpuSeconds}` for a gup that still exists.

### Cost of a command

To price a tool call, or to cut it off when your own user runs out of credits, ask exec for the
gup's cost with `"cost": true`. The stream then carries, about every 15 seconds and once more
just before the `exit` frame, what the gup has cost since the command began:

```jsonl
{"t":"cost","since":"2026-12-01T10:00:00.123456789Z","at":"2026-12-01T10:00:15.2Z","runningSeconds":15.08,"cost":0.000071206,"burstCpuSeconds":0,"through":"2026-12-01T10:00:09Z","final":false}
```

```ts
type Cost = {
  since: string;            // when the window began: the command's start
  until?: string;           // when the gup stopped running; absent while it runs
  at: string;               // when this figure was computed
  runningSeconds: number;
  cost: number;             // USD, to the nano-dollar
  burstCpuSeconds: number;  // vCPU-seconds billed above the gup's sold vCPUs, counted up to `through`
  through: string;
  final: boolean;           // the gup stopped and the figure will not change
};
```

- **What it counts.** Everything the gup is billed from `since` until it stops running: memory and
  its vCPUs per second, plus CPU used above them. It is what the gup costs, not what one command
  used, so give each of your users their own gup. Two commands running at once on one gup each
  report the whole gup's cost.
- **How fresh it is.** The time-based part is exact to the second. CPU above the sold vCPUs is
  counted up to `through`, about 15 seconds behind while the gup runs. The figure never counts
  more than the bill.
- **Cutting a command off.** Close the stream: the command stops.
- **Charging your user.** Windows that start at different commands overlap: the window of the
  first command also holds the second, so do not add up followed windows. Per call, charge the
  exec's `call` cost from its [record](#exec-records) (or its last cost frame). To also charge the time between calls, follow one window per
  session (no `since`, or the first command's) and debit the difference between frames.
- **Until the gup stops.** A gup keeps costing after the command ends. `GET /v1/gups/{id}/cost?since=<since>`
  returns the same `Cost` object for that window, and `&follow=1` streams it as `cost` frames
  until the gup stops and the figure is `final`, 60 to 90 seconds after the stop. A follow ends
  after an hour; reconnect with the same `since`. Without `since`, the window starts when the gup
  last started running.
- **When the window ends.** It ends when the gup stops running: a pause (an idle pause included),
  a stop or a delete. A later resume starts a new window. A resize does not end it.
- Cost frames on exec also carry `"exec"`: the exec's id.
- Following a gup's cost does not count as use: it neither keeps a gup from its idle pause nor
  wakes a paused one. A deleted gup's cost stays readable.
- `404` when the gup never ran in your team, `409` when it was not running at `since`, `400` for
  a `since` in the future.

### Exec records

Every exec is recorded for 30 days: when it ran, how it ended and what it cost. Find one by the
`id` of its `start` frame, or all of yours sent with a `callId`:

| Method and route | Role | Success |
| --- | --- | --- |
| `GET /v1/execs/{id}` | viewer | 200 exec |
| `GET /v1/execs?callId=<callId>` | viewer | 200 `{execs: [...]}`, newest first, at most 20 |

```ts
type Exec = {
  id: string; gupId: string; callId?: string;
  startedAt: string;
  endedAt?: string;      // absent while it runs
  exitCode?: number;     // absent while it runs, or when the stream ended with an error
  error?: string;        // the stream's error, e.g. "timed out after 5m0s"
  cost: {
    call: Cost | null;       // from the start to the exit: what this command cost
    untilStop: Cost | null;  // from the start until the gup stops, as GET …/cost?since=
  };
};
```

- **`call`** is the cost to charge for the command. While it runs it grows to now; after the exit
  it is `final` once the CPU around the exit is settled (about 2 minutes later).
- **`untilStop`** also counts the time after the command until the gup stops: what one user's
  gup cost since that command, including idle time.
- A command cut off has no `exitCode`: its `error` is the stream's (`timed out after …`), or
  `cancelled: the client closed the stream` when you closed it. Its `call` cost runs to that
  moment.
- A record without `endedAt` after its stream ended lost its end to a restart of our API: its
  `call` cost then runs until the gup stops. Charge the stream's last cost frame instead.
- Only the command's metadata is kept: no command text, output or environment.
- `404` for an id that is not your team's or older than 30 days. A record of a deleted gup stays
  readable. Reading records does not count as use of the gup.

## Billing

guplet is prepaid. Buy credits, or subscribe to the Pro plan, on the console's Usage & billing page.

### Plans

| | Developer | Pro | Scale |
| --- | --- | --- | --- |
| Price | No subscription; prepaid credits | $20 per month, which includes $20 of compute each month | $150 per month, which includes $150 of compute each month |
| Running gups at once | 5 | 100, subject to available capacity | 300, subject to available capacity |
| Paused or stopped gups kept | 10 | 50 | 200 |
| Largest disk per gup | 40 GiB (sizes `s`, `m`, `m4`) | 80 GiB (also size `l`) | 80 GiB |
| Snapshots kept | 10 | 50 | 200 |
| Snapshot retention | 14 days after the last use | 14 days after the last use | 14 days after the last use |
| Own warm pool slots | None | None | 10 |
| Workstation launch | Yes | Yes | Yes |
| Fast Spawn, team templates, warm pools | No: `403` `pro_required` (a template build: `403` `forbidden`) | Yes | Yes |
| How to get it | Every new team | Subscribe on the console's Usage & billing page | Subscribe on the console's Usage & billing page |

Upgrading from Pro to Scale cancels Pro at once; Stripe credits its unused days to your next
invoice. To leave Pro or Scale, cancel in the billing portal ("Manage subscription"): the plan runs
to the end of the month you paid for, then your team is on Developer.

Compute costs the same on every plan. On Pro and Scale, the month's included compute is used first,
then your prepaid credits; on Scale it also pays for your warm pool slots while they wait. Unused
included compute does not carry over. `GET /v1/billing` shows your `plan` (`developer`, `pro` or
`scale`), `hostedLimit` and `hostedConcurrency` (the running gups that count against it), and the
`allowance` left this month.

### Balance and prices

Create, start, resume, resize, template builds and wakes answer `402` once the balance is used
up, and running gups of a team without credits are stopped.

**Automatic top-up.** A team admin can save a card on the console's Usage & billing page: when the
balance falls below a threshold, the card is charged a chosen amount (whole dollars, $5 to $1,000;
at most 3 times in 24 hours; two declines in a row pause it until a new card is saved). `GET
/v1/billing/auto-top-up` (viewer) returns `{enabled, thresholdCents, amountCents, card, paused,
declines, lastError?, minCents, maxCents, maxPerDay, charges[]}`. Changing it is console-only.

`GET /v1/billing` (viewer) shows the balance and the price list:

```ts
type Billing = {
  team: string; currency: string; balance: number; granted: number; charged: number;
  plan?: "developer" | "pro"; hostedConcurrency?: number; hostedLimit?: number;
  availableBalance?: number;
  allowance?: { amount: number; used: number; remaining: number; endsAt: string };
  ledger: Array<{ amount: number; reason: string; createdBy?: string; createdAt: string }>;
  pricing: Array<{ tier: string; vcpu: number; memoryMiB: number; ratePerHour: number; cpuFloor?: number }>;
  metered?: { vcpuRatePerHour: number; gibRatePerHour: number; cpuFloorPerVcpu: number; through: string | null };
};
```

Prices are in USD per running hour, charged by the second. A running gup pays its size's
`ratePerHour`: its memory at `gibRatePerHour` plus `cpuFloor` vCPUs at `vcpuRatePerHour`. CPU used
above the floor is added at `vcpuRatePerHour`, measured every 15 seconds. `through` is how far CPU
use has been charged to the balance (about a minute behind). A paused or stopped gup is not
charged, nor are snapshots; charging stops at `pause.frozenAt`. `balance` is the prepaid credit;
`availableBalance` adds what is left of the Pro plan's allowance.

## Team members and invites

A team works like an organisation: owners and admins invite people, who then use the console
with their own login.

| Method and route | Role | Contract |
| --- | --- | --- |
| `POST /v1/invites` | admin | `{role}` (default `member`; only an owner can invite an `owner`) -> 201 `{id, token, path, role, expiresAt}`; the token is shown once, `path` is `/invite/<token>` |
| `GET /v1/invites` | admin | 200 pending invites, without tokens |
| `DELETE /v1/invites/{id}` | admin | 204; revokes the link |

Send `https://console.guplet.com/invite/<token>` to the person you invite. A link works once and
expires after 24 hours. Whoever opens it signs in or creates an account and joins with the link's
role; they keep their other teams. Changing roles, removing members and leaving a team are done
in the console. The last owner of a team cannot be removed, demoted or leave.

## Errors and retries

Every error is JSON:

```json
{"error": {"code": "team_limit", "message": "team limit reached: 5 of 5 active gups (the most this team may run at once on the platform); pause, stop or delete one first, or ask for a higher limit"}}
```

Match on `code` and show `message`. More codes may be added: for a code
you do not know, go by the HTTP status. A failed pause or resize answers `500` with the gup as its
body, and errors inside a stream arrive as `error` frames. A port answers with the app's own
responses; only the proxy's refusals use this format.

| Code | Status | Meaning |
| --- | --- | --- |
| `bad_request` | 400 | Invalid request; show the message |
| `unauthorized` | 401 | Missing, revoked or invalid API key |
| `insufficient_credits` | 402 | Out of credits |
| `forbidden` | 403 | Your role does not allow it, or a file permission refusal |
| `pro_required` | 403 | Fast Spawn, a create from a team template, or a warm pool on the Developer plan |
| `storage_limit` | 403 | A disk larger than your plan allows, or more snapshots than it keeps; delete a snapshot or pick a smaller size |
| `not_found` | 404 | No such resource, or it belongs to another team |
| `method_not_allowed` | 405 | Wrong HTTP method for the route |
| `conflict` | 409 | Wrong phase for this action, a conflicting operation, or a missing prerequisite |
| `not_running` | 409 | The gup is not running and was not woken (`autoResume` off, paused by its lease, or failed); see [When exec fails](#when-exec-fails) |
| `busy` | 409 | Another lifecycle operation is in progress; retry once it settles |
| `location_unavailable` | 409 | The location has no ready node |
| `warm_pool_limit` | 409 | More warm pool slots than your allowance |
| `upload_offset` | 409 | An upload part's offset is past what was received |
| `idempotency_in_progress` | 409 | The first request with this `Idempotency-Key` is still running |
| `gone` | 410 | The resource is gone |
| `too_large`, `part_too_large` | 413 | The body, or an upload part, is too large |
| `range_not_satisfiable` | 416 | A download `Range` past the end of the file |
| `idempotency_key_reused`, `checksum_mismatch`, `unprocessable` | 422 | Same key with another body; upload checksum differs; otherwise unprocessable |
| `team_limit`, `rate_limited` | 429 | Too many running gups, or too many requests; retry after `Retry-After` |
| `internal` | 500 | Internal or lifecycle failure; read the body and check the gup's state |
| `not_enabled`, `agent_unavailable`, `agent_too_old` | 501 | Feature off; the gup's in-guest agent is missing or too old (recreate the gup) |
| `bad_gateway` | 502 | The gup or an upstream service did not answer |
| `starting`, `no_capacity`, `unavailable` | 503 | Still starting, no capacity, or a dependency is down; retry after `Retry-After` |
| `timeout` | 504 | An upstream timed out |


**Retrying.** Every `429` and `503` carries `Retry-After` in seconds: wait that long, then repeat
the request. After a network error, `502` or `504`, repeat only requests that are safe to repeat:
`GET`, `PUT`, `DELETE`, a create or process start with its `Idempotency-Key`, lifecycle actions
and keepalive. **Never repeat an exec once the request was sent**: the command may have run. The
one exception is an exec refused with our JSON error, which never started its command (see
[When exec fails](#when-exec-fails)). The
SDKs do this for you (3 retries, `Retry-After` capped at 30 s, otherwise backoff from 0.5 s).

## API versioning

- `/v1` only grows: new routes, new optional request fields, new response fields, new error
  codes, new stream frame types.
- Your client must ignore what it does not know: unknown fields, unknown frame types and unknown
  error codes (fall back to the HTTP status).
- A breaking change ships only under `/v2`. `/v1` keeps working for at least 90 days after `/v2`
  exists, and during that time its responses carry `Deprecation` and `Sunset` headers
  (RFC 9745, RFC 8594).
- The SDKs follow Semantic Versioning: a new major version for a new API major version, a minor
  version for new features.
- Every change is listed in the [Changelog](#changelog) at the end of this page.

## SDKs

Both SDKs are open source (Apache-2.0) and share one version number. They handle retries,
idempotency keys, NDJSON streams, chunked uploads and resumable downloads. The Python SDK has a
sync client and an asyncio client in the same install (see
[Python with asyncio](#python-with-asyncio)); the TypeScript SDK is async by nature.

| Language | Install | Import |
| --- | --- | --- |
| Python 3.9+ | `pip install guplet-sdk` ([PyPI](https://pypi.org/project/guplet-sdk/)) | `import guplet` |
| TypeScript / JavaScript, Node.js 22+ | `npm install guplet-sdk` ([npm](https://www.npmjs.com/package/guplet-sdk)) | `import { Client } from "guplet-sdk"` |

A longer Python example:

```python
import guplet

client = guplet.Client()
vm = client.create(os="ubuntu-24.04", size="s", ttl=900, wait=True)

for stream, text in vm.run_stream("for i in 1 2 3; do echo $i; sleep 1; done"):
    print(stream, text, end="")

vm.files.write("notes.txt", "hello\n")
print(vm.files.read_text("notes.txt"))

p = vm.processes.start("python3 -m http.server 8080")
print(vm.port_url(8080))                 # https://8080-<id>.guplet.com

vm.pause(wait=True)
vm.resume(wait=True)
snap = vm.snapshot()
vm.kill()
```

SDK errors are `GupletError` with the HTTP status and the error code, and subclasses such as
`Unauthorized` (401), `InsufficientCredits` (402), `Forbidden` (403; `StorageLimit` for
`storage_limit`), `NotFound` (404), `Conflict` (409), `TeamLimit` (429 `team_limit`) and
`NotEnabled` (501). A non-zero exit code is not an error: read it from the result.
`client.limits()` returns your plan's caps and current counts (`GET /v1/limits`).

### Python with asyncio

For code that runs on an event loop (FastAPI, aiohttp, an asyncio agent loop), use
`guplet.AsyncClient`, which comes with `pip install guplet-sdk` (1.5.0 or later). The calls are
the same as the sync client's, awaited:

```python
from contextlib import asynccontextmanager
from fastapi import FastAPI
import guplet

@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.guplet = guplet.AsyncClient()   # one per process: it keeps connections alive
    yield
    await app.state.guplet.aclose()

app = FastAPI(lifespan=lifespan)

@app.post("/run")
async def run(cmd: str):
    async with await app.state.guplet.create(os="toolbox", size="s", ttl=600, wait=True) as gup:
        r = await gup.run(cmd, timeout=60)    # other requests keep being served meanwhile
        return {"stdout": r.stdout, "exit_code": r.exit_code}
```

- **What it covers:** `create`, `get`, `list`, `delete`, `exec` and `execs`; on a gup `run`,
  `run_stream`, `cost`, `cost_stream`, `keepalive`, `files`, `processes`, `pause`, `resume`,
  `kill`, `refresh`, `wait` and `port_url`. Everything else (templates, secrets, snapshots,
  resize, logs, desktop) is in the sync `guplet.Client` only.
- **Many commands at once:** one client runs many commands at the same time, for example with
  `asyncio.gather(gup.run("a"), gup.run("b"))`.
- **Streams:** use `async with gup.run_stream(cmd) as s:` and then `async for name, text in s:`.
  `p.output()` on a background process and `gup.cost_stream()` work the same way.
- **Your own httpx client:** `guplet.AsyncClient(http_client=httpx.AsyncClient(...))` sends every
  call through your client, so its connection limits, timeouts, proxies and event hooks (for
  tracing) apply. Closing the guplet client leaves yours open. Without `timeout=`, calls use your
  client's timeout (httpx's default is 5 seconds), except that streams wait up to 60 seconds for
  data and `wait=True` calls up to their timeout plus 10 seconds. Every running command holds one
  connection, so your `max_connections` (100 by default in httpx) limits how many run at once. A
  `raise_for_status()` response hook bypasses the SDK's retries and error classes: leave it out.
- **Cancelling:** cancelling a `run` stops the command on the gup. That covers `asyncio.wait_for`
  and anyio timeouts such as `anyio.fail_after`. FastAPI does not cancel an endpoint when its
  client disconnects, so give long runs a timeout.
- **Errors:** the same `GupletError` classes as the sync client. A network error is an
  `httpx.TransportError`.

## Command line (CLI)

`guplet` is a single binary for Linux and macOS, on amd64 and arm64. Install it with:

```bash
curl -fsSL https://guplet.com/install | sh
```

The installer downloads the build for your system, checks its SHA-256 and puts it in
`~/.local/bin` (no sudo). If that directory is not on your `PATH`, it tells you the line to add.
Set `GUPLET_INSTALL_DIR` to install elsewhere. Run it again to upgrade; `guplet version` prints the
version you have.

Log in once with a team API key. The API URL is built in.

```bash
guplet login --api-key-file ~/guplet-key.txt     # or: guplet login --api-key guplet_…
guplet whoami                                    # team and role
```

Common commands:

```bash
guplet catalog                                   # images, sizes, what each image is for
guplet gup create --os toolbox --size s --ttl 30m --wait
guplet gup list
guplet gup exec <id> -- 'python3 -c "print(6*7)"'   # the exit code is the command's
guplet gup exec <id> --detach -- 'python3 -m http.server 8080'   # in the background
guplet gup exec <id> --cost -- 'make test'           # prints the gup's cost since it began
guplet gup cost <id> --since <RFC 3339> -f           # follow that cost until the gup stops
guplet execs <exec id>                               # one command's record and costs (or --call-id ID)
guplet gup files put <id> ./data.csv /home/user/data.csv
guplet gup ssh <id>                              # SSH with a short-lived certificate
guplet gup terminal <id>                         # an interactive terminal, no SSH needed
guplet gup pause <id> --wait
guplet gup delete <id>
guplet usage                                     # running time and cost of the team
```

`guplet --help` lists every command, and `guplet gup <verb> -h` the flags of one. Every command
takes `-o json` for scripts. Instead of `guplet login`, scripts can set `GUPLET_TOKEN` (the API
key) or `GUPLET_API_KEY_FILE` (a file holding it).

## Connect an agent with MCP

guplet runs a hosted MCP server at `https://api.guplet.com/mcp` (Streamable HTTP). An agent that
speaks MCP, such as Claude or Claude Code, can then create gups, run commands, read and write
files, and delete gups without any code on your side.

Authenticate with a team API key in the `Authorization` header. The key acts as a team admin, and
everyone who uses a connector with a shared key acts as that team, so keep it in the MCP client's
secret settings.

- **Claude:** add a custom connector named `guplet` with the URL above, choose **No sign in**, and
  add the request header `Authorization: Bearer <your API key>`.
- **Claude Code:** add this to your MCP configuration; the key is read from `GUPLET_TOKEN`:

```json
{
  "mcpServers": {
    "guplet": {
      "type": "http",
      "url": "https://api.guplet.com/mcp",
      "headers": { "Authorization": "Bearer ${GUPLET_TOKEN}" }
    }
  }
}
```

To try it, ask your agent to create a `toolbox` gup, write a Python script that adds the integers
from 1 to 100, run it, read the result, and delete the gup.

| Tool | What it does |
| --- | --- |
| `get_catalog`, `get_limits` | The images, sizes and Fast Spawn images; your team's running gups and limit |
| `create_gup` | Creates a gup from `image` and `size`, with a `requestKey` you choose (send the same key and arguments again after a lost answer to avoid a second gup); optional `ttlSeconds` and `launchMode`. It is billed while it runs |
| `list_gups`, `get_gup` | Your gups, or one gup, with its phase and expiry; check the phase after a create |
| `write_file`, `read_file` | UTF-8 text files of up to 64 KiB; writing replaces the file |
| `run_command` | Runs a shell command, with optional `cwd` and `timeoutSeconds` (default 30, at most 60). Returns the exit code and the first 32 KiB of stdout and stderr, marked when cut. A non-zero exit is a completed command |
| `delete_gup` | Deletes the gup and its disk |

Errors come back as tool results with the API's `status`, `code` and `message` (and `retryAfter`
when there is one).

## Changelog

Changes to the API and the SDKs, newest first. Under `/v1` every change is additive unless it
says otherwise (see [API versioning](#api-versioning)).

### 2026-12-04: the Scale plan, and a limit on kept gups

- A third plan, **Scale**: $150 per month including $150 of compute, 300 running gups, 200 kept
  gups, 200 snapshots and 10 warm pool slots of your own. Subscribe on the console's Usage & billing
  page; upgrading from Pro cancels Pro with a prorated credit. `GET /v1/billing` answers
  `plan: "scale"`.
- Every plan has a limit on kept paused or stopped gups (Developer 10, Pro 50, Scale 200), shown in
  `GET /v1/limits` as `maxKeptGups` and `keptGups`. Once enforced, the least recently paused or
  stopped gup over the limit is deleted and a notification says why; for now nothing is deleted.

### 2026-12-04: interrupted streams, and 404 for a gup being deleted

- A command running when its gup is paused, stopped or deleted no longer hangs until its
  `timeoutSeconds`: its stream ends at once with `{"t":"error","message":"interrupted: the gup was
  paused (a pause request)"}` (or `its lease ran out`, `the team ran out of credits`, …), and the
  command is stopped. A logs follow ends the same way and a terminal closes; background-process
  output, file transfers and port connections are not cut.
- A gup whose deletion has started answers `404` to exec, files, terminal and the other calls at
  once (before: `503` until it was gone), and `start` or `resume` answers `409`.

### 2026-12-04: requests during a pause wait, then wake the gup

- Exec, files, terminal, logs, desktop and port requests that arrive after a pause or stop was
  asked for, before it is done, now wait for it to finish and then wake the gup. Before, they could
  start on the gup and be frozen halfway when the pause took effect. No API change.

### 2026-12-03: SDK 1.7.0, the command's start time on exec

- The exec stream and result keep the start frame's `since`, the start of the command's cost
  window, as soon as the stream opens: `result.since` / `stream.since` (a time) and
  `since_raw` / `sinceRaw` (the exact string, for `gup.cost(since)`). Before, the SDKs had it only
  from the first cost frame. Both SDKs are at 1.7.0.
- New in this reference: [When exec fails](#when-exec-fails), every status exec can answer, which
  ones leave the gup usable, and that an exec refused with our JSON error never started its command.

### 2026-12-03: SDK 1.6.0, more calls and your own httpx client for Python asyncio

- `guplet.AsyncClient` gains `exec` and `execs`, and an async gup gains `cost`, `cost_stream` and
  `keepalive`, the same calls as the sync client's, awaited.
- `guplet.AsyncClient(http_client=...)` takes your own `httpx.AsyncClient`. See
  [Python with asyncio](#python-with-asyncio). Both SDKs are at 1.6.0; the TypeScript SDK is
  unchanged.

### 2026-12-03: SDK 1.5.0, one install for Python

- `pip install guplet-sdk` now brings both Python clients, `guplet.Client` and
  `guplet.AsyncClient`: `httpx` is a regular dependency instead of the `async` extra.
  `pip install "guplet-sdk[async]"` still works and installs the same thing. Both SDKs are at 1.5.0;
  the TypeScript SDK is unchanged.

### 2026-12-03: SDK 1.4.0, asyncio client for Python

- `guplet.AsyncClient` in the Python SDK, for FastAPI and other asyncio code:
  `pip install "guplet-sdk[async]"`. See [Python with asyncio](#python-with-asyncio). The sync
  client is unchanged and still has no dependencies. The TypeScript SDK is unchanged.

### 2026-12-02: credits of any amount, automatic top-up

- The console's **Add credits** takes any whole-dollar amount from $5 to $1,000 besides the packs.
- **Automatic top-up:** a team admin can save a card in the console; when the balance falls below a
  threshold the card is charged a chosen amount (at most 3 times a day). `GET /v1/billing/auto-top-up`
  shows the state. Team admins also get an email when the balance runs low.

### 2026-12-02: SDK 1.3.0

- `client.limits()` in both SDKs: your plan's caps and current counts (`GET /v1/limits`).
- A `StorageLimit` error for `403` `storage_limit`, and the snapshot's `lastUsedAt` and `deleteAt`.

### 2026-12-01: storage limits

- **Storage limits per plan:** the largest disk of one gup (Developer 40 GiB, Pro 80 GiB) and how
  many snapshots a team keeps (10, 50). Over them, a create, restore, resize or snapshot answers
  `403` `storage_limit`. `GET /v1/limits` gains `maxDiskGiB`, `maxSnapshots`, `snapshots` and
  `snapshotRetentionSeconds`.
- **Snapshot retention:** a snapshot not restored for 14 days is deleted, with a notification 24 hours
  before. Snapshots gain `lastUsedAt` and `deleteAt`.

### 2026-12-01: SDK 1.2.0

- **Exec ids and records:** every exec stream starts with `{"t":"start","id":"ex_…"}` (also in the
  `X-Exec-Id` header) and can carry your `callId`; `GET /v1/execs/{id}` and
  `GET /v1/execs?callId=` return the exec with its cost from start to exit and from start until
  the gup stops (see [Exec records](#exec-records)). SDKs: `run(cmd, call_id=…)` /
  `run(cmd, { callId })`, `result.exec_id` / `result.execId`, `client.exec(id)`,
  `client.execs(call_id)`; CLI: `guplet gup exec --call-id`, `guplet execs`.
- **Cost of a command:** `"cost": true` on exec adds `cost` frames with what the gup has cost since
  the command began; `GET /v1/gups/{id}/cost?since=&follow=1` follows it until the gup stops (see
  [Cost of a command](#cost-of-a-command)). SDKs: `run(cmd, cost=True)`, `gup.cost()` and
  `gup.cost_stream()` (`costStream()` in TypeScript); CLI: `guplet gup exec --cost`, `guplet gup cost`.

### 2026-11-30

- **CLI installer:** `curl -fsSL https://guplet.com/install | sh` installs the `guplet` command
  line on Linux and macOS (see [Command line (CLI)](#command-line-cli)).
- **CLI installer** for Linux and macOS: `curl -fsSL https://guplet.com/install | sh`.
- **Hosted MCP server** at `https://api.guplet.com/mcp`: agents create gups, run commands and
  exchange files through MCP tools (see [Connect an agent with MCP](#connect-an-agent-with-mcp)).
- This reference is published at `https://console.guplet.com/docs`, with this changelog.

### 2026-11-25: SDK 1.1.0

- `create()` takes no type: `client.create(os="toolbox", size="s")`. `kind="microvm"` is still
  accepted.
- Python: one `Client` reuses its connections, so calls no longer pay a new TLS handshake each.
  `Client.close()` closes the idle ones.
- New: `fast_spawn_images` / `fastSpawnImages` on the catalogue, `client.warm_pools` /
  `client.warmPools`, and `goldens` on templates.

### 2026-11-24

- **`kind` is optional on `POST /v1/gups`.** A gup is created from an image (`os`) at a size; the
  image decides what the gup is. `kind: "microvm"` is still accepted, and responses still carry
  `kind`. A body without `os` answers `400`.
- **Fast Spawn takes only the images in `fastSpawnImages`** (new on `GET /v1/microvm/catalog`).
  `launchMode: "fast_spawn"` with another image now answers `400` instead of booting normally:
  use the default `workstation` for those.
- **New image `toolbox`** for agent tool calls: Python with numpy, pandas, matplotlib and
  requests, Node.js, git and GCC.
- Warm pools hold only Fast Spawn images.

### 2026-11-22: plans

- **Developer and Pro plans.** Every team starts on Developer. Pro is a monthly subscription that
  adds Fast Spawn (`launchMode: "fast_spawn"`) and team templates. On Developer, Fast Spawn and
  creates from a template answer `403` `pro_required`, and template builds `403`. `GET /v1/billing` gains `plan`, `hostedLimit`, `hostedConcurrency` and
  `allowance`. Developer teams may run 5 gups at once, Pro teams 100.

### 2026-11-21

- Only microVM gups can be created. A create that asks for a container answers `501`
  `not_enabled`, and the catalogue reports `containers: false`. Existing container gups keep
  running until they end.

### 2026-11-20

- **Faster template starts.** The first gup of a team template at a named size records a memory
  image of the booted gup; later gups of that template and size start from it.
  `GET /v1/templates/{name}` shows them as `goldens`.
- **Warm pools** for Pro teams: `/v1/warm-pools`, `maxWarmSlots` and `warmSlots` on
  `GET /v1/limits`, `warmSeconds`, `warmCost` and `warm` rows in `GET /v1/usage`, and the error code
  `warm_pool_limit`. Deleting a template that has a pool answers `409`.

### 2026-11-19: SDK 1.0.0

- **Background processes:** `/v1/gups/{id}/processes`, to start a command, read its output by
  offset, write to its stdin and stop it.
- **Large files:** resumable chunked uploads (`/files/uploads`), `Range` downloads and
  `POST /files/rename`.
- **Wake on use and idle pause:** calls to a paused or stopped gup wake it instead of answering
  `409`; a gup unused for 15 minutes is paused. New: `autoResume` and `idleTimeoutSeconds` on create
  and on the gup, `lastActivityAt`, and `PUT /v1/gups/{id}/lifecycle`.
- **Idempotent create:** the `Idempotency-Key` header on `POST /v1/gups` and on process start.
- **JSON errors:** every error is `{"error": {"code", "message"}}`, and every `429` and `503`
  carries `Retry-After`. *Changed:* error bodies used to be plain text with the same message.
- **Locations** (`GET /v1/locations`, `location` on create), **team limits** (`GET /v1/limits`,
  `429` `team_limit`), and **team invites** (`/v1/invites`).
- The SDKs' first public release, on PyPI and npm, with retries and idempotency keys built in.

### 2026-11-17

- **CPU billed by use.** Every gup may use up to `cpuBurstVcpu` vCPUs (new on the catalogue).
  Its size's CPU floor is billed whatever the use, and CPU used above the floor is billed by the
  vCPU-second. New: `metered` and `cpuFloor` on `GET /v1/billing`, `cpuFloorCores` on metrics,
  `cpuSeconds` and `burstCpuSeconds` in usage.

### 2026-11-07: renamed to guplet

- *Breaking:* the platform became guplet and a sandbox a gup. The API moved to
  `https://api.guplet.com`, routes to `/v1/gups`, and ports to `https://<port>-<id>.guplet.com`.
  The port header is `X-Gup-Token`, the field `gupId`, the events filter `?gup=`. New API keys
  start with `guplet_`; older keys keep working.
