# InstaBox docs > InstaBox gives each agent a Linux machine of its own in the cloud. Start with one command, then read only the page you need. --- # Quick start https://instabox.sh/docs/start.md Install the CLI and start your first machine. ### 1. Install ``` npx instabox@latest ``` This signs you in, installs the `instabox` CLI and adds the instabox skills. ### 2. Start a machine ``` instabox create --name dev instabox ssh dev # open a shell instabox exec dev -- uname -a # or run one command ``` Or ask your agent to "create an instabox machine and get me into it". ### 3. When you are done ``` instabox suspend dev # pause, everything is kept instabox resume dev # pick up where you left off instabox rm dev # delete it and its files ``` > `npx instabox@latest sh` does steps 1 and 2 in one go. --- # Concepts https://instabox.sh/docs/concepts.md The few words the dashboard, the CLI and the API use. | Word | What it is | |---|---| | **Machine** | A Linux VM of your own in the cloud, with its own kernel, root and Docker. Files under `/data` (home is `/data/home`) and the software you install stay. | | **Template** | What a new machine starts from: `agent-browser` (the default), `t3`, `herdr`, `orca`, `android` ([Android apps](https://instabox.sh/docs/android.md)) or `omarchy` (Arch Linux with the Omarchy desktop). The free plan creates from `agent-browser`, `android`, `omarchy` or `ci` only. `instabox templates` lists them. | | **Snapshot** | A saved copy of one of your machines, private to you. New machines can start from it. | | **Operation** | A change to a machine (create, start, stop, pause, resume, delete). You follow it until it succeeds or fails. | | **API key** | `ibk_...`: how programs, CI jobs and agents sign in. | | **Org Secrets** | Encrypted credentials that sandboxes see as placeholders; the outbound proxy adds them to HTTPS headers for allowed hosts. | ### Running, paused, stopped | State | Files | Memory and processes | Use it to | |---|---|---|---| | Running | kept | running | work | | Paused | kept | kept | step away and come back to the same session | | Stopped | kept | lost | shut down; the next start boots fresh | | Deleted | gone | gone | free the machine for a new one | A new machine pauses once it has been idle for 30 minutes. On a paid plan you can choose 5 to 30 minutes, or `instabox auto-suspend 0` to turn that off; below 5 or above 30 minutes is refused. On the free plan it stays 30 minutes, and `--auto-suspend` with another value is refused. Commands, files, SSH and a visit to one of its public port URLs resume it by themselves **only when it paused itself** (idle, the max-run cooldown or memory pressure: `autoSuspendedAt` set). A machine **you** paused or stopped stays offline: a public URL returns `503` (Sandbox offline) until you **Resume** (keeps memory) or **Start** (boots fresh). > The API and CLI say `suspend`, `suspending` and `suspended` for pause, Pausing and Paused, and `error` for Failed. --- # Integrate with the SDK https://instabox.sh/docs/integrate.md The calls an app needs: create, pause and resume, delete, a shell, the desktop, and usage. Everything below runs on your server with an API key (`ibk_...`, from **API keys** in the dashboard sidebar). Never send the key to a browser. ```sh npm install @insforge/instabox-sdk export INSTABOX_API_KEY=ibk_... ``` The SDK reads `INSTABOX_API_KEY` from the environment, so the `apiKey` option below is optional. Pass it when the key comes from somewhere else, such as your own secret store. Without a key, every call throws `InstaboxAuthError` (`missing_api_key`) before sending a request. Each example below is a whole program and runs on its own: save it as a `.mjs` file, such as `create.mjs`, and run `node create.mjs` with Node.js 18 or later. The examples use `import` and top-level `await`, so a `.js` file needs `"type": "module"` in your `package.json`. Each example deletes the machine it creates, in `finally` when other steps come first, so a failed step does not leave a machine running. Your app keeps the machine and deletes it when your user is done. ### 1. Create a machine ```js import { Sandbox } from '@insforge/instabox-sdk' const sbx = await Sandbox.create('agent-browser', { // optional: the env var works without this line apiKey: process.env.INSTABOX_API_KEY, // your own tags, to find it later metadata: { customer: 'acme' }, // disable personal Vault delivery; no Secret selections are supplied vault: false, }) try { // m_...: store it with your user console.log(sbx.sandboxId) } finally { // your app keeps it; this example cleans up await sbx.kill() } ``` `agent-browser` is the default template: Linux, a desktop and a browser. Later, from another request: `const sbx = await Sandbox.connect(sandboxId)`, with the `sbx.sandboxId` you stored. `Sandbox.list({ metadata: { customer: 'acme' } })` finds machines by tag. ### 2. Pause and resume ```js import { Sandbox } from '@insforge/instabox-sdk' const sbx = await Sandbox.create('agent-browser', { vault: false }) try { // memory, files and running processes are kept await sbx.pause() // carries on where it left off, usually in about a second await sbx.resume() // look without waking it, e.g. from another request const peek = await Sandbox.connect(sbx.sandboxId, { resume: false }) console.log((await peek.getInfo()).state) // connect also resumes a paused machine const again = await Sandbox.connect(sbx.sandboxId) console.log(await again.isRunning()) } finally { await sbx.kill() } ``` Idle machines pause by themselves after 30 minutes. ### 3. Delete it ```js import { Sandbox } from '@insforge/instabox-sdk' const sbx = await Sandbox.create('agent-browser', { vault: false }) // store the ID: any later request can delete by ID const id = sbx.sandboxId // deletes the machine and its disks; false if already gone console.log(await sbx.kill()) // the same, by ID; false here, as it is already gone console.log(await Sandbox.kill(id)) ``` ### 4. A shell For commands from your code: ```js import { Sandbox } from '@insforge/instabox-sdk' const sbx = await Sandbox.create('agent-browser', { vault: false }) try { const r = await sbx.commands.run('python3 -c "print(6 * 7)"', { cwd: '/data/home', timeoutMs: 60_000, }) // a non-zero exit throws CommandExitError (stdout, stderr, exitCode) console.log(r.stdout, r.exitCode) await sbx.files.write('/data/home/app.py', 'print("hi")') console.log(await sbx.files.read('/data/home/app.py')) } finally { await sbx.kill() } ``` For an interactive SSH session (your public key in, a short-lived certificate out): ```js import { execFileSync } from 'node:child_process' import { existsSync, mkdtempSync, readFileSync } from 'node:fs' import { homedir, tmpdir } from 'node:os' import { join } from 'node:path' import { Sandbox } from '@insforge/instabox-sdk' // your key pair; a throwaway one if you have none let key = join(homedir(), '.ssh', 'id_ed25519') if (!existsSync(`${key}.pub`)) { key = join(mkdtempSync(join(tmpdir(), 'instabox-ssh-')), 'id_ed25519') execFileSync('ssh-keygen', ['-q', '-t', 'ed25519', '-N', '', '-f', key]) } const publicKey = readFileSync(`${key}.pub`, 'utf8') const sbx = await Sandbox.create('agent-browser', { vault: false }) try { const ssh = await sbx.sshCredentials(publicKey, { ttlSeconds: 3600 }) // save ssh.certificate as -cert.pub next to the private key, // add ssh.knownHostsLine to known_hosts, then: console.log(`ssh -i ${key} -p ${ssh.port} ${ssh.username}@${ssh.host}`) } finally { // your app keeps the machine while the session lasts await sbx.kill() } ``` See [SSH](https://instabox.sh/docs/ssh.md) for the details. ### 5. The desktop (VNC) ```js import { randomBytes } from 'node:crypto' import http from 'node:http' import https from 'node:https' import { Sandbox } from '@insforge/instabox-sdk' const sbx = await Sandbox.create('agent-browser', { vault: false }) try { // starts the desktop; safe to call again await sbx.desktop.start() // { installed, running, width, height } console.log(await sbx.desktop.status()) // Let an agent use it await sbx.desktop.open('https://example.com') const png = await sbx.desktop.screenshot() console.log(png.length) await sbx.desktop.click(640, 400) await sbx.desktop.type('hello') await sbx.desktop.press('Enter') // Your own VNC viewer: GET /v1/machines/{id}/vnc with the key upgrades // to a WebSocket that carries the desktop's VNC (RFB) stream const api = new URL(process.env.INSTABOX_API_URL ?? 'https://api.instabox.sh') const status = await new Promise((ok, fail) => { const req = (api.protocol === 'https:' ? https : http).request( new URL(`/v1/machines/${sbx.sandboxId}/vnc`, api), { headers: { 'X-API-Key': process.env.INSTABOX_API_KEY, Connection: 'Upgrade', Upgrade: 'websocket', 'Sec-WebSocket-Version': '13', 'Sec-WebSocket-Key': randomBytes(16).toString('base64'), }, }, ) // 101: hand the socket to your VNC client; this example closes it req.on('upgrade', (res, socket) => { socket.destroy() ok(res.statusCode) }) req.on('response', (res) => fail(new Error(`vnc: HTTP ${res.statusCode}`))) req.on('error', fail) req.end() }) console.log(status) } finally { await sbx.kill() } ``` Any key with `machines:write` that can reach the machine, a workspace key too, opens its desktop this way, over `GET /v1/machines/{id}/vnc`. A link for people without an instabox account, `sbx.desktop.streamUrl({ viewOnly: true, ttlSeconds: 3600 })` for a new tab or an ` ``` - **One machine.** A link opens that machine's desktop only. It is not an API key and cannot call the API. - **View-only is enforced by the server.** Keyboard, mouse and clipboard input from a view-only link never reach the machine. Pass `viewOnly: false` for a link that can control it. - **Expiry stops new connections.** A viewer that is already connected stays connected until it leaves. - **Revoke ends everything.** `revokeStreamUrls()` invalidates every link for the machine and closes open viewers within a few seconds. Deleting the machine does the same. ### Building a service for your own users Keep your API key on your server, never in a browser. Links are the machine creator's, so this server runs on the personal key of the account that creates the machines, and creates them with that key too. A workspace key gets `403 permission_denied` here. Make a fresh link each time a user opens their desktop, and revoke when their access ends: ``` // your server, e.g. Express app.get('/api/desktop-link', async (req, res) => { const machineId = await machineOf(req.user) // your own user-to-machine mapping const sbx = await Sandbox.connect(machineId) res.json(await sbx.desktop.streamUrl({ viewOnly: !req.user.canControl, ttlSeconds: 600 })) }) // when the user's access ends await (await Sandbox.connect(machineId)).desktop.revokeStreamUrls() ``` On a workspace key, relay the desktop instead of making links: your server opens `GET /v1/machines/{id}/vnc` (a WebSocket, with a key that has `machines:write`) and passes the VNC stream to your user's viewer, or sends them `sbx.desktop.screenshot()` images. Your server then decides who sees what, and revoking is closing that connection. Each user has at most 8 open terminals and desktops at once, and a workspace key counts as its workspace's owner: a ninth `/vnc` connection gets a retryable `429 quota_exceeded`, so close a viewer's connection when they leave. Tag machines with metadata, such as `{ customer: 'acme' }`, to find them later with `Sandbox.list({ metadata })`. ### Over HTTP ``` H="X-API-Key: $INSTABOX_API_KEY" # universal and t3 only (no desktop in the image): install, then wait until installed (about half a minute) curl -s -H "$H" -H 'Content-Type: application/json' \ -d '{"action": "install"}' "$INSTABOX_API_URL/v1/machines/m_.../desktop" for i in $(seq 60); do # up to 5 minutes; stops early on a failed install, and start then says why curl -s -H "$H" -H 'Content-Type: application/json' -d '{"action": "status"}' \ "$INSTABOX_API_URL/v1/machines/m_.../desktop" | jq -e '.installed or .failed' >/dev/null && break sleep 5 done curl -s -H "$H" -H 'Content-Type: application/json' \ -d '{"action": "start", "width": 1280, "height": 800}' "$INSTABOX_API_URL/v1/machines/m_.../desktop" curl -s -H "$H" -H 'Content-Type: application/json' \ -d '{"viewOnly": true, "ttlSeconds": 3600}' "$INSTABOX_API_URL/v1/machines/m_.../desktop/stream" # {url, expiresAt} curl -s -X DELETE -H "$H" "$INSTABOX_API_URL/v1/machines/m_.../desktop/stream" # revoke ``` Over HTTP, `start` does not install anything. On a template without the desktop (`universal`, `t3`), send `{"action": "install"}` first, poll `{"action": "status"}` until `installed` is true (about half a minute), then `start`. A `start` that started nothing answers with `installed` false and a `hint` naming the next call. Both stream calls are the machine creator's: only the machine's creator, signed in or with their personal key (with `machines:write`), may call them. A workspace key gets `403 permission_denied` and opens the desktop over `GET /v1/machines/{id}/vnc` (a WebSocket, `machines:write`) instead. --- # Org Secrets https://instabox.sh/docs/secrets.md Credentials added to HTTPS headers by the outbound proxy, scoped to your org. Secrets are encrypted key=value pairs owned by an org. A sandbox can only use Secrets from its own org. Each Secret lists the exact hosts it may be sent to, or `*` for every public HTTPS destination. Partial wildcards such as `*.example.com` are not supported. Once Secrets is enabled for your account and supported by the server, new Dashboard sandboxes receive all current and future proxy Secrets from their workspace. Existing sandboxes keep their selections. Use the CLI or HTTP API to change a sandbox's selection. ### How a Secret reaches an API The sandbox sees the named environment variable, but its value is an opaque placeholder. Applications keep their normal HTTPS URL and header name. The outbound proxy checks sandbox authorization, host scope and the upstream TLS certificate before replacing the placeholder within a header value. Version one supports HTTPS on port 443; URL parameters and request bodies are not substituted. HTTP Basic auth in `Authorization` is decoded, the placeholder inside `user:password` is replaced, and the credential is re-encoded; any other encoding or signing of the placeholder prevents replacement. ### Browsers and HTTP/3 The proxy only sees HTTPS over TCP port 443. HTTP/3 (QUIC, on UDP port 443) bypasses it, so a request sent that way reaches the API with the placeholder instead of the credential, and the API usually refuses it (for example `401`). curl and most HTTP libraries use TCP unless asked for HTTP/3. The proxy also drops `Alt-Svc` from the responses it relays, but Chromium may still pick HTTP/3, for example from DNS or from an earlier visit saved in its profile. Turn QUIC off in a Chromium-based browser that sends Secrets: ```sh chromium --disable-quic ``` In Playwright or Puppeteer, pass the same flag: `chromium.launch({ args: ['--disable-quic'] })` or `puppeteer.launch({ args: ['--disable-quic'] })`. The browser must also trust the sandbox CA, with normal certificate checks; do not turn verification off. ### Save and select Sign in with the CLI as an org owner or admin, or run it headless with the workspace's `workspace:admin` API key in `INSTABOX_API_KEY` (org commands then default to the key's org, and `secrets rm` needs `--yes` without a terminal). Values below are read from stdin or a prompt without echo: ```sh instabox secrets set SERVICE_API_KEY --org team --host api.example.com instabox create --name app --org team --secrets all instabox secrets show app ``` Omitting `secrets` in CLI or API creation keeps the existing Vault behavior without enrolling the sandbox in Secrets. To disable delivery from both stores on a fresh sandbox, pass `--no-vault --secrets none`. Without `--host`, a Secret may be sent to every public HTTPS destination (`*`); pass `--host` to limit it. ### AI provider keys `--ai` scopes a model provider key to its API: `anthropic` (`api.anthropic.com`), `openai` (`api.openai.com`), `gemini` (`generativelanguage.googleapis.com`) and `openrouter` (`openrouter.ai`). It can be repeated and combined with `--host`: ```sh instabox secrets set ANTHROPIC_API_KEY --ai anthropic instabox secrets select app --secrets ANTHROPIC_API_KEY ``` The box only sees a placeholder in its environment and files, so the real key never lands on its disk or in snapshots; the proxy puts the key into `x-api-key` or `Authorization` only for the provider's host. Block a box from all Secrets with `secrets select BOX --secrets none` and unblock it with `--secrets all`. Servers with per-sandbox usage enabled show each Secret's proxied and denied request counts in `secrets show BOX` and `GET /v1/machines/{id}/secrets`. With `*`, any process in an enrolled sandbox can send the Secret to any public HTTPS destination, including a host it controls. All supported HTTPS hosts are intercepted, even without a placeholder. Intercepted connections to private addresses are closed, WebSockets work (placeholders are replaced in the handshake headers, not in messages), and clients must trust the sandbox CA without certificate pinning. Prefer exact hosts when the credential must stay with a specific service. The application reads `SERVICE_API_KEY` as a sandbox-specific placeholder and sends it in its usual header, such as `Authorization: Bearer ` or `X-Api-Key: `. No separate Secret retrieval API is needed. Git over HTTPS sends the token as Basic auth, so `git clone` and `git push` to private repos work with a placeholder too. Add `github.com` (git) to the Secret's hosts next to `api.github.com` (`gh`), and give git a credential helper that returns the placeholder, such as `gh auth setup-git` for `GH_TOKEN`. For bulk import, `instabox secrets import .env --org team --host api.example.com` validates and writes the whole file atomically; all entries share that host scope. Importing Secrets does not authorize any sandbox to receive them. ### Update a running sandbox ```sh instabox secrets select app --secrets SERVICE_API_KEY instabox secrets push app instabox secrets show app ``` The supplied selection replaces the previous one. Removing and recreating a Secret with the same name does not restore an explicit grant to the old Secret. `all` includes newly created Secrets. `instabox secrets show` reports proxy authorization and placeholder setup in the sandbox independently. A proxy update is pending until acknowledged, and an acknowledged lease expires within at most 60 seconds without renewal. Requests already admitted, including streams, may finish. Rotating an existing value keeps its placeholder, so applications need no restart. ### Save a Secret with the HTTP API `PUT /v1/orgs/{id}/secrets/{name}` creates or replaces a Secret. The body has three fields: | Field | Required | Meaning | | --- | --- | --- | | `value` | yes | The credential, up to 64 KiB of UTF-8. Proxy values must fit in an HTTP header. | | `delivery` | yes | `"proxy"` or `"env"`, on every write, including a rotation. Without it the request fails with `400 delivery is required`; nothing is inferred from the name or value. | | `hosts` | proxy only | Up to 32 exact hostnames (no scheme, port, path or wildcard); `"*"` allows every public HTTPS destination. Omitted or `[]` means `["*"]`. An env Secret with non-empty `hosts` is rejected. | The name is the variable the box exports, so it follows the rule of a box's [environment variables](https://instabox.sh/docs/machines.md): the names env refuses are refused here too (`400 bad_request`), `BASH_ENV`, `ENV` and `IFS` among them. A Secret saved under a name before it was reserved is not delivered: the rest of the selection is, `secrets show` reports `not delivered: `, and `secrets push` answers `400`. Save the value under another name, select it, delete the old Secret and run `secrets push`. The caller must be an org owner or admin, signed in. After `instabox login`, the CLI's access token works (`instabox whoami` refreshes it first). A workspace API key with `workspace:admin` also works for its workspace, sent as `X-API-Key`. This saves a proxy Secret in your personal org: ```sh instabox whoami >/dev/null AUTH=$(mktemp) jq -r '"Authorization: Bearer " + .accessToken' "${XDG_CONFIG_HOME:-$HOME/.config}/instabox/credentials.json" >"$AUTH" ORG=$(curl -sS "https://api.instabox.sh/v1/orgs" -H @"$AUTH" | jq -r '.orgs[] | select(.personal) | .id') curl -sS -X PUT "https://api.instabox.sh/v1/orgs/$ORG/secrets/SERVICE_API_KEY" -H @"$AUTH" -H 'Content-Type: application/json' --data-binary @- <<'EOF' {"value":"example-api-key","delivery":"proxy","hosts":["api.example.com"]} EOF rm -f "$AUTH" ``` The token header is read from a mode 0600 file and the body from stdin, so neither appears in the process list. A heredoc you type still lands in shell history: for a real credential, build the body from a file instead, `jq -Rs '{value: rtrimstr("\n"), delivery: "proxy", hosts: ["api.example.com"]}' ` | Inside the sandbox: any process there can read and copy it. No host restriction applies. | Both modes are written to `/run/instabox/secrets/env` (tmpfs, mode 0600, owned by the sandbox user) and loaded by `/etc/profile.d/zz-instabox-secrets.sh`. Login shells get them: SSH, `instabox exec` and the exec API. Processes that skip the profile (systemd units, cron, `bash -c` without `-l`) do not, and running processes keep their old environment until restarted. An env Secret reaches a sandbox only when the sandbox selects it in `envSecrets` (`"envSecrets": ["DATABASE_URL"]` on `POST /v1/machines` or `PATCH /v1/machines/{id}/secrets`); `"secrets": "all"` never includes env Secrets. ### Direct Secrets: env and files **Prefer the proxy.** For an HTTPS API key, a proxy Secret keeps the real value out of the box entirely. A direct Secret (`delivery: "env"`, `--direct` in the CLI) puts the real value in the box: any code there, including an agent or a package it installs, can read and copy it. Use direct Secrets only for what the proxy cannot carry: | Use | Delivery | | --- | --- | | API keys and tokens in HTTPS headers, git over HTTPS | proxy (default) | | Login files (`~/.local/share/opencode/auth.json`, `~/.config/gh/hosts.yml`), SSH keys | direct, as a file | | Database, Redis or SMTP URLs; request signing (AWS SigV4, service-account JWTs, HMAC); keys in bodies or query strings; pinned clients | direct, as a variable or a file | Save the Secret as direct (owner or admin), then reference it from a box as a variable (`--secret-env VAR=SECRET`, or `SECRET` for the same name) and/or a home file (`--secret-file PATH=SECRET`): ```sh instabox secrets set OPENCODE_AUTH --direct < ~/.local/share/opencode/auth.json instabox secrets set PROD_PG --direct instabox create --name agent --secret-file .local/share/opencode/auth.json=OPENCODE_AUTH --secret-env DATABASE_URL=PROD_PG instabox secrets select agent --secret-env none # remove every direct reference instabox exec agent --secret-env DATABASE_URL=PROD_PG -- psql -c 'select 1' # this command only ``` In the HTTP API, `POST /v1/machines` and `PATCH /v1/machines/{id}/secrets` take `"directSecrets": [{"secret": "PROD_PG", "env": "DATABASE_URL"}, {"secret": "OPENCODE_AUTH", "file": ".local/share/opencode/auth.json"}]` (replacing the box's direct references; `envSecrets` is the same-name shorthand, not sent with it), and `POST /v1/machines/{id}/exec` takes `"secretEnvs": {"DATABASE_URL": "PROD_PG"}`. - **Where the value lives.** Variables go to `/run/instabox/secrets/env` like the other modes. A file's value is written to `/run/instabox/secrets/files/` (tmpfs, mode 0600, owned by the sandbox user) and the home path becomes a symlink to it, so the disk, disk snapshots and forks never hold the value. A path that already holds a file of the box's is left alone and `secrets show` reports the error; move the file and run `secrets push`. A tool that rewrites its login file replaces the link with a real file on the disk, which is then the box's own. - **Who can reference.** Only an org owner or admin can save a Secret as direct. Anyone who can change a box (`machines:write`) in the org can reference the org's direct Secrets; a proxy Secret can never be referenced as direct, and a Secret of another org cannot be referenced at all. - **Rotation and removal.** A new value reaches running boxes within about 10 seconds: files change in place and new shells get the new variable, while running processes keep the old one until restarted. Stopped and paused boxes get the current value when they start or resume. Deleting the Secret or the reference removes the variable and the file at the next delivery, but copies already read stay: to revoke a direct credential, rotate it at its service. - **Never shown.** No API returns a value: `secrets show` and `GET /v1/machines/{id}/secrets` list `directSecrets` as names and paths. Each reference (create, select, fork, exec) is audited by name. - **Forks** copy the source's Secret selection, proxy and direct, and resolve the values again. A box created from a snapshot takes only its own selection. - Variable names follow the Secret name rule and cannot be `PATH`, `HOME`, `BASH_ENV`, `IFS`, the CA variables or start with `INSTABOX_` or `SSH_`. Paths are relative to the box's home directory: write `.ssh/id_ed25519`, not `~/.ssh/id_ed25519` (the shell turns an unquoted `~/` into your own home; the CLI takes that back as home-relative). At most 64 direct references per box. ### HTTP and SDK callers Use the HTTP API for explicit selections when an SDK does not expose them: ```json { "name": "app", "templateId": "agent-browser", "orgId": "org_...", "secrets": ["SERVICE_API_KEY"] } ``` Send this to `POST /v1/machines`. After creation, use `PATCH /v1/machines/{id}/secrets` with a new `secrets` selection, `GET` on the same path for metadata and status, and `POST` on that path for an immediate refresh. Explicit `null` selections are rejected. API keys with `machines:read` can read org Secret metadata and sandbox selections. `machines:write` can change selections and refresh delivery for authorized sandboxes. Creating, importing, changing or deleting org Secret values requires the org owner or admin: a signed-in session or the workspace's own `workspace:admin` API key. A personal org's key and narrower keys cannot manage values (`403 missing_scope`). Management reads never return values. Full endpoint schemas are in the [OpenAPI specification](https://api.instabox.sh/v1/openapi.json). The SDK creation option `vault: false` disables only per-user Vault delivery; it does not change org Secret selections. Vault inspection and push APIs remain available. When an SDK does not expose Secret selection fields, use the Secret CLI or HTTP API. ### Existing Vault items Vault and Org Secrets remain independent stores. Existing env values, file delivery and metadata selectors keep working; there is no automatic migration. A sandbox can use both stores, and explicitly selected Secrets take precedence for same-named environment variables. `--no-vault` affects only Vault; clearing Secret selections affects only Secrets. `instabox vault export NAME --out recovered.json` remains available for items retained by an earlier explicit migration. Its output contains the real value. --- # Webhooks https://instabox.sh/docs/webhooks.md Signed POSTs when a sandbox is ready, pauses, stops, fails or is deleted. Register an HTTPS endpoint for an org and InstaBox POSTs a signed JSON event to it when one of the org's sandboxes or snapshots changes state, so clients need not poll `GET /v1/machines/{id}`. ### Events | Type | When | |---|---| | `sandbox.created` | the sandbox is accepted (state `creating`) | | `sandbox.started` | it is `running` and ready for exec and SSH (after create, start, resume or wake) | | `sandbox.stopped` | it is `stopped` | | `sandbox.suspended` | it is paused (`suspended`): by you, when idle, or by a plan limit | | `sandbox.error` | it is in `error` | | `sandbox.deleted` | it is `deleted` | | `snapshot.created`, `snapshot.failed`, `snapshot.deleted` | a snapshot is ready, failed to upload, or is deleted | | `webhook.test` | only from a test send | Each body is `{"id":"evt_…","type":"sandbox.suspended","createdAt":"…","orgId":"org_…","data":{"sandbox":{"id":"m_…","name":"worker-1","metadata":{}},"previousState":"suspending","state":"suspended","reason":"idle","operationId":"op_…"}}`. `reason` is what moved it: `user`, `idle`, `archive`, `wake`, `system` (observed by the server, such as a crash), and others. ### Create an endpoint ```sh instabox webhooks create https://example.com/hook --event sandbox.started --event sandbox.error instabox webhooks ls instabox webhooks test wh_... instabox webhooks deliveries wh_... ``` Every `webhooks` subcommand takes `--json` (or `-o json`), `events`, `rm`, `test` and `retry` included. No `--event` subscribes to every type. `create` and `rotate` print the signing secret (`whsec_…`) once. The URL must be public `https`; redirects are not followed. The org's owner or admin manages endpoints, signed in or with an API key of that org: `machines:read` lists and reads deliveries, `machines:write` creates, updates, rotates, tests and retries, `machines:delete` deletes. With `INSTABOX_API_KEY`, `--org` defaults to the key's org. The dashboard's Webhooks page does the same, with a delivery log. Over HTTP: ```sh curl -X POST https://api.instabox.sh/v1/orgs/$ORG/webhooks -H "Authorization: Bearer $INSTABOX_API_KEY" \ -H 'Content-Type: application/json' -d '{"url":"https://example.com/hook","events":["sandbox.started","sandbox.error"]}' ``` `GET /v1/orgs` lists your orgs; an API key sees only its own. The routes are under `/v1/orgs/{id}/webhooks` in the [OpenAPI document](https://api.instabox.sh/v1/openapi.json). ### Verify the signature Requests follow [Standard Webhooks](https://www.standardwebhooks.com/), so its libraries verify them. Headers: `webhook-id` (the event ID, the same on every retry: dedupe on it), `webhook-timestamp` (Unix seconds) and `webhook-signature`: `v1,` and the base64 HMAC-SHA256 of `..`, keyed with the base64-decoded part of the secret after `whsec_`. After a rotation it lists two signatures for 24 hours; accept either, comparing in constant time. Reject timestamps more than 5 minutes off. ```js import crypto from 'node:crypto'; const key = Buffer.from(secret.slice('whsec_'.length), 'base64'); const want = crypto.createHmac('sha256', key).update(`${id}.${timestamp}.${rawBody}`).digest(); const ok = header.split(' ').some((s) => { const got = Buffer.from(s.startsWith('v1,') ? s.slice(3) : '', 'base64'); return got.length === want.length && crypto.timingSafeEqual(got, want); // constant time }); ``` ### Delivery Answer 2xx within 10 seconds of connecting: reply first, then do the work. Other answers and timeouts are retried after 5 s, 5 min, 30 min, 2 h, 5 h, 10 h and 10 h, then the delivery fails; A delivery still pending 3 days after its event fails as expired. `instabox webhooks retry` sends a finished one again. One sandbox's events arrive in order, also across retries: a later event waits while an earlier one is retried. Events of different sandboxes interleave: order those by `createdAt`. An endpoint that fails every attempt for 5 days is disabled, and the workspace's owner and admins get an email; `instabox webhooks update ID --enable` turns it back on. Deliveries are kept 30 days. --- # Agent sign-up https://instabox.sh/docs/agent-auth.md An agent with no browser signs itself up; the account owner approves later with a code. An agent on a machine with no instabox credentials and nobody at the keyboard signs up by itself: it registers, prints a code for the account owner and keeps working. The owner approves later, from any device. The agent then holds an ordinary **API key** of the owner's account (the same kind as [API keys and SDK](https://instabox.sh/docs/keys-sdk.md)), with the scopes the owner granted, and nothing exists until they approve. ### The agent's side ``` instabox login --agent # default name agent@, scopes machines:read machines:write machines:delete images:read instabox login --agent --name 'claude on ci' --scope machines:read,machines:write --expires-in-days 30 ``` It prints a claim page and a code, like ``` Ask the account owner to approve it: open https://dashboard.instabox.sh/dashboard/claim?code=KFXR-7Q2M (or https://dashboard.instabox.sh/dashboard/claim and enter the code KFXR-7Q2M) Waiting for the account owner to approve… ``` Relay the page and the code to the person and wait: the command finishes on its own once they approve, stores the key in `~/.config/instabox/credentials.json` and every later `instabox` command uses it. The code works for 24 hours. `--no-wait` prints the page and code and exits (`--json`: as JSON); `instabox login --agent` again resumes the same registration instead of printing a second code. A denial or an expired code ends with an error; register again. If the key cannot be stored (a full disk, say), the command says so without printing it and exits non-zero; run it again within 10 minutes and the server hands over the same key. A key neither used nor stored within those 10 minutes is revoked. `--json` prints the key itself (and `--no-wait --json` the claim token): keep that output out of transcripts and logs. Over HTTP: `POST /v1/auth/agent` with `{"name", "email", "scopes", "expiresInDays"}` (all optional) answers `claimToken`, `userCode`, `verificationUri`, `verificationUriComplete`, `interval` and `expiresIn`; poll `POST /v1/auth/agent/token` with `{"claimToken"}` every `interval` seconds. It answers `400 authorization_pending` until the owner decides, `slow_down` (poll less often: the server added 5 s to its interval; doubling yours catches up from any gap), `expired_token` (register again) or `access_denied` (the owner refused), then once `200` with `key` (the secret, `ibk_...`), `apiKey` (its ID, name and scopes) and the account's `userId` and `login`. Send the key as `X-API-Key` from then on. ### The owner's side Open the page the agent printed (signed out: sign in or sign up with GitHub or Google first; the page comes back). It shows the agent's name, when and from which address it registered and what it asks to do; untick permissions you do not want to give, then **Approve** or **Deny**. Or, signed in on your own computer: ``` instabox claim KFXR-7Q2M # shows what the agent asks for, then asks instabox claim KFXR-7Q2M --scope machines:read --expires-in-days 7 --yes instabox claim KFXR-7Q2M --deny ``` Only approve an agent you started yourself. The key appears on your **API keys** page under the agent's name; revoke it there or with `instabox keys rm` when the agent is done. An agent's key never manages keys, workspaces or billing, and an account holds at most 20 active keys. > Before the owner approves, the agent has no account and no credential: it cannot read or create anything. Everything it needs to plan with (templates, sizes, prices, limits) is in these docs and in `/llms.txt`. --- # MCP https://instabox.sh/docs/mcp.md Sandbox tools for Claude Code, Cursor, Codex, OpenCode and Antigravity over the Model Context Protocol, and a public server that reads these docs. The `instabox` CLI and the instabox agent skills are the main way for an agent to use sandboxes. MCP is one more way in, for a client that should call tools without a CLI. The tools are the same either way: `create_machine`, `list_machines`, `get_machine`, `exec`, `read_file`, `write_file`, `suspend_machine`, `resume_machine`, `save_snapshot`, `list_snapshots`, `delete_machine` and `get_usage`. Each answers JSON; a refused call is a tool error with the API's `code` and `message` (for example `missing_scope` and the scope it needs). ### Documentation MCP (no sign-in) `https://instabox.sh/mcp` is a public MCP server that reads these docs, so an agent can read them before anything is installed. Its tools: `list_docs` is the index, `get_doc` reads one page by id, `search_docs` finds the pages that mention something, `get_started` is the quick start. It needs no account and only reads docs; acting on sandboxes takes the hosted server at `https://api.instabox.sh/mcp` or `instabox mcp init`, below. Add it: ``` claude mcp add --scope user --transport http instabox-docs https://instabox.sh/mcp codex mcp add instabox-docs --url https://instabox.sh/mcp ``` Cursor: add `{"mcpServers":{"instabox-docs":{"url":"https://instabox.sh/mcp"}}}` to `~/.cursor/mcp.json`. OpenCode: add `{"mcp":{"instabox-docs":{"type":"remote","url":"https://instabox.sh/mcp"}}}` to `opencode.json`. The server is stateless (Streamable HTTP, JSON answers, no session, `GET /mcp` is `405`). The rest of this page is the sandbox MCP. ### Set it up ``` instabox mcp init claude # or cursor, codex, opencode, antigravity: the client runs `instabox mcp start` instabox mcp init claude --hosted # the hosted server, with the key from INSTABOX_API_KEY instabox mcp init antigravity --hosted --inline-key # Antigravity: the key goes into the file ``` Restart the client afterwards. `init` adds one server named `instabox` and keeps the rest of the file: | Client | Your config | `--project` | |---|---|---| | Claude Code | `~/.claude.json` | `./.mcp.json` | | Cursor | `~/.cursor/mcp.json` | `./.cursor/mcp.json` | | Codex | `~/.codex/config.toml` | `./.codex/config.toml` | | OpenCode | `~/.config/opencode/opencode.json` | `./opencode.json` | | Antigravity | `~/.gemini/config/mcp_config.json` | `./.agents/mcp_config.json` | With `--hosted` the file holds a reference to `INSTABOX_API_KEY` (`${INSTABOX_API_KEY}` for Claude Code, `${env:INSTABOX_API_KEY}` for Cursor, `env_http_headers` for Codex, `{env:INSTABOX_API_KEY}` for OpenCode), not the key, so the variable must be set where the client starts. `--inline-key` writes the key itself and makes the file readable by you only; keep such a file out of git. Antigravity reads no variables from its config, so `--hosted` needs `--inline-key` there. ### The hosted server URL: `https://api.instabox.sh/mcp` (Streamable HTTP). Send an API key as `X-API-Key: ibk_...` or `Authorization: Bearer ibk_...`; a signed-in CLI's access token works as a bearer too. Create a key with `instabox keys create --name mcp` or on the **API keys** page. For Claude Code by hand: ``` claude mcp add --transport http instabox https://api.instabox.sh/mcp --header "X-API-Key: $INSTABOX_API_KEY" ``` The server keeps no session: every request is one JSON-RPC message with its own credentials, there is no `Mcp-Session-Id` and no event stream (`GET /mcp` is `405`). A tool call runs the same route as the REST API, so the key's scopes, your plan, quotas and rate limits apply as they do there. ### Local: `instabox mcp start` A stdio server for clients that start a command. It sends each message to the hosted server with the CLI's credentials: `INSTABOX_API_KEY` when set, otherwise your `instabox login` sign-in, refreshed as needed. It never opens a browser; sign in once first, or set the key. ### Tools and scopes | Tool | Does | Scope | |---|---|---| | `list_machines`, `get_machine` | your sandboxes; one by ID or name | `machines:read` | | `create_machine` | from a template (default `agent-browser`) or snapshot, waits until it runs | `machines:write` | | `exec` | `argv` (no shell) or `cmd` (`bash -lc`), `timeout_seconds` up to 600; a non-zero exit is a result | `machines:write` | | `read_file`, `write_file` | up to 1 MiB; text as UTF-8, other bytes as base64 | `machines:write` | | `suspend_machine`, `resume_machine` | pause and resume, memory kept; they wait for the operation | `machines:write` | | `save_snapshot`, `list_snapshots` | save a sandbox's disks; list snapshots | `images:write`, `images:read` | | `delete_machine` | deletes it for good; `confirm` must be its ID or name | `machines:delete` | | `get_usage` | counts, running time and limits (or one sandbox's) | `machines:read` or `images:read` | A tool given a name instead of an ID looks the sandbox up first, which needs `machines:read`. Lifecycle tools wait up to 120 s by default (`wait_seconds`, at most 600: a larger value waits 600, 0 or less the default; `wait: false` returns the operation at once). `read_file` reads up to `max_bytes` (default 256 KiB, at most 1 MiB: a larger value is taken as 1 MiB, 0 or less as the default). For files over 1 MiB use `instabox cp`. --- # API keys and SDK https://instabox.sh/docs/keys-sdk.md Drive machines from code: TypeScript, Python, HTTP, or the CLI with a key. Code uses an **API key** (`ibk_...`): the TypeScript and Python SDKs, plain HTTP, the CLI and SSH all accept one. Signing in with GitHub or Google is for people, to use the dashboard and to create keys. An agent with nobody at the keyboard gets its key by itself: [Agent sign-up](https://instabox.sh/docs/agent-auth.md). ### 1. Create a key On **API keys** in the dashboard sidebar, choose **Create Key**. **Full access** suits the SDK; **Restricted** picks scopes: | Scope | Allows | |---|---| | `machines:read` | list and get machines, operations, metrics and usage; the CI jobs and stats (`instabox ci`) | | `machines:write` | create, start, stop, pause, resume, set auto-pause and labels, exec and SSH | | `machines:delete` | delete machines | | `images:read`, `images:write`, `images:delete` | list, save and delete snapshots | Write and delete include read. The SDK and CLI look names up with `images:read`, so give it to keys that create machines. The secret is shown once; revoking a key also ends its SSH certificates. Keys cannot create keys. ``` export INSTABOX_API_KEY=ibk_... export INSTABOX_API_URL=https://api.instabox.sh ``` > A key with `machines:write` can select org Secrets for a sandbox and execute code there. That code can send selected Secrets to their allowed hosts. For a fresh sandbox that should receive credentials from neither store, pass `"vault": false, "secrets": []` to the creation API. ### 2. TypeScript SDK ``` npm install @insforge/instabox-sdk ``` It reads `INSTABOX_API_KEY` and `INSTABOX_API_URL`, or takes `{ apiKey, apiUrl }` as options. ``` import { Sandbox } from '@insforge/instabox-sdk' const sbx = await Sandbox.create('agent-browser', { // a template, a snapshot name, or a snapshot ID metadata: { task: 'review' }, }) const r = await sbx.commands.run('uname -a') // throws CommandExitError on a non-zero exit console.log(r.stdout) await sbx.files.write('/data/home/notes.txt', 'hello') console.log(await sbx.files.read('/data/home/notes.txt')) await sbx.pause() // pause; memory is kept const again = await Sandbox.connect(sbx.sandboxId) // resumes it await Sandbox.list({ metadata: { task: 'review' } }) await again.kill() // delete ``` Also: `setAutoSuspend`, `setMetadata`, `stop`, `getInfo`, `sshCredentials`, `getMetrics` and `getUsage`, and `sbx.desktop` to watch and drive the desktop ([Desktop](https://instabox.sh/docs/desktop.md)). To copy a machine, save a snapshot with `createSnapshot` and pass its ID to `Sandbox.create`. Full reference: [SDK reference](https://instabox.sh/docs/sdk.md). From Python: `pip install instabox-sdk`, then [Python SDK](https://instabox.sh/docs/python-sdk.md). ### 3. HTTP Send the key as `X-API-Key` (or `Authorization: Bearer`). Lifecycle calls return an **operation**: poll it until `succeeded` or `failed` before the next change to that machine. They need an `Idempotency-Key` header (without one: `400`); reuse a key only to retry the same request. ``` H="X-API-Key: $INSTABOX_API_KEY" curl -s -H "$H" -H "Idempotency-Key: $(uuidgen)" -H 'Content-Type: application/json' \ -d '{"name": "box", "templateId": "agent-browser"}' "$INSTABOX_API_URL/v1/machines" curl -s -H "$H" "$INSTABOX_API_URL/v1/operations/op_...?wait=25s" # long poll, until "state": "succeeded" curl -s -H "$H" -H 'Content-Type: application/json' \ -d '{"cmd": "uname -a", "timeoutSeconds": 60}' "$INSTABOX_API_URL/v1/machines/m_.../exec" curl -s -H "$H" -H 'Content-Type: application/json' \ -d '{"argv": ["printf", "%s|", "a b", "$X"]}' "$INSTABOX_API_URL/v1/machines/m_.../exec" # no shell: prints a b|$X| curl -s -X DELETE -H "$H" -H "Idempotency-Key: $(uuidgen)" -H "X-Confirm-Delete: m_..." "$INSTABOX_API_URL/v1/machines/m_..." ``` `POST /v1/machines` takes `{}` (agent-browser, named `box-` and 8 random hex digits); an unknown `templateId` is `400` listing the templates your plan can create from, and a body field the API lacks is `400 unknown_field` (`"template"`: did you mean `"templateId"`?). `exec` returns `stdout`, `stderr` and `exitCode` when the command exits (after `timeoutSeconds` it is killed: 60 by default, at most 600), or streams them as the command runs with `Accept: text/event-stream` (`instabox exec --stream`); a longer job runs detached with `instabox exec --background` and `instabox jobs`. Send `cmd` (a shell string, run with `bash -lc`) or `argv` (a program and its arguments, run with no shell), not both. It takes no Idempotency-Key: a retry runs the command again. When a disk of the machine is at least 90% full, or the command failed with `No space left on device`, the result carries a `diskWarning` (`mount`, `usedPct`, `level`, `noSpace`, `message`) naming the full disk and the fix (`instabox resize --disk ` grows `/data`, live on a running machine); `instabox exec` prints it on stderr. The [API reference](https://instabox.sh/docs/api.md) explains each endpoint an API key calls. ### 4. CLI and SSH with a key With `INSTABOX_API_KEY` set, the CLI needs no login: ``` npm install -g instabox instabox create --name box --template agent-browser instabox exec box -- uname -a instabox exec --background box -- 'npm run build' # detached job: prints its ID instabox jobs logs box -f # follow it; exits with its code instabox agent prompt box --provider codex -f 'fix the failing test' # a coding agent turn, its JSONL events instabox agent steer box 'use the existing helper instead' # interrupt it and follow up instabox ssh box instabox rm --yes box instabox run -- uname -a # one-shot: create, run, delete instabox run --push . -- ls # upload this directory (git-ignored files skipped) first ``` Over plain HTTP, `POST /v1/machines/{id}/connections` with your public key (and an `Idempotency-Key`) returns the certificate and host CA. --- # CI with instabox https://instabox.sh/docs/ci.md Send GitHub Actions jobs to instabox with runs-on: instabox-medium, or run a command on instabox from any CI. Run your CI on instabox, one of two ways: | | `runs-on: instabox-medium` (recommended) | The CLI from any CI | |---|---|---| | What runs on instabox | Each job, on a fresh machine of its own | One command per step | | Setup | Install the GitHub App, change `runs-on` | An API key as a CI secret | | Works with | GitHub Actions | Any CI | | GitHub Actions minutes | None | The job's runner uses them | ### 1. runs-on: instabox-medium #### Set up On the dashboard's **CI** page, click **Connect GitHub**, then change `runs-on` in your workflow to `instabox-medium`. ![The CI page: Connect GitHub, then change runs-on to instabox-medium](images/ci-setup.webp) Each job gets a fresh Ubuntu 24.04 machine with the tools of GitHub's `ubuntu-24.04` image, deleted when the job ends. Tools and versions are those of GitHub's software list for the runner-images release the image is built from, [`ubuntu24/20261026.354`](https://github.com/actions/runner-images/blob/ubuntu24/20261026.354/images/ubuntu/Ubuntu2404-Readme.md) (a job reads it in `$ImageVersion`, and `/usr/local/lib/instabox/ci/software-list` prints what its machine has). Not installed: Haskell, Swift, Julia, CodeQL, Edge and Homebrew. The Android SDK is a trimmed one, with a single NDK (27). #### Sizes | Label | Machine | Plans | |---|---|---| | `instabox-small` | 2 vCPU, 4 GiB | Pro, Builder, Team | | `instabox-medium` | 4 vCPU, 8 GiB | Free, Pro, Builder, Team | | `instabox-large` | 8 vCPU, 16 GiB | Pro, Builder, Team | | `instabox-xlarge` | 16 vCPU, 32 GiB | Builder, Team | | `instabox-2xlarge` | 32 vCPU, 64 GiB | Team | The free plan runs `instabox-medium` only. #### See your jobs The dashboard's **CI** page and `instabox ci` list your jobs and why one waits or was refused. GitHub just shows it as queued. #### Start jobs from a snapshot A job can start from a snapshot of your own instead of a fresh machine, so your repository, toolchain and package caches are already there: ```sh instabox create --name ci-warm --template ci # then set it up: instabox ssh ci-warm instabox stop ci-warm instabox snapshot save ci-warm --name acme-warm ``` Clone your repository to `~/work//` (where `actions/checkout` puts it) before you save. Then add `-snapshot-` and the snapshot's name to the size label, in place of the size label: ```yaml jobs: test: runs-on: instabox-medium-snapshot-acme-warm ``` - The label is the job's whole `runs-on`: no size label, `self-hosted` or other label beside it. Only a job with this exact `runs-on` can run on a machine from the snapshot. - The size still sets vCPUs and memory; storage is at least the snapshot's. `instabox-medium-snapshot-sn_...` names it by ID. - Snapshots work in private repositories only, with **Run workflows from fork pull requests** off (**Settings > Actions > General**). Elsewhere jobs naming a snapshot are refused: a fork's workflow could name it too. - `instabox ci` and the **CI** page show the snapshot each job started from. - A job is refused, with the reason, when the snapshot isn't in the workspace the GitHub App is linked to, is still saving or failed, or wasn't saved from a `ci` machine. It never falls back to a fresh machine. - Keep secrets out of the snapshot: any workflow on a branch of a linked repository can name it. A job can't change the snapshot: each gets its own copy. - The snapshot keeps the runner it was saved with, and GitHub stops sending jobs to a runner more than 30 days behind its latest release. Save it again from a new `ci` machine at least once a month. ### 2. The CLI from any CI A step creates a machine, uploads the checkout, runs one command and deletes the machine. Store an API key as a CI secret: ```sh instabox keys create --name github-ci --expires-in-days 90 --json | jq -r .key | gh secret set INSTABOX_API_KEY ``` ```yaml jobs: test: runs-on: ubuntu-latest timeout-minutes: 30 env: INSTABOX_API_KEY: ${{ secrets.INSTABOX_API_KEY }} steps: - uses: actions/checkout@v4 - name: Install the instabox CLI run: npm install -g instabox - name: Run the tests run: instabox run --push . --timeout 10m -e CI=1 -- 'npm ci && npm test' ``` - The step fails when the command fails. The command can run 10 minutes at most. - Pass secrets with `-e NAME="$NAME"`. Pull requests from forks get no secrets, so the step can't run there. ### Questions #### What permissions does the GitHub App ask for? The [instabox GitHub App](https://github.com/apps/instabox-cloud) asks for: | Permission | Used for | |---|---| | Metadata: read | Required by GitHub for every App | | Actions: read | A job's branch, commit and failed step | | Administration: read and write | Registering and deleting each job's runner | | Members: read (organizations) | Checking that whoever links an organization belongs to it | Nothing on your code, pull requests, issues or workflows. #### Why Administration? GitHub only lets an App add a runner to a repository through Administration. Personal accounts have no organization-level runners, so it is the only way to run their CI. #### Don't want to grant it? - Use [the CLI from any CI](https://instabox.sh/docs/ci.md#2-the-cli-from-any-ci): no GitHub App, just an API key. - On Enterprise, we can set up a narrower App for your organization. [Contact us](https://instabox.sh/contact). --- # Android apps https://instabox.sh/docs/android.md A machine with Android 14 in it: install and test apps with adb, see the phone on the desktop. Every plan, free included. The `android` template is a machine with Android 14 running in it, for installing and testing Android apps and for agents that drive a phone. Android runs as a container on the machine's own Linux kernel. There is no emulator and no nested VM. A create boots the machine cold (a few seconds longer than `agent-browser`), Android is up about 20 seconds after the machine starts, and pause, idle pause and fork work as on any other machine. It has everything `agent-browser` has (Docker, Node.js, Python, the desktop, ...). ### Create one ``` instabox create --name phone --template android ``` - **Plans:** every plan: free and every paid plan (Pro, Builder, Team, Enterprise). - **Size:** use the default 4 vCPUs / 8 GiB or larger; smaller sizes work but are untested. Android uses 1 to 2 GiB of memory while it runs. ### adb adb is installed in the machine and finds the phone by itself once Android has booted: ``` instabox ssh phone adb devices # emulator-5554 (or 127.0.0.1:5555) adb shell getprop sys.boot_completed # 1 once Android has booted adb install app.apk adb shell input tap 360 640 adb exec-out screencap -p > screen.png ``` From your own computer, copy the APK in and install it in one go: ``` instabox push phone ./app-debug.apk instabox exec phone -- adb install app-debug.apk ``` Right after a create or a fork, Android is still booting and `adb devices` is empty. Wait for it: ``` until [ "$(docker exec instabox-android getprop sys.boot_completed 2>/dev/null)" = 1 ]; do sleep 1; done ``` Then `adb devices` lists the phone. You do not need `adb connect`: the machine connects adb to the phone once Android has booted. If `adb devices` still lists nothing, restart the adb server and it finds the phone: ``` adb kill-server adb devices ``` Do not add a second connection with `adb connect`: the same phone twice makes `adb shell` ask which one. ### See the phone Open the machine in the dashboard and choose the **Computer** tab: the phone is the **Android** window on the desktop, and takes clicks and typing like any window. An agent drives it the same way with the desktop API (screenshots, clicks, keys: [Desktop](https://instabox.sh/docs/desktop.md)) or directly with `adb shell input`. ### Pause, idle pause and fork - **Pause and resume**, and idle pause and wake, keep the same running Android: apps, their state and the clock carry on where they were. - **Fork** copies Android's data (installed apps and their data). The new machine boots its own Android from it, ready about 20 seconds later; apps that were running are not carried over. - To free Android's memory, `sudo systemctl stop instabox-android`; `sudo systemctl disable instabox-android` keeps it off across restarts. ### Limits - **No Google Play or Google services.** There is no Play Store; install apps with `adb install`. Apps that need Google services for sign-in, maps or push do not fully work. - **x86_64 only.** Apps that ship only ARM native code need ARM translation, which is not included, so they do not run. Apps with no native code, or with x86_64 libraries, run. - **Software rendering.** Fine for app testing and UI automation, slow for games and heavy 3D. - **Paid plans only** (above). --- # SDK reference https://instabox.sh/docs/sdk.md Every class, method and option of @insforge/instabox-sdk. Version 0.7.0 of `@insforge/instabox-sdk`. For a walk through the common calls, start with [Integrate with the SDK](https://instabox.sh/docs/integrate.md). ### Install and authenticate ``` npm install @insforge/instabox-sdk export INSTABOX_API_KEY=ibk_... # optional; the default is https://api.instabox.sh export INSTABOX_API_URL=https://api.instabox.sh ``` Every static call (`create`, `connect`, `list`, `kill`, the snapshot calls and the metrics and usage calls) also takes the key and URL as options, which win over the environment. A `Sandbox` object keeps its connection, so its own methods take no key. ``` import { Sandbox } from '@insforge/instabox-sdk' const sbx = await Sandbox.create('agent-browser', { apiKey: process.env.INSTABOX_API_KEY, apiUrl: 'https://api.instabox.sh', }) ``` With no key from either, the call throws `InstaboxAuthError` with code `missing_api_key` (status 0) before any request. The key is sent as the `X-API-Key` header. These connection options (`ConnectionOptions`) apply to every static call: | Option | Type | Default | |---|---|---| | `apiKey` | `string` | env `INSTABOX_API_KEY` | | `apiUrl` | `string` | env `INSTABOX_API_URL`, else `https://api.instabox.sh` | | `requestTimeoutMs` | `number` | 60 000 per HTTP request; a command gets its own timeout plus 30 000 | | `operationTimeoutMs` | `number` | 600 000: the wait for create, pause, resume and kill | | `fetch` | `typeof fetch` | the global `fetch` (Node 18+, Bun, Deno) | | `pollIntervalMs` | `number` | 250: first delay of operation polling, grows 1.5x to 1 s | | `retryDelayMs` | `number` | 250: first delay between retries | Scopes a key needs: | Scope | Allows | |---|---| | `machines:read` | `Sandbox.list`, `getInfo`, `isRunning`, `getMetrics`, `getUsage`, `Sandbox.usage` | | `machines:write` | `create`, `connect` (resume), `pause`, `resume`, `stop`, `setAutoSuspend`, `setMetadata`, `commands`, `files`, `sshCredentials` | | `machines:delete` | `kill` | | `images:read` | Resolve private snapshot names, `listSnapshots`, `getSnapshot` | | `images:write` | `createSnapshot` | | `images:delete` | `deleteSnapshot` | `:write` and `:delete` include `:read`. Creating from a snapshot name also needs `images:read`. A call outside the key's scopes throws `InstaboxAuthError` (`403 missing_scope`). ### Sandbox.create ``` Sandbox.create(opts?: SandboxOpts): Promise Sandbox.create(template: string, opts?: SandboxOpts): Promise ``` `template` is a template ID (`agent-browser`), a private snapshot name or a snapshot ID (`sn_...`). Template IDs take precedence over snapshot names. The default is `agent-browser` (`DEFAULT_TEMPLATE`), or `universal` (`FALLBACK_TEMPLATE`) on a server without it. It resolves once the machine runs; a snapshot that is still being saved is waited for, up to `operationTimeoutMs`. The free plan creates from `agent-browser`, `android`, `omarchy` or `ci` only; the other templates (`universal`, `t3`, `herdr`, `orca`) need a paid plan, and on free they are `403 template_not_allowed`. `SandboxOpts` is the connection options plus: | Option | Type | Default | |---|---|---| | `name` | `string` | `sbx-`; lowercase letters, digits and `-` | | `metadata` | `Record` | none; labels to filter `Sandbox.list` on | | `envs` | `Record` | none; added to every `commands.run` of this object (client side) | | `archiveMs` | `number` | none; maps to API `archiveSeconds`. After this many ms from create, the server **stops** a still-running machine (`archiveAt`); disks stay and a later start restores it. Not a delete; omit for no archive deadline | | `autoSuspendMs` | `number` | 30 minutes; pause after this much idle time. A paid plan takes 5-30 minutes in whole minutes (a part minute, below 5 or above 30 is refused), `0` never. The free plan always pauses after 30 idle minutes; a server from 2026-10-25 refuses another value (403, `spec_not_allowed`, a plan limit) instead of ignoring it | | `vcpus` | `number` | the template's | | `memMiB` | `number` | the template's | | `diskGiB` | `number` | the size's; the disk (`/data`), in GiB, sent as the API's `persistentDiskGiB` | | `vault` | `boolean` | `false` disables only personal Vault delivery; org Secret selections are independent | Times are sent as whole seconds. On api.instabox.sh a sandbox is 4 vCPUs and 8 GiB unless `vcpus` and `memMiB` name another size of your plan (Pro: 2/4, 4/8, 8/16; Builder: 2/4 up to 16/32; Team: 2/4 up to 32/64; `GET /v1/orgs` lists each workspace's as `allowedSpecs`). Any other size is refused with `400 spec_not_allowed`, and so is a `diskGiB` other than the disk the size comes with: leave it out. A paid sandbox's disk grows later with `PATCH /v1/machines/{id}` (see [Disk sizes](https://instabox.sh/docs/limits.md)), and its size changes while it is stopped with the same PATCH (`vcpus`, `memMiB`; see [Sizes](https://instabox.sh/docs/machines.md)). In a REST body the field is `persistentDiskGiB`; `diskGiB` there is `400 unknown_field`. The free plan creates from agent-browser, android, omarchy or ci only (`403 template_not_allowed`); a sandbox from a snapshot is not limited. **No kernel tracing, no nested KVM.** The guest kernel has the eBPF syscall and JIT (root only: unprivileged BPF is off, so use `sudo`), and socket, cgroup and XDP programs load. What it lacks is the tracing side: no kprobes, no ftrace or tracepoints, and no BTF (`/sys/kernel/btf/vmlinux` is absent), so `bpftrace`, BCC tools and `perf probe` do not work and there is nothing to attach a tracing program to. There is also no `/dev/kvm` in the guest (the kernel is a KVM guest, not a KVM host), so Firecracker, QEMU with KVM, Docker-in-VM runtimes that need it, and nested microVMs cannot run; QEMU in pure emulation (`-accel tcg`) works, slowly. ### Connect, list and kill ``` Sandbox.connect(sandboxId: string, opts?: SandboxConnectOpts) : Promise Sandbox.list(opts?: SandboxListOpts): Promise Sandbox.kill(sandboxId: string, opts?: ConnectionOptions) : Promise ``` - `connect` attaches to an existing machine and resumes it if it is paused or stopped. `resume: false` attaches without waking it. `envs` works as in `create`. - `list` returns every page of your machines. `metadata` keeps those with every given key and value. - `kill` deletes a machine and its disks. It returns `false` if the machine did not exist. ### Snapshot calls ``` Sandbox.listSnapshots(opts?: ConnectionOptions): Promise Sandbox.getSnapshot(snapshotId: string, opts?: ConnectionOptions) : Promise Sandbox.deleteSnapshot(snapshotId: string, opts?: ConnectionOptions) : Promise ``` `listSnapshots` returns your private snapshots. `deleteSnapshot` returns `false` if the snapshot was already gone. Save one with `sbx.createSnapshot`. To copy a sandbox, save a snapshot and create from it: ``` const snap = await sbx.createSnapshot({ name: 'my-setup' }) const copy = await Sandbox.create(snap.id, { vault: false }) ``` A copy uses its creation request's selections, not the source sandbox's grants. Omitting `secrets` does not enroll the copy in Secrets. `vault: false` disables only Vault delivery. To explicitly select Secrets, use the CLI or HTTP API. ### The Sandbox object | Member | Returns | What it does | |---|---|---| | `sandboxId` | `string` | The machine ID, `m_...` | | `getInfo()` | `Promise` | Fresh state from the server | | `isRunning()` | `Promise` | True if `state` is `running` | | `pause()` | `Promise` | Saves memory and suspends it | | `resume()` | `Promise` | Resumes a paused machine, or starts a stopped one | | `stop()` | `Promise` | Shuts it down; processes end, `/data` is kept | | `setAutoSuspend(idleMs: number)` | `Promise` | Idle pause; a paid plan takes 5-30 minutes in whole minutes (a part minute, below 5 or above 30 is refused), and `0` turns it off, the free plan keeps 30 minutes and refuses another value. Kept across pause and resume | | `setMetadata(metadata: Record)` | `Promise` | Replaces the labels; `{}` clears them | | `createSnapshot(opts: CreateSnapshotOpts)` | `Promise` | Saves its disks as a private snapshot | | `getMetrics(opts?: SandboxMetricsOpts)` | `Promise` | CPU and memory samples, oldest first | | `getUsage(opts?: SandboxUsageOpts)` | `Promise` | What it used over a window | | `sshCredentials(publicKey: string, opts?: { ttlSeconds?: number })` | `Promise` | A short-lived SSH certificate for `publicKey` | | `kill()` | `Promise` | Deletes it and its disks; `false` if already gone | | `commands` | `Commands` | Run shell commands | | `files` | `Files` | Read and write files | | `desktop` | `Desktop` | See and control the desktop | Lifecycle calls (`create`, `connect`, `pause`, `resume`, `stop`, `kill`) wait for the server's operation to finish, up to `operationTimeoutMs`. `getInfo()` returns a `SandboxInfo`: `sandboxId`, `templateId`, `snapshotId?`, `name`, `metadata`, `vault`, `startedAt`, `archiveAt?`, `autoSuspendMs?`, `state` and `machine` (the raw API object). `state` is one of: ``` creating starting running stopping stopped suspending suspended resuming deleting deleted error ``` A paused machine is `suspended`. The `vault` field describes personal Vault delivery. Vault inspection and push endpoints remain available independently of `GET /v1/machines/{id}/secrets`, which returns org Secret selections and delivery status. Use the [Secret CLI or HTTP API](https://instabox.sh/docs/secrets.md) to manage those selections. `CreateSnapshotOpts`: `name` (required), `description`, and `rootOnly` to save only the root disk. From a running machine the snapshot comes back with `status: 'pending'` and turns `ready` once saved. `SshCredentials`: `host`, `port`, `username` (the machine ID), `certificate` (save it as `-cert.pub`), `knownHostsLine`, `expiresAt` and `connectionId`. The machine must be running. `ttlSeconds` is 1 to 86 400; the default is 1 hour. See [SSH](https://instabox.sh/docs/ssh.md). ### sbx.commands ``` run(cmd: string, opts?: CommandOptions & { background?: false }) : Promise run(cmd: string, opts: CommandOptions & { background: true }) : Promise ``` | Option | Type | Default | |---|---|---| | `cwd` | `string` | the server's: HOME, `/data/home` | | `envs` | `Record` | none; merged over the `envs` given to `Sandbox.create` | | `timeoutMs` | `number` | the server's; sent as whole seconds, at most 600 000 | | `stdin` | `string` or `Uint8Array` | none; text or bytes, passed byte for byte. Up to 1 MiB of UTF-8 (`MAX_STDIN_BYTES`) goes in the request; more, or bytes that are not UTF-8, go up as a temporary file first (up to 5 GiB) | | `onStdout` | `(data: string) => unknown` | none; called with each chunk of stdout as the command writes it | | `onStderr` | `(data: string) => unknown` | none; the same, for stderr | | `background` | `boolean` | `false`; `true` starts it detached and returns at once | | `signal` | `AbortSignal` | none; aborting it kills the command and `run` throws `aborted`; with `background: true` it only aborts the start (the job keeps running) | The result (`CommandResult`) is `{ stdout, stderr, exitCode, timedOut, truncated, error? }`. Without callbacks the result arrives in one response, each output stream cut at 1 MiB, and `truncated` says so. With `onStdout` or `onStderr` the output is streamed: each callback is called with every chunk as the command writes it, while the command runs. A returned promise is awaited before the next chunk. `run` still resolves (or throws `CommandExitError`) with the whole `stdout` and `stderr` once the command ends; streamed output is not capped, so `truncated` is false. A callback that throws ends the command, and `run` rejects with that error. ``` // Prints 1, 2 and 3 about a second apart, as the command writes them. const r = await sbx.commands.run('for i in 1 2 3; do echo $i; sleep 1; done', { onStdout: (out) => process.stdout.write(out), onStderr: (err) => process.stderr.write(err), }) console.log(r.stdout) // "1\n2\n3\n" ``` A non-zero exit throws `CommandExitError`, which carries the same fields. A command that runs past `timeoutMs` throws it with `timedOut: true` and exit code 124. ``` import { CommandExitError } from '@insforge/instabox-sdk' try { await sbx.commands.run('exit 3') } catch (e) { if (e instanceof CommandExitError) console.log(e.exitCode, e.stderr) } ``` With `background: true`, `run` starts the command detached, as a job in its own session, and returns a `CommandHandle` at once. It is not limited to 10 minutes. - `pid`: the shell, which leads the process group. - `jobId`: the job's ID. The CLI sees the same job: `instabox jobs ls`, `instabox jobs logs -f`, `instabox jobs wait`. - `kill()`: sends SIGTERM to everything it started; returns `false` if all had exited. - `wait({ onStdout?, timeoutMs?, signal? })`: follows the job's log, calling `onStdout` with each chunk from the start, and resolves with `{ stdout, stderr: '', exitCode, timedOut: false, truncated: false }` once it ends. A background command's stdout and stderr go to one log (`~/.instabox/jobs//out`), so `stdout` holds both. A non-zero exit throws `CommandExitError`; a job that ended without an exit code (the sandbox restarted) throws `job_lost`. `timeoutMs` gives up with `InstaboxTimeoutError` (`job_wait_timeout`) and `signal` stops waiting (`aborted`); the job keeps running either way. `run` does not take `onStdout`, `onStderr` or `stdin` with `background: true`: it throws `InstaboxError` with code `bad_request`. Pass `onStdout` to `wait()` instead. Background commands need bash, util-linux `setsid` and GNU coreutils in the sandbox; without them `run` throws `background_unsupported`, naming what is missing. ``` const build = await sbx.commands.run('npm test', { background: true, cwd: '/data/home/app', }) console.log(build.jobId) // Follows the log; throws CommandExitError if the tests fail. await build.wait({ onStdout: (out) => process.stdout.write(out) }) const server = await sbx.commands.run('node server.js', { background: true, }) await server.kill() ``` `exec(cmd, opts?)` takes `cwd`, `envs`, `timeoutMs` and `stdin` and returns the `CommandResult` without throwing on a non-zero exit. It is marked internal, so prefer `run`. Commands are never retried. ### sbx.files ``` read(path: string, opts?: { format?: 'text'; maxBytes?: number }) : Promise read(path: string, opts: { format: 'bytes'; maxBytes?: number }) : Promise readStream(path: string, opts?: ReadStreamOptions): Promise write(path: string, data: WriteData, opts?: WriteOptions) : Promise upload(localDir: string, remoteDir: string, opts?: UploadOptions) : Promise download(remoteDir: string, localDir: string, opts?: DownloadOptions) : Promise list(path: string): Promise remove(path: string): Promise exists(path: string): Promise ``` - `read` loads the file into memory and returns UTF-8 text, or bytes with `{ format: 'bytes' }`. A text read of a file that is not UTF-8 throws `not_utf8`. It stops at 10 MiB (`MAX_FILE_BYTES`) with `file_too_large`: pass `maxBytes` to raise it, or use `readStream`. - `readStream` returns the file as a `ReadableStream` that also works with `for await`, with no size cap. A missing file or a directory throws `not_found` before any byte; a stream cut short errors with `file_changed`. - `write` takes a string, bytes, or a stream: a Node `Readable`, a web `ReadableStream`, or an async iterable of chunks. A stream is sent as it is read, so memory stays flat. Up to 5 GiB per file (`MAX_UPLOAD_BYTES`). It creates parent directories, checks the size and SHA-256 the server reports, and replaces the file atomically. It returns `{ path }`. Writing to a directory throws `is_a_directory`; an error from your stream throws `source_error` and leaves the old file. - `upload` puts a local directory's contents into `remoteDir` as one gzipped tar, as `instabox push` does. In a git work tree only tracked files go; `{ all: true }` adds untracked files git does not ignore, `{ git: false }` sends everything. Symlinks stay symlinks and modes are kept. It returns `{ path, files, bytes }`. - `download` brings a sandbox directory into `localDir` the same way, as `instabox pull` does: everything under it, dot files and empty directories included. It returns `{ path, remotePath, files, bytes }`. `upload` and `download` need Node.js, Bun or Deno; in a browser or a Worker they throw `unsupported`. - `list` returns `{ name, path, type }` entries, `type` being `'file'` or `'dir'`. It is not recursive. - `remove` deletes a file or a directory, recursively. A missing path is fine. `read`, `readStream` and `write` use the API's file routes (`GET /v1/machines/{id}/files/content`, `PUT /v1/machines/{id}/files`), the path `instabox cp` takes, and need the same scope as commands. `list`, `exists` and `remove` run as commands. Relative paths start at HOME, `/data/home`, on the persistent disk. ``` import { createReadStream, createWriteStream } from 'node:fs' import { Readable } from 'node:stream' import { pipeline } from 'node:stream/promises' await sbx.files.write('data.bin', createReadStream('data.bin')) await pipeline( Readable.fromWeb(await sbx.files.readStream('data.bin')), createWriteStream('copy.bin'), ) await sbx.files.upload('my-app', 'my-app') await sbx.files.download('my-app/dist', 'dist') ``` ### sbx.desktop ``` start(opts?: { width?: number; height?: number }) : Promise status(): Promise screenshot(): Promise click(x: number, y: number, opts?: { button?: MouseButton; double?: boolean }): Promise move(x: number, y: number): Promise drag(from: [number, number], to: [number, number]): Promise scroll(opts: { direction: ScrollDirection; amount?: number }) : Promise type(text: string, opts?: { delayMs?: number }): Promise press(keys: string | string[]): Promise open(url: string): Promise cursorPosition(): Promise<{ x: number; y: number }> streamUrl(opts?: { viewOnly?: boolean; ttlSeconds?: number }) : Promise revokeStreamUrls(): Promise ``` - `start` resolves once the desktop runs and leaves a running one as it is. On a template without the desktop (`universal`, `t3`) the SDK installs it first, about half a minute, once: it sends `install`, polls `status`, then sends `start`. The HTTP `start` action alone never installs. Screen: 800 to 2560 by 600 to 1600, default 1280 x 800. - `status` returns `DesktopStatus`: `installed`, `running`, and `width` and `height` while running. - `screenshot` returns a PNG of the whole screen. - `click` uses the left button unless `button` is `'right'` or `'middle'`; `double` clicks twice. Coordinates are pixels from the top left. - `drag` holds the left button. `scroll` turns the wheel at the pointer, `amount` notches (default 3), `direction` `'up'`, `'down'`, `'left'` or `'right'`. - `type` types the text as is, quotes, newlines and Unicode included, into the focused window. - `press` takes a key (`'Enter'`, `'a'`, `'F5'`) or a chord (`['ctrl', 'l']`). - `open` opens an http or https URL in the desktop's browser. Input and screenshots run commands in the machine, so a failing one throws `CommandExitError`. The desktop runs on X display `:1` (`DESKTOP_DISPLAY`). **The stream link.** `streamUrl` returns `{ url, expiresAt }`: a page that shows the desktop full-screen, to open or put in an `