@insforge/instabox-sdk 0.5.3 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -25,21 +25,21 @@ export INSTABOX_API_URL=https://api.instabox.sh # optional, this is the defaul
25
25
  or pass it in code (options win over env vars):
26
26
 
27
27
  ```ts
28
- const sandbox = await Sandbox.create('universal', { apiKey: '...', apiUrl: 'https://...' })
28
+ const sandbox = await Sandbox.create({ apiKey: '...', apiUrl: 'https://...' })
29
29
  ```
30
30
 
31
31
  The key is sent as the `X-API-Key` header.
32
32
 
33
33
  ### Scopes
34
34
 
35
- | Scope | Allows |
36
- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
37
- | `machines:read` | `Sandbox.list`, `getInfo`, `isRunning`, `vault` |
38
- | `machines:write` | `create`, `connect` (resume), `pause`, `resume`, `stop`, `setTimeout`, `setAutoSuspend`, `setMetadata`, `disableVault`, `pushVault`, `commands`, `files`, `sshCredentials` |
39
- | `machines:delete` | `kill` |
40
- | `images:read` | Resolve private snapshot names, `listSnapshots`, `getSnapshot` |
41
- | `images:write` | `createSnapshot` |
42
- | `images:delete` | `deleteSnapshot` |
35
+ | Scope | Allows |
36
+ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
37
+ | `machines:read` | `Sandbox.list`, `getInfo`, `isRunning`, `vault` |
38
+ | `machines:write` | `create`, `connect` (resume), `pause`, `resume`, `stop`, `setAutoSuspend`, `setMetadata`, `disableVault`, `pushVault`, `commands`, `files`, `sshCredentials` |
39
+ | `machines:delete` | `kill` |
40
+ | `images:read` | Resolve private snapshot names, `listSnapshots`, `getSnapshot` |
41
+ | `images:write` | `createSnapshot` |
42
+ | `images:delete` | `deleteSnapshot` |
43
43
 
44
44
  `:write` and `:delete` imply `:read`. Creating from a template or a snapshot ID needs only machine scopes. Creating from a snapshot name also needs `images:read`. Snapshot permissions are named `images:*` by the current API. Add `images:write` and `images:delete` if your code saves and deletes snapshots. A call outside the key's scopes throws `InstaboxAuthError` (`403 insufficient_scope`).
45
45
 
@@ -54,25 +54,22 @@ console.log(r.stdout)
54
54
  await sandbox.kill()
55
55
  ```
56
56
 
57
- `Sandbox.create(template?, opts?)` takes a template ID (`universal`), a private snapshot name (`my-setup`) or a snapshot ID (`sn_...`). It defaults to `agent-browser` (universal with a desktop and browser preinstalled, which the dashboard's Computer tab shows; `universal` on a server without it). Template IDs take precedence over snapshot names. An unknown name or an ambiguous snapshot name throws before creating a machine; use an ID to select a specific snapshot.
57
+ `Sandbox.create(template?, opts?)` takes a template ID (`agent-browser`), a private snapshot name (`my-setup`) or a snapshot ID (`sn_...`). It defaults to `agent-browser` (universal with a desktop and browser preinstalled, which the dashboard's Computer tab shows; `universal` on a server without it). The free plan creates from `agent-browser`, `android` or `ci` only; the other templates (`universal`, `t3`, `herdr`, `orca`) need a paid plan, and on free they throw `403 template_not_allowed`. Template IDs take precedence over snapshot names. An unknown name or an ambiguous snapshot name throws before creating a machine; use an ID to select a specific snapshot.
58
58
 
59
59
  ```ts
60
- const sandbox = await Sandbox.create('universal', {
60
+ const sandbox = await Sandbox.create('agent-browser', {
61
61
  name: 'my-box', // default sbx-<random>; lowercase letters, digits and '-'
62
62
  envs: { NODE_ENV: 'development' }, // applied to every commands.run of this object
63
63
  metadata: { userId: 'u_42' }, // labels stored with the sandbox (plaintext: not for secrets)
64
64
  vault: false, // for a sandbox made for someone else: none of the account's Vault items
65
- timeoutMs: 30 * 60_000, // server pauses it 30 min from now (60 s to 24 h)
66
- archiveMs: 24 * 60 * 60_000, // stops it at this deadline, independent of timeout
67
- onTimeout: 'pause', // or 'kill' to delete it instead
68
- autoSuspendMs: 10 * 60_000, // pauses it after 10 idle minutes (default 30; 0: never, see Manual lifecycle)
65
+ archiveMs: 24 * 60 * 60_000, // stops it at this deadline
69
66
  })
70
67
  console.log(sandbox.sandboxId) // m_...
71
68
  ```
72
69
 
73
70
  Sizes are fixed by the service: 4 vCPU, 8 GiB memory, a 16 GiB root disk and a 20 GiB `/data` disk. The `vcpus`, `memMiB`, `diskGiB` and `rootDiskGiB` options are for other deployments; `api.instabox.sh` refuses them (`400 spec_not_allowed`).
74
71
 
75
- `create` waits for the create operation to succeed. `getInfo().machine.runtime.ready` reports guest readiness. `archiveMs` is optional (60 seconds to 24 hours) and becomes `getInfo().archiveAt`; its deadline is independent of the pause/kill timeout.
72
+ `create` waits for the create operation to succeed. `getInfo().machine.runtime.ready` reports guest readiness. `archiveMs` is optional (60 seconds to 24 hours) and becomes `getInfo().archiveAt`.
76
73
 
77
74
  ## Commands
78
75
 
@@ -100,27 +97,83 @@ try {
100
97
  }
101
98
  ```
102
99
 
103
- The API returns `timedOut` and `truncated` flags. A command that runs past `timeoutMs` throws `CommandExitError` with `timedOut: true` and `exitCode` 124. Each output stream is limited to 1 MiB, and `stdin` to 1 MiB (UTF-8; a longer one throws before the request). Command timeouts are 1–600 seconds; the default HTTP request deadline allows an additional 30 seconds for the result. An explicit `requestTimeoutMs` overrides that default. Output is not streamed: `onStdout` and `onStderr` are called once with the full output after the command finishes.
100
+ With `onStdout` or `onStderr`, the output is streamed: each callback is called with every chunk as the command writes it, while the command runs. The call still resolves (or throws `CommandExitError`) with the whole `stdout` and `stderr` once the command ends. A callback's returned promise is awaited before the next chunk. Streamed output is not capped, so `truncated` is false; without callbacks the result arrives in one response, each output stream limited to 1 MiB.
104
101
 
105
- `background: true` starts the command detached, in its own process group, and returns `{ pid, kill() }` right away. `kill()` sends SIGTERM to the command and everything it started; it returns false if they had all exited. Background commands need `setsid` in the sandbox.
102
+ ```ts
103
+ // Prints 1, 2 and 3 about a second apart, as the command writes them.
104
+ await sandbox.commands.run('for i in 1 2 3; do echo $i; sleep 1; done', {
105
+ onStdout: (out) => process.stdout.write(out),
106
+ })
107
+ ```
108
+
109
+ The API returns `timedOut` and `truncated` flags. A command that runs past `timeoutMs` throws `CommandExitError` with `timedOut: true` and `exitCode` 124. `stdin` is a string or a `Uint8Array`, and reaches the command byte for byte: up to 1 MiB of UTF-8 goes in the exec request itself, and anything else (bytes that are not UTF-8, or more than 1 MiB) is first uploaded to a temporary file in the sandbox (`/tmp/.instabox-stdin-*`, mode 0600) that the command reads and removes as it starts, as `instabox exec --stdin` does. That file goes over the file routes (up to 5 GiB), or in base64 chunks over exec on a server without them. Command timeouts are 1–600 seconds; the default HTTP request deadline, which covers the whole stream, allows an additional 30 seconds for the result. An explicit `requestTimeoutMs` overrides that default. `signal` (an `AbortSignal`) stops a command: the request is closed, which kills the command in the sandbox, and `run` throws `InstaboxError` with code `aborted`. A callback that throws also ends the command, and `run` rejects with that error.
110
+
111
+ `background: true` starts the command detached, as a job in its own session, and returns `{ pid, jobId, kill(), wait() }` right away. It is not limited to 10 minutes: use it for builds and test runs that may take longer. Its stdout and stderr go to one log in the sandbox (`~/.instabox/jobs/<jobId>/out`). `wait({ onStdout })` follows that log, calling `onStdout` with each new chunk from the start, and resolves with the whole log as `stdout` and the exit code; a non-zero exit throws `CommandExitError`. `wait({ timeoutMs })` gives up with `InstaboxTimeoutError` (code `job_wait_timeout`) and `signal` stops waiting; the job keeps running either way. `kill()` sends SIGTERM to the command and everything it started; it returns false if they had all exited. `run` does not take `onStdout` or `onStderr` together 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 (`stat`, `dd`, `base64`) in the sandbox; on an image without them `run` throws `InstaboxError` with code `background_unsupported`, naming what is missing, before starting anything. With a `requestTimeoutMs` of 5 seconds or less, `wait()` cannot long-poll and checks the log every 0.25 to 2 seconds instead. The CLI sees the same jobs: `instabox jobs ls`, `instabox jobs logs <sandbox> <jobId> -f`, `instabox jobs wait`.
106
112
 
107
113
  ```ts
114
+ const build = await sandbox.commands.run('cargo test', { background: true, cwd: '/data/home/app' })
115
+ const r = await build.wait({ onStdout: (out) => process.stdout.write(out) }) // throws CommandExitError if it fails
116
+
108
117
  const server = await sandbox.commands.run('node server.js', { background: true })
109
118
  await server.kill()
110
119
  ```
111
120
 
121
+ Changed in 0.6.0: `onStdout` and `onStderr` were called once, after the command finished, with its whole output; they are now called with each chunk as it is written. A background command's output was discarded; it is now kept in its job's log, which `wait()` and the CLI's `instabox jobs` commands read. Remove old logs with `rm -rf ~/.instabox/jobs/<jobId>`. `onStdout` or `onStderr` passed with `background: true` were ignored; they now throw `bad_request`.
122
+
112
123
  ## Files
113
124
 
114
125
  ```ts
115
- await sandbox.files.write('/data/home/app.js', 'console.log(1)') // string or Uint8Array -> { path }
116
- const text = await sandbox.files.read('/data/home/app.js') // string
126
+ await sandbox.files.write('/data/home/app.js', 'console.log(1)') // string, bytes or a stream -> { path }
127
+ const text = await sandbox.files.read('/data/home/app.js') // string; throws not_utf8 if the file is not UTF-8
117
128
  const bytes = await sandbox.files.read('/data/home/logo.png', { format: 'bytes' })
118
129
  const entries = await sandbox.files.list('/data/home') // [{ name, path, type: 'file' | 'dir' }]
119
130
  await sandbox.files.exists('/data/home/app.js') // boolean
120
131
  await sandbox.files.remove('/data/home/tmp') // files or directories
121
132
  ```
122
133
 
123
- Files go over the command channel as base64 in bounded chunks. Each read or write is capped at 10 MiB. Truncated file output raises an error. `write` creates parent directories and replaces the file atomically; writing to a path that is a directory throws `InstaboxError` with code `is_a_directory`. Relative paths are relative to HOME. HOME is `/data/home`, on the persistent disk.
134
+ Large files, whole directories and binary stdin (the paths are relative to HOME in the sandbox, and to the current directory locally):
135
+
136
+ <!-- verbatim: test/readme-transfer.test.ts runs this block as written -->
137
+
138
+ ```ts
139
+ import { createReadStream, createWriteStream } from 'node:fs'
140
+ import { readFile } from 'node:fs/promises'
141
+ import { Readable } from 'node:stream'
142
+ import { pipeline } from 'node:stream/promises'
143
+
144
+ // Stream a file of any size (up to 5 GiB) in, and back out, without holding it in memory.
145
+ await sandbox.files.write('dataset.bin', createReadStream('dataset.bin'))
146
+ await pipeline(Readable.fromWeb(await sandbox.files.readStream('dataset.bin')), createWriteStream('copy.bin'))
147
+
148
+ // A whole directory, one call each way.
149
+ const up = await sandbox.files.upload('my-app', 'my-app') // { path: '/data/home/my-app', files, bytes }
150
+ const down = await sandbox.files.download('my-app/dist', 'dist') // { path: 'dist', remotePath, files, bytes }
151
+
152
+ // Bytes on stdin arrive exactly as sent.
153
+ const logo = await readFile('logo.png')
154
+ const { stdout } = await sandbox.commands.run('sha256sum', { stdin: new Uint8Array(logo) })
155
+ ```
156
+
157
+ `read`, `readStream` and `write` move the bytes in one request each over the API's file routes (`GET /v1/machines/{id}/files/content` and `PUT /v1/machines/{id}/files`), the path `instabox cp` uses, as the sandbox's user. Measured from us-west on 2026-10-30: about 1.3 s to write and 1.4 s to read 3 MiB, and under 3 s each for 10 MiB. A server without those routes gets base64 chunks over exec (about 21 s per MiB written), and there a write is capped at 10 MiB.
158
+
159
+ `write` takes a string, a `Uint8Array` (or `Buffer`, `ArrayBuffer`), or a stream: a Node `Readable` (`fs.createReadStream`), a web `ReadableStream`, or any `AsyncIterable` of `Uint8Array` or string chunks (an async generator). A stream is sent as it is read, so memory stays flat whatever its size: 100 MiB moved with about 6 MiB of chunks alive at once (test/stream-memory.test.ts holds it under 16 MiB). The server takes up to 5 GiB per file (`MAX_UPLOAD_BYTES`; `too_large` past it) and drops a transfer that moves nothing for 60 seconds; the SDK gives up on a streamed write that moves nothing for 2 minutes (`InstaboxTimeoutError`, `request_timeout`). A stream can be sent only once, so a streamed write is never retried; bytes are, on 502 to 504. An error thrown by your stream rejects `write` with `InstaboxError` code `source_error` (the original as `cause`), and the file keeps its old content. `signal` stops a write (`aborted`).
160
+
161
+ `read` loads the file into memory and is capped at 10 MiB by default (`file_too_large`): pass `maxBytes` to raise it, or use `readStream`. `readStream(path)` resolves once the file is open, to a `ReadableStream<Uint8Array>` that is also async-iterable (`for await`), with no size cap; in Node, `Readable.fromWeb(stream)` makes it a Node stream. A missing file or a directory rejects the promise with `not_found` before any byte; a stream that ends short of the file's size errors with `file_changed`.
162
+
163
+ `write` creates parent directories, checks the size and SHA-256 the server reports (`transfer_mismatch` when they differ) and replaces the file atomically; an existing file keeps its mode, a new one gets 0644. Writing to a path that is a directory throws `InstaboxError` with code `is_a_directory`; reading a missing path or a directory throws `not_found`. `read` returns a string only for valid UTF-8: a file with other bytes (an image, an archive, a compiled binary) throws `InstaboxNotUtf8Error` (code `not_utf8`, status 0, "file is not UTF-8 text; read it with { format: 'bytes' }") and never a string with U+FFFD in place of the bad bytes. Read such a file with `{ format: 'bytes' }`, which returns its exact bytes. Relative paths are relative to HOME (one exec looks it up, once per sandbox object). HOME is `/data/home`, on the persistent disk. `list`, `exists` and `remove` run over exec.
164
+
165
+ ### Directories: `upload` and `download`
166
+
167
+ `files.upload(localDir, remoteDir)` puts the contents of a local directory into `remoteDir`, and `files.download(remoteDir, localDir)` the contents of a sandbox directory into `localDir`, in one call each. They move one gzipped tar the way `instabox push` and `instabox pull` do: `upload` packs it locally as it streams it to a temporary file in the sandbox (`/tmp/.instabox-transfer-*`) over `PUT /v1/machines/{id}/files`, then unpacks it there with `tar`; `download` packs the directory with `tar` in the sandbox (as root when sudo allows it, as the file routes read), streams the archive back over `GET /v1/machines/{id}/files/content` and unpacks it as it arrives. Neither holds the archive in memory, and the temporary file is removed. On a server without the file routes the archive moves in base64 chunks over exec instead.
168
+
169
+ - What `upload` sends: in a git work tree, only the files git tracks (`git ls-files`), as `instabox push` does; `{ all: true }` adds untracked files git does not ignore, and `{ git: false }` sends everything under the directory. Outside a git work tree, or with `git: false`, everything is sent, dot files and empty directories included. Git does not track empty directories, so in a work tree they are not sent.
170
+ - What `download` brings: everything under `remoteDir`, dot files and empty directories included.
171
+ - Symlinks are copied as symlinks (their target text as is), never followed. Sockets, FIFOs and devices are skipped. File and directory permission bits are kept; owners are not (files belong to the user that unpacks them).
172
+ - The destination and its parents are created. Existing files there are replaced; files the archive does not name are kept (a merge, not a mirror).
173
+ - `download` refuses an archive entry that would land outside `localDir` (an absolute path, `..`, or a path through a symlink), with `invalid_response`.
174
+ - Both return a summary: `upload` resolves to `{ path, files, bytes }` (the resolved sandbox directory, regular files sent, archive size); `download` to `{ path, remotePath, files, bytes }`.
175
+ - Errors: a missing local directory throws `local_not_found`, a local error `local_io_error`; a missing sandbox directory `not_found` (404); a file where a directory was expected `not_a_directory`; a failure of `tar` in the sandbox `transfer_failed` (`permission_denied`, 403, when it was refused access). Every error is an `InstaboxError`.
176
+ - They need Node.js (or Bun, Deno) for the local file system; in a browser or a Worker they throw `unsupported`. `read`, `readStream`, `write` and everything else work there too.
124
177
 
125
178
  ## Lifecycle
126
179
 
@@ -130,26 +183,24 @@ await sandbox.resume() // restore the snapshot (or start a stopped machine)
130
183
  const again = await Sandbox.connect(id) // attach; resumes a paused or stopped sandbox
131
184
  const noWake = await Sandbox.connect(id, { resume: false })
132
185
 
133
- const info = await sandbox.getInfo() // { sandboxId, templateId, snapshotId?, name, metadata, vault, startedAt, endAt?, archiveAt?, onTimeout, autoSuspendMs?, state, machine }
186
+ const info = await sandbox.getInfo() // { sandboxId, templateId, snapshotId?, name, metadata, vault, startedAt, archiveAt?, autoSuspendMs?, state, machine }
134
187
  await sandbox.isRunning() // boolean
135
188
 
136
189
  const all = await Sandbox.list() // your sandboxes, as SandboxInfo[]
137
190
  const mine = await Sandbox.list({ metadata: { userId: 'u_42' } }) // all pairs must match
138
191
 
139
- await sandbox.setTimeout(10 * 60_000) // pause 10 min from now; setTimeout(0) clears it
140
- await sandbox.setTimeout(60_000, { onTimeout: 'kill' })
141
- await sandbox.setAutoSuspend(10 * 60_000) // pause after 10 idle minutes; 0 keeps it on
192
+ await sandbox.setAutoSuspend(10 * 60_000) // paid plan: pause after 10 idle minutes; 0 keeps it on (free plan: 403)
142
193
  await sandbox.setMetadata({ userId: 'u_42', stage: 'review' }) // replaces it; {} clears
143
194
 
144
- await sandbox.kill() // delete the machine and its disks; false if already gone
195
+ await sandbox.kill() // delete the machine and its disks (sends X-Confirm-Delete); false if already gone
145
196
  await Sandbox.kill(id)
146
197
  ```
147
198
 
148
199
  Every lifecycle call waits for its operation to finish (default limit 10 minutes, `operationTimeoutMs` to change it).
149
200
 
150
- A timeout is enforced by the server: at `endAt` it suspends the sandbox (`onTimeout: 'pause'`, resume it with `Sandbox.connect`) or deletes it (`'kill'`). It fires once and is then cleared, so a resumed sandbox runs without a timeout until you set one again. Without `timeoutMs` there is no deadline.
201
+ Idle pause: a new sandbox pauses after 30 idle minutes (no agent working, no terminal use, little CPU) and resumes on the next `commands.run`, file read or SSH sign-in, processes and memory intact. On a paid plan, `autoSuspendMs` sets another idle time (5 to 30 minutes, in whole minutes) or 0 (never) and `setAutoSuspend(ms)` changes it later; the free plan keeps 30 minutes and refuses any other value with a 403, so leave both out there. The dashboard always uses 30 minutes. `getInfo().autoSuspendMs` shows what applies. The setting stays across pause and resume.
151
202
 
152
- Idle pause: a new sandbox pauses after 30 idle minutes (no agent working, no terminal use, little CPU) and resumes on the next `commands.run`, file read or SSH sign-in, processes and memory intact. `autoSuspendMs` sets another idle time or 0 (never), `setAutoSuspend(ms)` changes it later and the dashboard always uses 30 minutes. `getInfo().autoSuspendMs` shows what applies. Unlike a timeout the setting stays across pause and resume.
203
+ No lifetime timeout: since 0.6.0 (server change of 2026-10-20) a sandbox has no timeout that pauses or deletes it a fixed time after creation. Passing the 0.5 options `timeoutMs` or `onTimeout`, or calling `setTimeout()`, throws `InstaboxError` with code `retired_option` before any request, so code written for 0.5 fails instead of leaving sandboxes running. Use `autoSuspendMs` / `setAutoSuspend(ms)` (paid plan) for the idle pause, `archiveMs` to stop and archive a sandbox a set time after creation, and `kill()` in a `finally` block to delete it when you are done.
153
204
 
154
205
  ### Pause, stop or kill
155
206
 
@@ -161,16 +212,17 @@ Idle pause: a new sandbox pauses after 30 idle minutes (no agent working, no ter
161
212
  | Counts toward `maxMachines` | Yes | Yes | No |
162
213
  | Use it for | A break: the user comes back to the same session | Done for now: free memory, keep the files | Done for good |
163
214
 
164
- The server's own pauses (idle pause, `onTimeout: 'pause'`) are the same as `pause()`; `archiveMs` is a `stop()`.
215
+ The server's idle pause is the same as `pause()`; `archiveMs` is a `stop()`.
165
216
 
166
- ### Manual lifecycle: the sandbox pauses only when you pause it
217
+ ### Manual lifecycle: the sandbox pauses only when you pause it (paid plan)
167
218
 
168
- For a product that decides itself when its sandboxes run, create them with `autoSuspendMs: 0`: the sandbox never pauses for idleness, and no timeout or archive deadline is set unless you pass one. It runs until your code pauses, stops or kills it, so keep its ID:
219
+ For a product that decides itself when its sandboxes run, create them on a paid plan with `autoSuspendMs: 0`: the sandbox never pauses for idleness, and no archive deadline is set unless you pass one. It runs until your code pauses, stops or kills it, so keep its ID. A free-plan key gets a 403 for `autoSuspendMs: 0`; there, create without it (the free-plan line below): the sandbox also pauses itself after 30 idle minutes, and `Sandbox.connect(id)` resumes it.
169
220
 
170
221
  ```ts
171
222
  // `db` is your own store, mapping your user to their sandbox
172
223
  async function start(userId: string) {
173
- const box = await Sandbox.create({ autoSuspendMs: 0, metadata: { userId } })
224
+ const box = await Sandbox.create({ autoSuspendMs: 0, metadata: { userId } }) // paid plan
225
+ // free plan: const box = await Sandbox.create({ metadata: { userId } })
174
226
  await db.saveSandbox(userId, box.sandboxId) // m_...
175
227
  }
176
228
 
@@ -192,7 +244,7 @@ async function findSandbox(userId: string) {
192
244
  }
193
245
  ```
194
246
 
195
- `Sandbox.connect(id)` without `resume: false` resumes a paused or stopped sandbox, so use it when the user comes back, not to pause. A sandbox your code paused stays paused: commands, file reads and SSH do not wake it, only `resume()` or `connect()`. An existing sandbox switches with `setAutoSuspend(0)`. If your process can die before it pauses a sandbox, add a backstop: `setTimeout(4 * 60 * 60_000)` pauses it 4 hours from now (`{ onTimeout: 'kill' }` deletes it), and calling it again pushes the deadline out.
247
+ `Sandbox.connect(id)` without `resume: false` resumes a paused or stopped sandbox, so use it when the user comes back, not to pause. A sandbox your code paused stays paused: commands, file reads and SSH do not wake it, only `resume()` or `connect()`. On a paid plan an existing sandbox switches with `setAutoSuspend(0)`. If your process can die before it pauses a sandbox, keep the default idle pause instead: the sandbox then pauses itself after 30 idle minutes.
196
248
 
197
249
  ## Vault
198
250
 
@@ -201,7 +253,7 @@ The Vault holds the account's secrets on the control plane (API keys for model p
201
253
  What an API key can do is keep a sandbox out of it, which **a program creating sandboxes for other people must do**: anything running in a sandbox can read what the Vault writes into it.
202
254
 
203
255
  ```ts
204
- const tenant = await Sandbox.create('universal', { vault: false }) // never gets the account's items
256
+ const tenant = await Sandbox.create('agent-browser', { vault: false }) // never gets the account's items
205
257
  await sandbox.disableVault() // for good, in any state
206
258
  ```
207
259
 
@@ -290,9 +342,10 @@ A product that gives each of its users a computer they watch, or drive, in its o
290
342
  // your own records, never take it from the browser: the API key controls
291
343
  // every sandbox of the account.
292
344
 
293
- // sign-up: one sandbox per user, without your account's Vault, paused only by you
345
+ // sign-up: one sandbox per user, without your account's Vault
294
346
  async function onSignUp(userId: string) {
295
- const box = await Sandbox.create({ vault: false, autoSuspendMs: 0, metadata: { userId } })
347
+ const box = await Sandbox.create({ vault: false, metadata: { userId } })
348
+ // paid plan: add autoSuspendMs: 0 so it pauses only when you pause it
296
349
  await db.saveSandbox(userId, box.sandboxId)
297
350
  }
298
351
 
@@ -328,37 +381,47 @@ const samples = await sandbox.getMetrics({ since: new Date(Date.now() - 15 * 60_
328
381
 
329
382
  // What the sandbox used, for billing your own customers (default: this calendar month, UTC, to now)
330
383
  const usage = await Sandbox.getUsage(sandbox.sandboxId, { from: new Date('2026-10-01T00:00:00Z') })
331
- // { from, to, runningSeconds, vcpuSeconds, memGiBSeconds, diskGiBSeconds }
384
+ // { from, to, runningSeconds, vcpuSeconds, memGiBSeconds, diskGiBSeconds, egressBytes }
332
385
 
333
386
  // Your account: counts, stored bytes (per sandbox in storage.machines, measured hourly) and limits
334
387
  const account = await Sandbox.usage()
388
+ // account.cost: this month's costUSD, allowanceUSD, creditRemainingUSD, creditsUSD, ... (absent from older servers)
335
389
  ```
336
390
 
337
391
  All three need `machines:read` (`Sandbox.usage()` also works with `images:read`).
338
392
 
339
393
  - Metrics are measured on the host: `cpuUsedPct` is CPU time over the sandbox's vCPUs (0-100), `memUsed` the guest memory it has touched, in bytes. `diskUsed` is not reported yet. The list is empty while the sandbox is not running.
340
- - `runningSeconds` counts time running, not paused or stopped; `vcpuSeconds` and `memGiBSeconds` multiply it by the sandbox's size. `diskGiBSeconds` is its disk size (system disk plus `/data`) times the time it existed in the window, paused or stopped included. Running time is recorded from the server release that added this route; earlier time is not counted. A deleted sandbox's usage stays readable by its ID.
394
+ - `runningSeconds` counts time running, not paused or stopped; `vcpuSeconds` and `memGiBSeconds` multiply it by the sandbox's size. `diskGiBSeconds` is its disk size (system disk plus `/data`) times the time it existed in the window, paused or stopped included. `egressBytes` is what it sent to the public internet, counted by the hour (every hour from the one `from` falls in up to `to`), billed or not; absent from servers before it. Running time is recorded from the server release that added this route; earlier time is not counted. A deleted sandbox's usage stays readable by its ID.
341
395
 
342
396
  ## Errors
343
397
 
344
- | Class | When |
345
- | ---------------------- | ------------------------------------------------------------------------------------------------------------- |
346
- | `InstaboxError` | Base class. `status`, `code`, `message`, `requestId`, `retryable`, `operationId` from the API error envelope. |
347
- | `InstaboxAuthError` | 401 / 403: invalid or revoked API key, or no access. No API key at all: code `missing_api_key`, status 0. |
348
- | `InstaboxQuotaError` | 429 `quota_exceeded`, for example the machine limit. |
349
- | `InstaboxTimeoutError` | A request or an operation took too long. |
350
- | `CommandExitError` | A command exited non-zero. Carries `stdout`, `stderr`, `exitCode`. |
398
+ | Class | When |
399
+ | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
400
+ | `InstaboxError` | Base class. `status`, `code`, `message`, `requestId`, `retryable`, `operationId` from the API error envelope. |
401
+ | `InstaboxAuthError` | 401 / 403 that is not a plan limit: invalid, expired or revoked API key, missing scope, or no access (`permission_denied`). No API key at all: code `missing_api_key`, status 0. |
402
+ | `InstaboxQuotaError` | A quota, plan or billing limit (the CLI's exit code 5): any code in `LIMIT_CODES` whatever the status, and any other 402 or 429. For example 403 `template_not_allowed`, 400 `spec_not_allowed`, 402 `credit_exhausted`, 429 `quota_exceeded`. |
403
+ | `InstaboxNotUtf8Error` | `files.read` in the default text format met bytes that are not valid UTF-8: code `not_utf8`, status 0. Read the file with `{ format: 'bytes' }`. |
404
+ | `InstaboxTimeoutError` | A request or an operation took too long. |
405
+ | `CommandExitError` | A command exited non-zero. Carries `stdout`, `stderr`, `exitCode`. |
406
+
407
+ An option or method the SDK no longer has (`timeoutMs`, `onTimeout`, `setTimeout()`) throws `InstaboxError` with code `retired_option` and status 0; the message names what replaces it.
408
+
409
+ A failed operation (for example `no_capacity` while creating) throws `InstaboxError` with the operation's `code` and `operationId` (`InstaboxQuotaError` for a limit code).
410
+
411
+ `LIMIT_CODES` (exported, with `isLimitCode(code)`) lists the limit codes: `quota_exceeded`, `credit_exhausted`, `spend_limit_reached`, `subscription_required`, `payment_method_required`, `payment_failed`, `template_limit`, `template_not_allowed`, `spec_not_allowed`, `concurrency_limit`, `rate_limited`. A new API key does not fix them; a plan change, lower usage or (for `rate_limited` and `concurrency_limit`) waiting does.
412
+
413
+ Changed in 0.6.0: a limit code returned with 401 or 403 (`template_not_allowed`, `template_limit`) threw `InstaboxAuthError` and now throws `InstaboxQuotaError`; a limit code with another status (402 `credit_exhausted`, 400 `spec_not_allowed`) threw `InstaboxError` and now throws `InstaboxQuotaError`. Both are still `InstaboxError`, and 429 is unchanged. Code that caught `InstaboxAuthError` for a plan limit should catch `InstaboxQuotaError` or check `err.code`.
351
414
 
352
- A failed operation (for example `no_capacity` while creating) throws `InstaboxError` with the operation's `code` and `operationId`.
415
+ Changed in 0.6.0: `files.read` of a file that is not valid UTF-8 returned a string with U+FFFD in place of the bad bytes, silently; it now throws `InstaboxNotUtf8Error` (code `not_utf8`). Valid UTF-8 text and `{ format: 'bytes' }` reads are unchanged.
353
416
 
354
417
  Reads, and mutations (which always carry an `Idempotency-Key`), are retried up to 3 times with backoff on 502, 503, 504 and network errors. Commands send no `Idempotency-Key` and are not retried.
355
418
 
356
419
  ## Limits and what is not there yet
357
420
 
358
421
  - Quotas are account-specific; inspect `GET /v1/usage`. Exceeding a quota throws `InstaboxQuotaError`.
359
- - At most 32 requests per user run at once, across all your sandboxes. Commands, file reads, desktop, port-forward and vault-push calls share this limit. A `background: true` command counts only while it starts. More throw `InstaboxQuotaError` (429, retryable).
360
- - The timeout is a deadline from when it was set, not an inactivity timer.
361
- - Command output is not streamed.
422
+ - At most 32 requests per user run at once, across all your sandboxes. Commands, file reads, desktop, port-forward and vault-push calls share this limit. A `background: true` command counts only while it starts; each `wait()` holds one while it waits (it polls the job's log, up to 25 seconds per request). More throw `InstaboxQuotaError` (429, retryable).
423
+ - A command started with `run` runs for at most 10 minutes; longer ones need `background: true`. A background command takes no `stdin`, and its stdout and stderr share one log.
424
+ - A file moves at up to 5 GiB per `write` (the server's limit) in one request; the CLI's `instabox push` splits a file of 64 MiB or more into 4 parallel uploads, which the SDK does not do yet.
362
425
 
363
426
  ## Agent skill
364
427