@insforge/instabox-sdk 0.5.2 → 0.6.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,17 +54,15 @@ 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` (and `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
65
+ archiveMs: 24 * 60 * 60_000, // stops it at this deadline
68
66
  autoSuspendMs: 10 * 60_000, // pauses it after 10 idle minutes (default 30; 0: never, see Manual lifecycle)
69
67
  })
70
68
  console.log(sandbox.sandboxId) // m_...
@@ -72,7 +70,7 @@ console.log(sandbox.sandboxId) // m_...
72
70
 
73
71
  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
72
 
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.
73
+ `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
74
 
77
75
  ## Commands
78
76
 
@@ -100,27 +98,41 @@ try {
100
98
  }
101
99
  ```
102
100
 
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.
101
+ 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
102
 
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.
103
+ ```ts
104
+ // Prints 1, 2 and 3 about a second apart, as the command writes them.
105
+ await sandbox.commands.run('for i in 1 2 3; do echo $i; sleep 1; done', {
106
+ onStdout: (out) => process.stdout.write(out),
107
+ })
108
+ ```
109
+
110
+ The API returns `timedOut` and `truncated` flags. A command that runs past `timeoutMs` throws `CommandExitError` with `timedOut: true` and `exitCode` 124. `stdin` is limited to 1 MiB (UTF-8; a longer one throws before the request). 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.
111
+
112
+ `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
113
 
107
114
  ```ts
115
+ const build = await sandbox.commands.run('cargo test', { background: true, cwd: '/data/home/app' })
116
+ const r = await build.wait({ onStdout: (out) => process.stdout.write(out) }) // throws CommandExitError if it fails
117
+
108
118
  const server = await sandbox.commands.run('node server.js', { background: true })
109
119
  await server.kill()
110
120
  ```
111
121
 
122
+ Changed in the next release: `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`.
123
+
112
124
  ## Files
113
125
 
114
126
  ```ts
115
127
  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
128
+ const text = await sandbox.files.read('/data/home/app.js') // string; throws not_utf8 if the file is not UTF-8
117
129
  const bytes = await sandbox.files.read('/data/home/logo.png', { format: 'bytes' })
118
130
  const entries = await sandbox.files.list('/data/home') // [{ name, path, type: 'file' | 'dir' }]
119
131
  await sandbox.files.exists('/data/home/app.js') // boolean
120
132
  await sandbox.files.remove('/data/home/tmp') // files or directories
121
133
  ```
122
134
 
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.
135
+ `read` and `write` stream 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). Each read or write is capped at 10 MiB. `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.
124
136
 
125
137
  ## Lifecycle
126
138
 
@@ -130,26 +142,24 @@ await sandbox.resume() // restore the snapshot (or start a stopped machine)
130
142
  const again = await Sandbox.connect(id) // attach; resumes a paused or stopped sandbox
131
143
  const noWake = await Sandbox.connect(id, { resume: false })
132
144
 
133
- const info = await sandbox.getInfo() // { sandboxId, templateId, snapshotId?, name, metadata, vault, startedAt, endAt?, archiveAt?, onTimeout, autoSuspendMs?, state, machine }
145
+ const info = await sandbox.getInfo() // { sandboxId, templateId, snapshotId?, name, metadata, vault, startedAt, archiveAt?, autoSuspendMs?, state, machine }
134
146
  await sandbox.isRunning() // boolean
135
147
 
136
148
  const all = await Sandbox.list() // your sandboxes, as SandboxInfo[]
137
149
  const mine = await Sandbox.list({ metadata: { userId: 'u_42' } }) // all pairs must match
138
150
 
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
151
  await sandbox.setAutoSuspend(10 * 60_000) // pause after 10 idle minutes; 0 keeps it on
142
152
  await sandbox.setMetadata({ userId: 'u_42', stage: 'review' }) // replaces it; {} clears
143
153
 
144
- await sandbox.kill() // delete the machine and its disks; false if already gone
154
+ await sandbox.kill() // delete the machine and its disks (sends X-Confirm-Delete); false if already gone
145
155
  await Sandbox.kill(id)
146
156
  ```
147
157
 
148
158
  Every lifecycle call waits for its operation to finish (default limit 10 minutes, `operationTimeoutMs` to change it).
149
159
 
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.
160
+ 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. The setting stays across pause and resume.
151
161
 
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.
162
+ 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)` 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
163
 
154
164
  ### Pause, stop or kill
155
165
 
@@ -161,11 +171,11 @@ Idle pause: a new sandbox pauses after 30 idle minutes (no agent working, no ter
161
171
  | Counts toward `maxMachines` | Yes | Yes | No |
162
172
  | 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
173
 
164
- The server's own pauses (idle pause, `onTimeout: 'pause'`) are the same as `pause()`; `archiveMs` is a `stop()`.
174
+ The server's idle pause is the same as `pause()`; `archiveMs` is a `stop()`.
165
175
 
166
176
  ### Manual lifecycle: the sandbox pauses only when you pause it
167
177
 
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:
178
+ For a product that decides itself when its sandboxes run, create them 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:
169
179
 
170
180
  ```ts
171
181
  // `db` is your own store, mapping your user to their sandbox
@@ -192,7 +202,7 @@ async function findSandbox(userId: string) {
192
202
  }
193
203
  ```
194
204
 
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.
205
+ `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, keep the default idle pause instead: the sandbox then pauses itself after 30 idle minutes.
196
206
 
197
207
  ## Vault
198
208
 
@@ -201,7 +211,7 @@ The Vault holds the account's secrets on the control plane (API keys for model p
201
211
  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
212
 
203
213
  ```ts
204
- const tenant = await Sandbox.create('universal', { vault: false }) // never gets the account's items
214
+ const tenant = await Sandbox.create('agent-browser', { vault: false }) // never gets the account's items
205
215
  await sandbox.disableVault() // for good, in any state
206
216
  ```
207
217
 
@@ -332,6 +342,7 @@ const usage = await Sandbox.getUsage(sandbox.sandboxId, { from: new Date('2026-1
332
342
 
333
343
  // Your account: counts, stored bytes (per sandbox in storage.machines, measured hourly) and limits
334
344
  const account = await Sandbox.usage()
345
+ // account.cost: this month's costUSD, allowanceUSD, creditRemainingUSD, creditsUSD, ... (absent from older servers)
335
346
  ```
336
347
 
337
348
  All three need `machines:read` (`Sandbox.usage()` also works with `images:read`).
@@ -341,24 +352,32 @@ All three need `machines:read` (`Sandbox.usage()` also works with `images:read`)
341
352
 
342
353
  ## Errors
343
354
 
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`. |
355
+ | Class | When |
356
+ | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
357
+ | `InstaboxError` | Base class. `status`, `code`, `message`, `requestId`, `retryable`, `operationId` from the API error envelope. |
358
+ | `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. |
359
+ | `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`. |
360
+ | `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' }`. |
361
+ | `InstaboxTimeoutError` | A request or an operation took too long. |
362
+ | `CommandExitError` | A command exited non-zero. Carries `stdout`, `stderr`, `exitCode`. |
363
+
364
+ 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.
365
+
366
+ A failed operation (for example `no_capacity` while creating) throws `InstaboxError` with the operation's `code` and `operationId` (`InstaboxQuotaError` for a limit code).
367
+
368
+ `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.
369
+
370
+ Changed in the next release: 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
371
 
352
- A failed operation (for example `no_capacity` while creating) throws `InstaboxError` with the operation's `code` and `operationId`.
372
+ Changed in the next release: `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
373
 
354
374
  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
375
 
356
376
  ## Limits and what is not there yet
357
377
 
358
378
  - Quotas are account-specific; inspect `GET /v1/usage`. Exceeding a quota throws `InstaboxQuotaError`.
359
- - At most 32 command requests per account are in flight at once on `api.instabox.sh`, across all sandboxes (file reads count too); more throw `InstaboxQuotaError` (429, retryable). A `background: true` command counts only while it starts.
360
- - The timeout is a deadline from when it was set, not an inactivity timer.
361
- - Command output is not streamed.
379
+ - 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).
380
+ - 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.
362
381
 
363
382
  ## Agent skill
364
383