@insforge/instabox-sdk 0.1.0 → 0.2.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
@@ -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,13 +46,13 @@ 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', {
@@ -63,9 +63,11 @@ const sandbox = await Sandbox.create('universal', {
63
63
  diskGiB: 20, // persistent /data disk
64
64
  envs: { NODE_ENV: 'development' }, // applied to every commands.run of this object
65
65
  metadata: { userId: 'u_42' }, // labels stored with the sandbox (plaintext: not for secrets)
66
+ vault: false, // for a sandbox made for someone else: none of the account's Vault items
66
67
  timeoutMs: 30 * 60_000, // server pauses it 30 min from now (60 s to 24 h)
67
68
  archiveMs: 24 * 60 * 60_000, // stops it at this deadline, independent of timeout
68
69
  onTimeout: 'pause', // or 'kill' to delete it instead
70
+ autoSuspendMs: 10 * 60_000, // pauses it after 10 idle minutes (default 30; 0: never)
69
71
  })
70
72
  console.log(sandbox.sandboxId) // m_...
71
73
  ```
@@ -128,7 +130,7 @@ await sandbox.resume() // restore the snapshot (or start a stopped machine)
128
130
  const again = await Sandbox.connect(id) // attach; resumes a paused or stopped sandbox
129
131
  const noWake = await Sandbox.connect(id, { resume: false })
130
132
 
131
- const info = await sandbox.getInfo() // { sandboxId, templateId, snapshotId?, name, metadata, startedAt, endAt?, archiveAt?, onTimeout, state, machine }
133
+ const info = await sandbox.getInfo() // { sandboxId, templateId, snapshotId?, name, metadata, vault, startedAt, endAt?, archiveAt?, onTimeout, autoSuspendMs?, state, machine }
132
134
  await sandbox.isRunning() // boolean
133
135
 
134
136
  const all = await Sandbox.list() // your sandboxes, as SandboxInfo[]
@@ -136,6 +138,7 @@ const mine = await Sandbox.list({ metadata: { userId: 'u_42' } }) // all pairs m
136
138
 
137
139
  await sandbox.setTimeout(10 * 60_000) // pause 10 min from now; setTimeout(0) clears it
138
140
  await sandbox.setTimeout(60_000, { onTimeout: 'kill' })
141
+ await sandbox.setAutoSuspend(10 * 60_000) // pause after 10 idle minutes; 0 keeps it on
139
142
  await sandbox.setMetadata({ userId: 'u_42', stage: 'review' }) // replaces it; {} clears
140
143
 
141
144
  await sandbox.kill() // delete the machine and its disks; false if already gone
@@ -144,7 +147,9 @@ await Sandbox.kill(id)
144
147
 
145
148
  Every lifecycle call waits for its operation to finish (default limit 10 minutes, `operationTimeoutMs` to change it).
146
149
 
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.
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.
151
+
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: 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
153
 
149
154
  ### Fork
150
155
 
@@ -154,6 +159,28 @@ const copy = await sandbox.fork({ name: 'copy' })
154
159
 
155
160
  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
161
 
162
+ ## Vault
163
+
164
+ 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.
165
+
166
+ 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.
167
+
168
+ ```ts
169
+ const tenant = await Sandbox.create('universal', { vault: false }) // never gets the account's items
170
+ const copy = await sandbox.fork({ vault: false })
171
+ await sandbox.disableVault() // for good, in any state
172
+ ```
173
+
174
+ `vault: false` is for good: such a sandbox, and its forks, never get items. On a sandbox that takes the Vault:
175
+
176
+ ```ts
177
+ const v = await sandbox.vault() // { enabled, items: [{ name, kind, path? }], applied: { at, env, files, removed?, kept?, error? } | null }
178
+ const applied = await sandbox.pushVault() // write the current items now (the sandbox must be running)
179
+ console.log((await sandbox.getInfo()).vault) // true
180
+ ```
181
+
182
+ 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.
183
+
157
184
  ## Snapshots
158
185
 
159
186
  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`.
@@ -190,7 +217,7 @@ appendFileSync(`${homedir()}/.ssh/known_hosts`, ssh.knownHostsLine + '\n')
190
217
  console.log(`ssh -p ${ssh.port} ${ssh.username}@${ssh.host}`)
191
218
  ```
192
219
 
193
- The sandbox must be running. Certificates last 1 hour by default (24 hours at most) and are revoked when the sandbox stops, pauses or is deleted.
220
+ 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.
194
221
 
195
222
  ## Errors
196
223
 
package/dist/index.cjs CHANGED
@@ -24,6 +24,7 @@ __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,
@@ -277,12 +278,12 @@ var Files = class {
277
278
  async list(path) {
278
279
  const p = shellQuote(path);
279
280
  const r = await this.commands.exec(
280
- `[ -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\\n' "$f"; else printf 'f\\t%s\\n' "$f"; fi; done`
281
+ `[ -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
282
  );
282
283
  if (r.exitCode === 3) throw new InstaboxError(`directory not found: ${path}`, { status: 404, code: "not_found" });
283
284
  ensureComplete(r);
284
285
  const base = path.endsWith("/") ? path.slice(0, -1) : path;
285
- return r.stdout.split("\n").filter(Boolean).map((line) => {
286
+ return r.stdout.split("\0").filter(Boolean).map((line) => {
286
287
  const tab = line.indexOf(" ");
287
288
  const name = line.slice(tab + 1);
288
289
  return { name, path: `${base}/${name}`, type: line.slice(0, tab) === "d" ? "dir" : "file" };
@@ -305,7 +306,7 @@ function ensureComplete(result) {
305
306
  }
306
307
 
307
308
  // src/http.ts
308
- var DEFAULT_API_URL = "https://api.box.instacloud.com";
309
+ var DEFAULT_API_URL = "https://api.instabox.sh";
309
310
  var MAX_RETRIES = 3;
310
311
  var HttpClient = class {
311
312
  apiUrl;
@@ -444,13 +445,15 @@ var HttpClient = class {
444
445
  };
445
446
 
446
447
  // src/sandbox.ts
447
- var DEFAULT_TEMPLATE = "universal";
448
+ var DEFAULT_TEMPLATE = "agent-browser";
449
+ var FALLBACK_TEMPLATE = "universal";
448
450
  function toInfo(m) {
449
451
  const info = {
450
452
  sandboxId: m.id,
451
453
  templateId: m.template?.id,
452
454
  name: m.name,
453
455
  metadata: { ...m.metadata },
456
+ vault: m.vault ?? true,
454
457
  startedAt: new Date(m.createdAt),
455
458
  onTimeout: m.onTimeout ?? "pause",
456
459
  state: m.state,
@@ -459,8 +462,19 @@ function toInfo(m) {
459
462
  if (m.snapshot?.id) info.snapshotId = m.snapshot.id;
460
463
  if (m.timeoutAt) info.endAt = new Date(m.timeoutAt);
461
464
  if (m.archiveAt) info.archiveAt = new Date(m.archiveAt);
465
+ if (m.autoSuspendAfterSeconds) info.autoSuspendMs = m.autoSuspendAfterSeconds * 1e3;
462
466
  return info;
463
467
  }
468
+ function toIdleSeconds(ms) {
469
+ if (ms === 0) return 0;
470
+ const s = Math.ceil(ms / 1e3);
471
+ if (!Number.isFinite(ms) || s < 120 || s > 86400) {
472
+ throw new InstaboxError(`autoSuspendMs must be 0 or between 120 000 (2 min) and 86 400 000 (24 h); got ${ms}`, {
473
+ code: "bad_request"
474
+ });
475
+ }
476
+ return s;
477
+ }
464
478
  function toSeconds(ms, field = "timeoutMs") {
465
479
  const s = Math.ceil(ms / 1e3);
466
480
  if (!Number.isFinite(ms) || s < 60 || s > 86400) {
@@ -489,12 +503,13 @@ var Sandbox = class _Sandbox {
489
503
  files;
490
504
  machine;
491
505
  static async create(a, b) {
492
- const template = typeof a === "string" ? a : DEFAULT_TEMPLATE;
493
506
  const opts = (typeof a === "string" ? b : a) ?? {};
494
507
  const http = new HttpClient(opts);
495
508
  const body = { name: opts.name ?? `sbx-${randomSuffix()}` };
496
509
  if (opts.timeoutMs !== void 0) body.timeoutSeconds = toSeconds(opts.timeoutMs);
497
510
  if (opts.archiveMs !== void 0) body.archiveSeconds = toSeconds(opts.archiveMs, "archiveMs");
511
+ if (opts.autoSuspendMs !== void 0) body.autoSuspendAfterSeconds = toIdleSeconds(opts.autoSuspendMs);
512
+ const template = typeof a === "string" ? a : await defaultTemplate(http);
498
513
  Object.assign(body, await resolveSource(http, template));
499
514
  if (opts.vcpus !== void 0) body.vcpus = opts.vcpus;
500
515
  if (opts.memMiB !== void 0) body.memMiB = opts.memMiB;
@@ -502,6 +517,7 @@ var Sandbox = class _Sandbox {
502
517
  if (opts.rootDiskGiB !== void 0) body.rootDiskGiB = opts.rootDiskGiB;
503
518
  if (opts.onTimeout) body.onTimeout = opts.onTimeout;
504
519
  if (opts.metadata) body.metadata = opts.metadata;
520
+ if (opts.vault === false) body.vault = false;
505
521
  const op = await http.request("POST", "/v1/machines", { body });
506
522
  const done = await http.waitForOperation(op);
507
523
  const machine = await getMachine(http, done.machineId);
@@ -557,8 +573,13 @@ var Sandbox = class _Sandbox {
557
573
  throw err;
558
574
  }
559
575
  }
560
- /** Saves a stopped sandbox's disks as a private snapshot. Requires images:write. */
576
+ /**
577
+ * Saves a stopped sandbox's disks as a private snapshot. Requires images:write. Waits first for a
578
+ * recent stop's upload to object storage (see `untilSynced`).
579
+ */
561
580
  async createSnapshot(opts) {
581
+ await this.settle();
582
+ await this.untilSynced();
562
583
  return this.http.request("POST", `/v1/machines/${enc(this.sandboxId)}/snapshots`, { body: opts });
563
584
  }
564
585
  /** Fetches the current state of the sandbox. */
@@ -575,12 +596,45 @@ var Sandbox = class _Sandbox {
575
596
  if (opts.onTimeout) body.onTimeout = opts.onTimeout;
576
597
  this.machine = await this.http.request("PATCH", `/v1/machines/${enc(this.sandboxId)}`, { body });
577
598
  }
599
+ /**
600
+ * Pauses the sandbox once it has been idle `idleMs` (whole seconds, 2 min to 24 h); 0 turns the idle
601
+ * pause off. Unlike a timeout the setting stays across pause and resume.
602
+ */
603
+ async setAutoSuspend(idleMs) {
604
+ this.machine = await this.http.request("PATCH", `/v1/machines/${enc(this.sandboxId)}`, {
605
+ body: { autoSuspendAfterSeconds: toIdleSeconds(idleMs) }
606
+ });
607
+ }
578
608
  /** Replaces the sandbox's metadata (`{}` clears it). */
579
609
  async setMetadata(metadata) {
580
610
  this.machine = await this.http.request("PATCH", `/v1/machines/${enc(this.sandboxId)}`, {
581
611
  body: { metadata }
582
612
  });
583
613
  }
614
+ /**
615
+ * What the Vault writes into this sandbox: whether it takes the Vault, the items that apply with its
616
+ * current metadata (names and paths, never values) and the last write. Requires machines:read.
617
+ * Throws `not_found` on a server without the Vault.
618
+ */
619
+ async vault() {
620
+ return this.http.request("GET", `/v1/machines/${enc(this.sandboxId)}/vault`);
621
+ }
622
+ /**
623
+ * Writes the account's current Vault items into the running sandbox now, the same write as after a boot,
624
+ * and returns its record (`error` set when the guest refused it). Requires machines:write.
625
+ */
626
+ async pushVault() {
627
+ return this.http.request("POST", `/v1/machines/${enc(this.sandboxId)}/vault`);
628
+ }
629
+ /**
630
+ * Turns the Vault off for this sandbox, for good, in any state: its next boot, resume or push removes
631
+ * what the Vault wrote and nothing is written again. Requires machines:write.
632
+ */
633
+ async disableVault() {
634
+ this.machine = await this.http.request("PATCH", `/v1/machines/${enc(this.sandboxId)}`, {
635
+ body: { vault: false }
636
+ });
637
+ }
584
638
  /** True if the sandbox is running (fetches fresh state). */
585
639
  async isRunning() {
586
640
  return (await this.getInfo()).state === "running";
@@ -608,6 +662,7 @@ var Sandbox = class _Sandbox {
608
662
  /** Copies this sandbox (root disk and `/data`) into a new sandbox and waits until it runs. */
609
663
  async fork(opts = {}) {
610
664
  if (opts.timeoutMs !== void 0) toSeconds(opts.timeoutMs);
665
+ if (opts.autoSuspendMs !== void 0) toIdleSeconds(opts.autoSuspendMs);
611
666
  await this.settle();
612
667
  if (this.machine.state !== "stopped") {
613
668
  if (opts.stopSource === false) {
@@ -617,6 +672,7 @@ var Sandbox = class _Sandbox {
617
672
  }
618
673
  await this.stop();
619
674
  }
675
+ await this.untilSynced();
620
676
  const body = { name: opts.name ?? `${this.machine.name}-fork-${randomSuffix(4)}` };
621
677
  if (opts.vcpus !== void 0) body.vcpus = opts.vcpus;
622
678
  if (opts.memMiB !== void 0) body.memMiB = opts.memMiB;
@@ -624,7 +680,9 @@ var Sandbox = class _Sandbox {
624
680
  if (opts.rootDiskGiB !== void 0) body.rootDiskGiB = opts.rootDiskGiB;
625
681
  if (opts.timeoutMs !== void 0) body.timeoutSeconds = toSeconds(opts.timeoutMs);
626
682
  if (opts.onTimeout) body.onTimeout = opts.onTimeout;
683
+ if (opts.autoSuspendMs !== void 0) body.autoSuspendAfterSeconds = toIdleSeconds(opts.autoSuspendMs);
627
684
  if (opts.metadata) body.metadata = opts.metadata;
685
+ if (opts.vault === false) body.vault = false;
628
686
  const op = await this.http.request("POST", `/v1/machines/${enc(this.sandboxId)}/fork`, { body });
629
687
  const done = await this.http.waitForOperation(op);
630
688
  return new _Sandbox(this.http, await getMachine(this.http, done.machineId));
@@ -666,6 +724,27 @@ var Sandbox = class _Sandbox {
666
724
  this.machine = await getMachine(this.http, this.sandboxId);
667
725
  }
668
726
  }
727
+ /**
728
+ * Waits until a stopped sandbox's disks are in object storage (`storage.synced`). A stop returns
729
+ * once the host has the snapshot and uploads it after, so a fork or snapshot right after a stop
730
+ * was refused ("not uploaded to object storage"), which took long enough after a pause and resume
731
+ * to fail every time. Only a stopped sandbox is waited for; the server says what else is wrong.
732
+ */
733
+ async untilSynced() {
734
+ const deadline = Date.now() + this.http.operationTimeoutMs;
735
+ let delay = this.http.pollIntervalMs;
736
+ while (this.machine.state === "stopped" && !this.machine.storage.synced) {
737
+ if (Date.now() + delay > deadline) {
738
+ throw new InstaboxTimeoutError(
739
+ `${this.sandboxId}'s disks were not uploaded to object storage within ${this.http.operationTimeoutMs} ms`,
740
+ { code: "operation_timeout" }
741
+ );
742
+ }
743
+ await new Promise((r) => setTimeout(r, delay));
744
+ delay = Math.min(delay * 2, 2e3);
745
+ this.machine = await getMachine(this.http, this.sandboxId);
746
+ }
747
+ }
669
748
  async mutate(method, action) {
670
749
  const op = await this.http.request(method, `/v1/machines/${enc(this.sandboxId)}/${action}`);
671
750
  await this.http.waitForOperation(op);
@@ -685,6 +764,10 @@ async function killMachine(http, id) {
685
764
  throw err;
686
765
  }
687
766
  }
767
+ async function defaultTemplate(http) {
768
+ const { templates } = await http.request("GET", "/v1/templates");
769
+ return templates.some((t) => t.id === DEFAULT_TEMPLATE && !t.hidden) ? DEFAULT_TEMPLATE : FALLBACK_TEMPLATE;
770
+ }
688
771
  async function resolveSource(http, ref) {
689
772
  if (/^sn_[a-z2-7]{26}$/.test(ref)) return { snapshotId: ref };
690
773
  const { templates } = await http.request("GET", "/v1/templates");