@insforge/instabox-sdk 0.1.1 → 0.2.1

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
@@ -17,7 +17,7 @@ Create an API key on the **API Keys** page of the instabox dashboard (or `instab
17
17
 
18
18
  ```bash
19
19
  export INSTABOX_API_KEY=...
20
- export INSTABOX_API_URL=https://api.box.instacloud.com # optional, this is the default
20
+ export INSTABOX_API_URL=https://api.instabox.sh # optional, this is the default
21
21
  ```
22
22
 
23
23
  or pass it in code (options win over env vars):
@@ -30,14 +30,14 @@ The key is sent as the `X-API-Key` header.
30
30
 
31
31
  ### Scopes
32
32
 
33
- | Scope | Allows |
34
- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
35
- | `machines:read` | `Sandbox.list`, `getInfo`, `isRunning` |
36
- | `machines:write` | `create`, `connect` (resume), `pause`, `resume`, `stop`, `fork`, `setTimeout`, `setMetadata`, `commands`, `files`, `sshCredentials` |
37
- | `machines:delete` | `kill` |
38
- | `images:read` | Resolve private snapshot names, `listSnapshots`, `getSnapshot` |
39
- | `images:write` | `createSnapshot` |
40
- | `images:delete` | `deleteSnapshot` |
33
+ | Scope | Allows |
34
+ | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
35
+ | `machines:read` | `Sandbox.list`, `getInfo`, `isRunning`, `vault` |
36
+ | `machines:write` | `create`, `connect` (resume), `pause`, `resume`, `stop`, `fork`, `setTimeout`, `setMetadata`, `disableVault`, `pushVault`, `commands`, `files`, `sshCredentials` |
37
+ | `machines:delete` | `kill` |
38
+ | `images:read` | Resolve private snapshot names, `listSnapshots`, `getSnapshot` |
39
+ | `images:write` | `createSnapshot` |
40
+ | `images:delete` | `deleteSnapshot` |
41
41
 
42
42
  `: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`).
43
43
 
@@ -46,30 +46,30 @@ The key is sent as the `X-API-Key` header.
46
46
  ```ts
47
47
  import { Sandbox } from '@insforge/instabox-sdk'
48
48
 
49
- const sandbox = await Sandbox.create('universal')
49
+ const sandbox = await Sandbox.create() // agent-browser
50
50
  const r = await sandbox.commands.run('node -v')
51
51
  console.log(r.stdout)
52
52
  await sandbox.kill()
53
53
  ```
54
54
 
55
- `Sandbox.create(template?, opts?)` takes a template ID (`universal`), a private snapshot name (`my-setup`) or a snapshot ID (`sn_...`). It defaults to `universal`. 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.
55
+ `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.
56
56
 
57
57
  ```ts
58
58
  const sandbox = await Sandbox.create('universal', {
59
- name: 'my-box', // default sbx-<random>
60
- vcpus: 4, // defaults: the template's
61
- memMiB: 8192,
62
- rootDiskGiB: 32,
63
- diskGiB: 20, // persistent /data disk
59
+ name: 'my-box', // default sbx-<random>; lowercase letters, digits and '-'
64
60
  envs: { NODE_ENV: 'development' }, // applied to every commands.run of this object
65
61
  metadata: { userId: 'u_42' }, // labels stored with the sandbox (plaintext: not for secrets)
62
+ vault: false, // for a sandbox made for someone else: none of the account's Vault items
66
63
  timeoutMs: 30 * 60_000, // server pauses it 30 min from now (60 s to 24 h)
67
64
  archiveMs: 24 * 60 * 60_000, // stops it at this deadline, independent of timeout
68
65
  onTimeout: 'pause', // or 'kill' to delete it instead
66
+ autoSuspendMs: 10 * 60_000, // pauses it after 10 idle minutes (default 30; 0: never)
69
67
  })
70
68
  console.log(sandbox.sandboxId) // m_...
71
69
  ```
72
70
 
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`).
72
+
73
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`; its deadline is independent of the pause/kill timeout.
74
74
 
75
75
  ## Commands
@@ -98,9 +98,9 @@ try {
98
98
  }
99
99
  ```
100
100
 
101
- The API returns `timedOut` and `truncated` flags. Each output stream is limited to 1 MiB. 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
+ 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.
102
102
 
103
- `background: true` starts the command detached and returns `{ pid, kill() }` right away:
103
+ `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.
104
104
 
105
105
  ```ts
106
106
  const server = await sandbox.commands.run('node server.js', { background: true })
@@ -118,7 +118,7 @@ await sandbox.files.exists('/data/home/app.js') // boolean
118
118
  await sandbox.files.remove('/data/home/tmp') // files or directories
119
119
  ```
120
120
 
121
- 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. HOME is `/data/home`, on the persistent disk.
121
+ 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.
122
122
 
123
123
  ## Lifecycle
124
124
 
@@ -128,7 +128,7 @@ await sandbox.resume() // restore the snapshot (or start a stopped machine)
128
128
  const again = await Sandbox.connect(id) // attach; resumes a paused or stopped sandbox
129
129
  const noWake = await Sandbox.connect(id, { resume: false })
130
130
 
131
- const info = await sandbox.getInfo() // { sandboxId, templateId, snapshotId?, name, metadata, startedAt, endAt?, archiveAt?, onTimeout, state, machine }
131
+ const info = await sandbox.getInfo() // { sandboxId, templateId, snapshotId?, name, metadata, vault, startedAt, endAt?, archiveAt?, onTimeout, autoSuspendMs?, state, machine }
132
132
  await sandbox.isRunning() // boolean
133
133
 
134
134
  const all = await Sandbox.list() // your sandboxes, as SandboxInfo[]
@@ -136,6 +136,7 @@ const mine = await Sandbox.list({ metadata: { userId: 'u_42' } }) // all pairs m
136
136
 
137
137
  await sandbox.setTimeout(10 * 60_000) // pause 10 min from now; setTimeout(0) clears it
138
138
  await sandbox.setTimeout(60_000, { onTimeout: 'kill' })
139
+ await sandbox.setAutoSuspend(10 * 60_000) // pause after 10 idle minutes; 0 keeps it on
139
140
  await sandbox.setMetadata({ userId: 'u_42', stage: 'review' }) // replaces it; {} clears
140
141
 
141
142
  await sandbox.kill() // delete the machine and its disks; false if already gone
@@ -144,7 +145,9 @@ await Sandbox.kill(id)
144
145
 
145
146
  Every lifecycle call waits for its operation to finish (default limit 10 minutes, `operationTimeoutMs` to change it).
146
147
 
147
- 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` a sandbox runs until you pause or kill it.
148
+ 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.
149
+
150
+ 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: 0` makes a sandbox that stays on (a server that must keep answering), another value changes the idle time, `setAutoSuspend(ms)` changes it later and `getInfo().autoSuspendMs` shows it. Unlike a timeout the setting stays across pause and resume.
148
151
 
149
152
  ### Fork
150
153
 
@@ -154,12 +157,33 @@ const copy = await sandbox.fork({ name: 'copy' })
154
157
 
155
158
  A fork copies the root disk and `/data`, including credentials kept under HOME. InstaBox forks only stopped machines, so `fork()` first stops a running or paused source (its processes end, `/data` is kept) and leaves it stopped; call `sandbox.resume()` to start it again. Pass `stopSource: false` to fail instead.
156
159
 
160
+ ## Vault
161
+
162
+ The Vault holds the account's secrets on the control plane (API keys for model providers, a `.env`, a service-account file) and writes them into every sandbox of the account when it boots or resumes: `env` items become environment variables of every login shell (so of `commands.run` too), `file` items become files under the home directory. Items are managed by a person, on the dashboard's Vault page or with `instabox vault set`; an API key cannot read, create or change them.
163
+
164
+ 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.
165
+
166
+ ```ts
167
+ const tenant = await Sandbox.create('universal', { vault: false }) // never gets the account's items
168
+ const copy = await sandbox.fork({ vault: false })
169
+ await sandbox.disableVault() // for good, in any state
170
+ ```
171
+
172
+ `vault: false` is for good: such a sandbox, and its forks, never get items. On a sandbox that takes the Vault:
173
+
174
+ ```ts
175
+ const v = await sandbox.vault() // { enabled, items: [{ name, kind, path? }], applied: { at, env, files, removed?, kept?, error? } | null }
176
+ const applied = await sandbox.pushVault() // write the current items now (the sandbox must be running)
177
+ console.log((await sandbox.getInfo()).vault) // true
178
+ ```
179
+
180
+ An item's selector limits it to sandboxes whose metadata has those labels, so `metadata` at creation chooses which items a sandbox gets. A write happens at every boot, start and resume and on `pushVault()`; after a resume a changed `env` item reaches new login shells only. `vault()` and `pushVault()` throw `not_found` on a server without the Vault.
181
+
157
182
  ## Snapshots
158
183
 
159
- Save a stopped sandbox's root and `/data` disks as a private snapshot. The source must be stopped explicitly. `rootOnly: true` saves only the root disk. Snapshot methods use `/v1/snapshots` and `/v1/machines/{id}/snapshots`.
184
+ Save a sandbox's root and `/data` disks as a private snapshot. The sandbox may be running or stopped. From a running sandbox the snapshot comes back with `status: 'pending'` and turns `ready` once saved; `Sandbox.create(snapshot.id)` waits for that (it retries the server's `409 operation_conflict` "still being saved", up to `operationTimeoutMs`). `rootOnly: true` saves only the root disk. Snapshot methods use `/v1/snapshots` and `/v1/machines/{id}/snapshots`.
160
185
 
161
186
  ```ts
162
- await sandbox.stop()
163
187
  const snapshot = await sandbox.createSnapshot({ name: 'my-setup', description: 'Prepared workspace' })
164
188
  const restored = await Sandbox.create(snapshot.id)
165
189
  try {
@@ -190,14 +214,14 @@ appendFileSync(`${homedir()}/.ssh/known_hosts`, ssh.knownHostsLine + '\n')
190
214
  console.log(`ssh -p ${ssh.port} ${ssh.username}@${ssh.host}`)
191
215
  ```
192
216
 
193
- The sandbox must be running. Certificates last 1 hour by default (24 hours at most). Pausing or stopping prevents connections while the sandbox is not running; an unexpired certificate can be used again after resume or start. Deleting the sandbox or revoking the API key that issued the certificate revokes access.
217
+ The sandbox must be running. Certificates last 1 hour by default; `ttlSeconds` takes 1 to 86 400 (24 hours), other values throw before the request. Pausing or stopping prevents connections while the sandbox is not running; an unexpired certificate can be used again after resume or start. Deleting the sandbox or revoking the API key that issued the certificate revokes access.
194
218
 
195
219
  ## Errors
196
220
 
197
221
  | Class | When |
198
222
  | ---------------------- | ------------------------------------------------------------------------------------------------------------- |
199
223
  | `InstaboxError` | Base class. `status`, `code`, `message`, `requestId`, `retryable`, `operationId` from the API error envelope. |
200
- | `InstaboxAuthError` | 401 / 403: missing, invalid or revoked API key, or no access. |
224
+ | `InstaboxAuthError` | 401 / 403: invalid or revoked API key, or no access. No API key at all: code `missing_api_key`, status 0. |
201
225
  | `InstaboxQuotaError` | 429 `quota_exceeded`, for example the machine limit. |
202
226
  | `InstaboxTimeoutError` | A request or an operation took too long. |
203
227
  | `CommandExitError` | A command exited non-zero. Carries `stdout`, `stderr`, `exitCode`. |
@@ -226,3 +250,16 @@ npm run build
226
250
  npm test
227
251
  INSTABOX_LIVE=1 INSTABOX_API_KEY=... npm run test:live # creates and deletes one real machine
228
252
  ```
253
+
254
+ ## Releasing
255
+
256
+ Bump `version` in `package.json` in a PR. After it merges, tag that commit and push the tag:
257
+
258
+ ```bash
259
+ git tag v0.2.1 && git push origin v0.2.1
260
+ ```
261
+
262
+ The Release workflow checks that the tag is the package's version and that it is not on npm yet, runs the
263
+ checks and publishes through npm trusted publishing (OIDC): no token is stored anywhere. Once, a maintainer
264
+ adds the trusted publisher on npmjs.com (the package's Settings, Trusted Publisher, GitHub Actions: organization
265
+ `InsForge`, repository `instabox-sdk`, workflow `release.yml`, no environment).
package/dist/index.cjs CHANGED
@@ -24,12 +24,14 @@ __export(index_exports, {
24
24
  Commands: () => Commands,
25
25
  DEFAULT_API_URL: () => DEFAULT_API_URL,
26
26
  DEFAULT_TEMPLATE: () => DEFAULT_TEMPLATE,
27
+ FALLBACK_TEMPLATE: () => FALLBACK_TEMPLATE,
27
28
  Files: () => Files,
28
29
  InstaboxAuthError: () => InstaboxAuthError,
29
30
  InstaboxError: () => InstaboxError,
30
31
  InstaboxQuotaError: () => InstaboxQuotaError,
31
32
  InstaboxTimeoutError: () => InstaboxTimeoutError,
32
33
  MAX_FILE_BYTES: () => MAX_FILE_BYTES,
34
+ MAX_STDIN_BYTES: () => MAX_STDIN_BYTES,
33
35
  Sandbox: () => Sandbox
34
36
  });
35
37
  module.exports = __toCommonJS(index_exports);
@@ -137,6 +139,7 @@ function readEnv(name) {
137
139
  }
138
140
 
139
141
  // src/commands.ts
142
+ var MAX_STDIN_BYTES = 1024 * 1024;
140
143
  var Commands = class {
141
144
  /** @internal */
142
145
  constructor(http, sandboxId, defaultEnvs) {
@@ -149,7 +152,7 @@ var Commands = class {
149
152
  defaultEnvs;
150
153
  async run(cmd, opts = {}) {
151
154
  if (opts.background) {
152
- const wrapped = `nohup sh -c ${shellQuote(cmd)} >/dev/null 2>&1 & echo $!`;
155
+ const wrapped = `command -v setsid >/dev/null || { echo 'setsid not found' >&2; exit 127; }; setsid nohup sh -c ${shellQuote(cmd)} >/dev/null 2>&1 & echo $!`;
153
156
  if (opts.stdin !== void 0)
154
157
  throw new InstaboxError("stdin is not supported for background commands", { code: "bad_request" });
155
158
  const r2 = await this.exec(wrapped, { cwd: opts.cwd, envs: opts.envs, timeoutMs: opts.timeoutMs });
@@ -159,7 +162,7 @@ var Commands = class {
159
162
  throw new InstaboxError("exec returned an invalid background PID", { code: "invalid_response" });
160
163
  return {
161
164
  pid,
162
- kill: async () => (await this.exec(`kill ${pid}`)).exitCode === 0
165
+ kill: async () => (await this.exec(`kill -s TERM -- -${pid}`)).exitCode === 0
163
166
  };
164
167
  }
165
168
  const r = await this.exec(cmd, opts);
@@ -174,7 +177,12 @@ var Commands = class {
174
177
  const body = { cmd };
175
178
  if (opts.cwd !== void 0) body.cwd = opts.cwd;
176
179
  if (Object.keys(envs).length) body.envs = envs;
177
- if (opts.stdin !== void 0) body.stdin = opts.stdin;
180
+ if (opts.stdin !== void 0) {
181
+ if (new TextEncoder().encode(opts.stdin).length > MAX_STDIN_BYTES) {
182
+ throw new InstaboxError(`stdin is longer than ${MAX_STDIN_BYTES} bytes`, { code: "bad_request" });
183
+ }
184
+ body.stdin = opts.stdin;
185
+ }
178
186
  if (opts.timeoutMs !== void 0) {
179
187
  if (!Number.isFinite(opts.timeoutMs) || opts.timeoutMs <= 0 || opts.timeoutMs > 6e5) {
180
188
  throw new InstaboxError("command timeoutMs must be greater than 0 and at most 600 000", { code: "bad_request" });
@@ -214,7 +222,7 @@ var Files = class {
214
222
  }
215
223
  commands;
216
224
  async read(path, opts = {}) {
217
- const p = shellQuote(path);
225
+ const p = arg(path);
218
226
  const r = await this.commands.exec(
219
227
  `[ -f ${p} ] || { echo "no such file: "${p} >&2; exit 3; }; s=$(wc -c < ${p}) || exit 1; [ "$s" -le ${MAX_FILE_BYTES} ] || { echo "file too large: $s bytes" >&2; exit 4; }; printf '%s' "$s"`
220
228
  );
@@ -243,7 +251,10 @@ var Files = class {
243
251
  }
244
252
  return opts.format === "bytes" ? bytes : new TextDecoder().decode(bytes);
245
253
  }
246
- /** Writes a file, creating parent directories. Replaces the file atomically (temp file + rename). */
254
+ /**
255
+ * Writes a file, creating parent directories. Replaces the file atomically (temp file + rename).
256
+ * Throws `is_a_directory` when `path` is a directory.
257
+ */
247
258
  async write(path, data) {
248
259
  const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
249
260
  if (bytes.length > MAX_FILE_BYTES) {
@@ -251,23 +262,24 @@ var Files = class {
251
262
  code: "file_too_large"
252
263
  });
253
264
  }
254
- const p = shellQuote(path);
255
- const tmp = shellQuote(`${path}.instabox-${Math.random().toString(36).slice(2, 10)}.tmp`);
265
+ const p = arg(path);
266
+ const tmp = arg(`${path}.instabox-${Math.random().toString(36).slice(2, 10)}.tmp`);
256
267
  const b64 = bytesToBase64(bytes);
257
268
  const chunks = [];
258
269
  for (let i = 0; i < b64.length; i += WRITE_CHUNK_B64) chunks.push(b64.slice(i, i + WRITE_CHUNK_B64));
259
270
  if (chunks.length === 0) chunks.push("");
271
+ const notDir = `if [ -d ${p} ]; then echo "is a directory: "${p} >&2; exit 21; fi; `;
260
272
  try {
261
273
  for (let i = 0; i < chunks.length; i++) {
262
274
  const redirect = i === 0 ? ">" : ">>";
263
- const prefix = i === 0 ? `mkdir -p "$(dirname ${p})" && ` : "";
275
+ const prefix = i === 0 ? `${notDir}mkdir -p -- "$(dirname -- ${p})" && ` : "";
264
276
  const r2 = await this.commands.exec(`${prefix}printf '%s' '${chunks[i]}' | base64 -d ${redirect} ${tmp}`);
265
- if (r2.exitCode !== 0) throw new CommandExitError(r2);
277
+ if (r2.exitCode !== 0) throw writeError(r2, path);
266
278
  }
267
- const r = await this.commands.exec(`mv -f ${tmp} ${p}`);
268
- if (r.exitCode !== 0) throw new CommandExitError(r);
279
+ const r = await this.commands.exec(`${notDir}mv -f -- ${tmp} ${p}`);
280
+ if (r.exitCode !== 0) throw writeError(r, path);
269
281
  } catch (err) {
270
- await this.commands.exec(`rm -f ${tmp}`).catch(() => {
282
+ await this.commands.exec(`rm -f -- ${tmp}`).catch(() => {
271
283
  });
272
284
  throw err;
273
285
  }
@@ -275,7 +287,7 @@ var Files = class {
275
287
  }
276
288
  /** Lists the entries of a directory (not recursive). */
277
289
  async list(path) {
278
- const p = shellQuote(path);
290
+ const p = arg(path);
279
291
  const r = await this.commands.exec(
280
292
  `[ -d ${p} ] || { echo "no such directory: "${p} >&2; exit 3; }; cd ${p} && for f in .* *; do case "$f" in .|..) continue ;; esac; [ -e "$f" ] || [ -L "$f" ] || continue; if [ -d "$f" ]; then printf 'd\\t%s\\0' "$f"; else printf 'f\\t%s\\0' "$f"; fi; done`
281
293
  );
@@ -290,22 +302,29 @@ var Files = class {
290
302
  }
291
303
  /** Removes a file or a directory (recursively). Missing paths are fine. */
292
304
  async remove(path) {
293
- const r = await this.commands.exec(`rm -rf -- ${shellQuote(path)}`);
305
+ const r = await this.commands.exec(`rm -rf -- ${arg(path)}`);
294
306
  if (r.exitCode !== 0) throw new CommandExitError(r);
295
307
  }
296
308
  /** True if a file or directory exists at `path`. */
297
309
  async exists(path) {
298
- const r = await this.commands.exec(`test -e ${shellQuote(path)}`);
310
+ const r = await this.commands.exec(`test -e ${arg(path)}`);
299
311
  return r.exitCode === 0;
300
312
  }
301
313
  };
314
+ function arg(path) {
315
+ return shellQuote(path.startsWith("-") ? `./${path}` : path);
316
+ }
317
+ function writeError(result, path) {
318
+ if (result.exitCode === 21) return new InstaboxError(`is a directory: ${path}`, { code: "is_a_directory" });
319
+ return new CommandExitError(result);
320
+ }
302
321
  function ensureComplete(result) {
303
322
  if (result.exitCode !== 0) throw new CommandExitError(result);
304
323
  if (result.truncated) throw new InstaboxError("file command output was truncated", { code: "output_truncated" });
305
324
  }
306
325
 
307
326
  // src/http.ts
308
- var DEFAULT_API_URL = "https://api.box.instacloud.com";
327
+ var DEFAULT_API_URL = "https://api.instabox.sh";
309
328
  var MAX_RETRIES = 3;
310
329
  var HttpClient = class {
311
330
  apiUrl;
@@ -318,7 +337,7 @@ var HttpClient = class {
318
337
  constructor(opts = {}) {
319
338
  const apiKey = opts.apiKey ?? readEnv("INSTABOX_API_KEY");
320
339
  if (!apiKey) {
321
- throw new InstaboxError(
340
+ throw new InstaboxAuthError(
322
341
  "No instabox API key. Set the INSTABOX_API_KEY environment variable or pass { apiKey } (create one on the API Keys page of the instabox dashboard).",
323
342
  { code: "missing_api_key" }
324
343
  );
@@ -444,13 +463,15 @@ var HttpClient = class {
444
463
  };
445
464
 
446
465
  // src/sandbox.ts
447
- var DEFAULT_TEMPLATE = "universal";
466
+ var DEFAULT_TEMPLATE = "agent-browser";
467
+ var FALLBACK_TEMPLATE = "universal";
448
468
  function toInfo(m) {
449
469
  const info = {
450
470
  sandboxId: m.id,
451
471
  templateId: m.template?.id,
452
472
  name: m.name,
453
473
  metadata: { ...m.metadata },
474
+ vault: m.vault ?? true,
454
475
  startedAt: new Date(m.createdAt),
455
476
  onTimeout: m.onTimeout ?? "pause",
456
477
  state: m.state,
@@ -459,8 +480,19 @@ function toInfo(m) {
459
480
  if (m.snapshot?.id) info.snapshotId = m.snapshot.id;
460
481
  if (m.timeoutAt) info.endAt = new Date(m.timeoutAt);
461
482
  if (m.archiveAt) info.archiveAt = new Date(m.archiveAt);
483
+ if (m.autoSuspendAfterSeconds) info.autoSuspendMs = m.autoSuspendAfterSeconds * 1e3;
462
484
  return info;
463
485
  }
486
+ function toIdleSeconds(ms) {
487
+ if (ms === 0) return 0;
488
+ const s = Math.ceil(ms / 1e3);
489
+ if (!Number.isFinite(ms) || s < 120 || s > 86400) {
490
+ throw new InstaboxError(`autoSuspendMs must be 0 or between 120 000 (2 min) and 86 400 000 (24 h); got ${ms}`, {
491
+ code: "bad_request"
492
+ });
493
+ }
494
+ return s;
495
+ }
464
496
  function toSeconds(ms, field = "timeoutMs") {
465
497
  const s = Math.ceil(ms / 1e3);
466
498
  if (!Number.isFinite(ms) || s < 60 || s > 86400) {
@@ -489,12 +521,13 @@ var Sandbox = class _Sandbox {
489
521
  files;
490
522
  machine;
491
523
  static async create(a, b) {
492
- const template = typeof a === "string" ? a : DEFAULT_TEMPLATE;
493
524
  const opts = (typeof a === "string" ? b : a) ?? {};
494
525
  const http = new HttpClient(opts);
495
526
  const body = { name: opts.name ?? `sbx-${randomSuffix()}` };
496
527
  if (opts.timeoutMs !== void 0) body.timeoutSeconds = toSeconds(opts.timeoutMs);
497
528
  if (opts.archiveMs !== void 0) body.archiveSeconds = toSeconds(opts.archiveMs, "archiveMs");
529
+ if (opts.autoSuspendMs !== void 0) body.autoSuspendAfterSeconds = toIdleSeconds(opts.autoSuspendMs);
530
+ const template = typeof a === "string" ? a : await defaultTemplate(http);
498
531
  Object.assign(body, await resolveSource(http, template));
499
532
  if (opts.vcpus !== void 0) body.vcpus = opts.vcpus;
500
533
  if (opts.memMiB !== void 0) body.memMiB = opts.memMiB;
@@ -502,7 +535,8 @@ var Sandbox = class _Sandbox {
502
535
  if (opts.rootDiskGiB !== void 0) body.rootDiskGiB = opts.rootDiskGiB;
503
536
  if (opts.onTimeout) body.onTimeout = opts.onTimeout;
504
537
  if (opts.metadata) body.metadata = opts.metadata;
505
- const op = await http.request("POST", "/v1/machines", { body });
538
+ if (opts.vault === false) body.vault = false;
539
+ const op = await createMachine(http, body);
506
540
  const done = await http.waitForOperation(op);
507
541
  const machine = await getMachine(http, done.machineId);
508
542
  return new _Sandbox(http, machine, opts);
@@ -557,8 +591,14 @@ var Sandbox = class _Sandbox {
557
591
  throw err;
558
592
  }
559
593
  }
560
- /** Saves a stopped sandbox's disks as a private snapshot. Requires images:write. */
594
+ /**
595
+ * Saves the sandbox's disks as a private snapshot. Requires images:write. The sandbox may be running;
596
+ * the snapshot is then returned with `status: 'pending'` and becomes `ready` once saved. For a stopped
597
+ * sandbox it waits first for a recent stop's upload to object storage (see `untilSynced`).
598
+ */
561
599
  async createSnapshot(opts) {
600
+ await this.settle();
601
+ await this.untilSynced();
562
602
  return this.http.request("POST", `/v1/machines/${enc(this.sandboxId)}/snapshots`, { body: opts });
563
603
  }
564
604
  /** Fetches the current state of the sandbox. */
@@ -575,12 +615,45 @@ var Sandbox = class _Sandbox {
575
615
  if (opts.onTimeout) body.onTimeout = opts.onTimeout;
576
616
  this.machine = await this.http.request("PATCH", `/v1/machines/${enc(this.sandboxId)}`, { body });
577
617
  }
618
+ /**
619
+ * Pauses the sandbox once it has been idle `idleMs` (whole seconds, 2 min to 24 h); 0 turns the idle
620
+ * pause off. Unlike a timeout the setting stays across pause and resume.
621
+ */
622
+ async setAutoSuspend(idleMs) {
623
+ this.machine = await this.http.request("PATCH", `/v1/machines/${enc(this.sandboxId)}`, {
624
+ body: { autoSuspendAfterSeconds: toIdleSeconds(idleMs) }
625
+ });
626
+ }
578
627
  /** Replaces the sandbox's metadata (`{}` clears it). */
579
628
  async setMetadata(metadata) {
580
629
  this.machine = await this.http.request("PATCH", `/v1/machines/${enc(this.sandboxId)}`, {
581
630
  body: { metadata }
582
631
  });
583
632
  }
633
+ /**
634
+ * What the Vault writes into this sandbox: whether it takes the Vault, the items that apply with its
635
+ * current metadata (names and paths, never values) and the last write. Requires machines:read.
636
+ * Throws `not_found` on a server without the Vault.
637
+ */
638
+ async vault() {
639
+ return this.http.request("GET", `/v1/machines/${enc(this.sandboxId)}/vault`);
640
+ }
641
+ /**
642
+ * Writes the account's current Vault items into the running sandbox now, the same write as after a boot,
643
+ * and returns its record (`error` set when the guest refused it). Requires machines:write.
644
+ */
645
+ async pushVault() {
646
+ return this.http.request("POST", `/v1/machines/${enc(this.sandboxId)}/vault`);
647
+ }
648
+ /**
649
+ * Turns the Vault off for this sandbox, for good, in any state: its next boot, resume or push removes
650
+ * what the Vault wrote and nothing is written again. Requires machines:write.
651
+ */
652
+ async disableVault() {
653
+ this.machine = await this.http.request("PATCH", `/v1/machines/${enc(this.sandboxId)}`, {
654
+ body: { vault: false }
655
+ });
656
+ }
584
657
  /** True if the sandbox is running (fetches fresh state). */
585
658
  async isRunning() {
586
659
  return (await this.getInfo()).state === "running";
@@ -608,6 +681,7 @@ var Sandbox = class _Sandbox {
608
681
  /** Copies this sandbox (root disk and `/data`) into a new sandbox and waits until it runs. */
609
682
  async fork(opts = {}) {
610
683
  if (opts.timeoutMs !== void 0) toSeconds(opts.timeoutMs);
684
+ if (opts.autoSuspendMs !== void 0) toIdleSeconds(opts.autoSuspendMs);
611
685
  await this.settle();
612
686
  if (this.machine.state !== "stopped") {
613
687
  if (opts.stopSource === false) {
@@ -617,6 +691,7 @@ var Sandbox = class _Sandbox {
617
691
  }
618
692
  await this.stop();
619
693
  }
694
+ await this.untilSynced();
620
695
  const body = { name: opts.name ?? `${this.machine.name}-fork-${randomSuffix(4)}` };
621
696
  if (opts.vcpus !== void 0) body.vcpus = opts.vcpus;
622
697
  if (opts.memMiB !== void 0) body.memMiB = opts.memMiB;
@@ -624,7 +699,9 @@ var Sandbox = class _Sandbox {
624
699
  if (opts.rootDiskGiB !== void 0) body.rootDiskGiB = opts.rootDiskGiB;
625
700
  if (opts.timeoutMs !== void 0) body.timeoutSeconds = toSeconds(opts.timeoutMs);
626
701
  if (opts.onTimeout) body.onTimeout = opts.onTimeout;
702
+ if (opts.autoSuspendMs !== void 0) body.autoSuspendAfterSeconds = toIdleSeconds(opts.autoSuspendMs);
627
703
  if (opts.metadata) body.metadata = opts.metadata;
704
+ if (opts.vault === false) body.vault = false;
628
705
  const op = await this.http.request("POST", `/v1/machines/${enc(this.sandboxId)}/fork`, { body });
629
706
  const done = await this.http.waitForOperation(op);
630
707
  return new _Sandbox(this.http, await getMachine(this.http, done.machineId));
@@ -636,11 +713,18 @@ var Sandbox = class _Sandbox {
636
713
  /**
637
714
  * Issues a short-lived SSH certificate for `publicKey` (authorized_keys format).
638
715
  * Connect with `ssh -p <port> -o CertificateFile=<cert> -i <key> <username>@<host>` after adding
639
- * `knownHostsLine` to known_hosts. The sandbox must be running.
716
+ * `knownHostsLine` to known_hosts. The sandbox must be running. `ttlSeconds`: 1 to 86 400 (24 h);
717
+ * default: the server's (1 h).
640
718
  */
641
719
  async sshCredentials(publicKey, opts = {}) {
642
720
  const body = { publicKey: publicKey.trim() };
643
- if (opts.ttlSeconds) body.ttlSeconds = opts.ttlSeconds;
721
+ if (opts.ttlSeconds !== void 0) {
722
+ if (!Number.isInteger(opts.ttlSeconds) || opts.ttlSeconds < 1 || opts.ttlSeconds > 86400) {
723
+ const msg = `ttlSeconds must be a whole number between 1 and 86 400 (24 h); got ${opts.ttlSeconds}`;
724
+ throw new InstaboxError(msg, { code: "bad_request" });
725
+ }
726
+ body.ttlSeconds = opts.ttlSeconds;
727
+ }
644
728
  const c = await this.http.request("POST", `/v1/machines/${enc(this.sandboxId)}/connections`, { body });
645
729
  return {
646
730
  host: c.host,
@@ -666,6 +750,27 @@ var Sandbox = class _Sandbox {
666
750
  this.machine = await getMachine(this.http, this.sandboxId);
667
751
  }
668
752
  }
753
+ /**
754
+ * Waits until a stopped sandbox's disks are in object storage (`storage.synced`). A stop returns
755
+ * once the host has the snapshot and uploads it after, so a fork or snapshot right after a stop
756
+ * was refused ("not uploaded to object storage"), which took long enough after a pause and resume
757
+ * to fail every time. Only a stopped sandbox is waited for; the server says what else is wrong.
758
+ */
759
+ async untilSynced() {
760
+ const deadline = Date.now() + this.http.operationTimeoutMs;
761
+ let delay = this.http.pollIntervalMs;
762
+ while (this.machine.state === "stopped" && !this.machine.storage.synced) {
763
+ if (Date.now() + delay > deadline) {
764
+ throw new InstaboxTimeoutError(
765
+ `${this.sandboxId}'s disks were not uploaded to object storage within ${this.http.operationTimeoutMs} ms`,
766
+ { code: "operation_timeout" }
767
+ );
768
+ }
769
+ await new Promise((r) => setTimeout(r, delay));
770
+ delay = Math.min(delay * 2, 2e3);
771
+ this.machine = await getMachine(this.http, this.sandboxId);
772
+ }
773
+ }
669
774
  async mutate(method, action) {
670
775
  const op = await this.http.request(method, `/v1/machines/${enc(this.sandboxId)}/${action}`);
671
776
  await this.http.waitForOperation(op);
@@ -685,6 +790,30 @@ async function killMachine(http, id) {
685
790
  throw err;
686
791
  }
687
792
  }
793
+ async function createMachine(http, body) {
794
+ const deadline = Date.now() + http.operationTimeoutMs;
795
+ let delay = http.pollIntervalMs;
796
+ for (; ; ) {
797
+ try {
798
+ return await http.request("POST", "/v1/machines", { body });
799
+ } catch (err) {
800
+ const saving = body.snapshotId !== void 0 && err instanceof InstaboxError && err.status === 409 && err.code === "operation_conflict" && /still being saved/i.test(err.message);
801
+ if (!saving) throw err;
802
+ if (Date.now() + delay > deadline) {
803
+ throw new InstaboxTimeoutError(
804
+ `snapshot ${String(body.snapshotId)} was still being saved after ${http.operationTimeoutMs} ms`,
805
+ { code: "operation_timeout", cause: err }
806
+ );
807
+ }
808
+ await sleep(delay);
809
+ delay = Math.min(delay * 2, 2e3);
810
+ }
811
+ }
812
+ }
813
+ async function defaultTemplate(http) {
814
+ const { templates } = await http.request("GET", "/v1/templates");
815
+ return templates.some((t) => t.id === DEFAULT_TEMPLATE && !t.hidden) ? DEFAULT_TEMPLATE : FALLBACK_TEMPLATE;
816
+ }
688
817
  async function resolveSource(http, ref) {
689
818
  if (/^sn_[a-z2-7]{26}$/.test(ref)) return { snapshotId: ref };
690
819
  const { templates } = await http.request("GET", "/v1/templates");