@insforge/instabox-sdk 0.8.0 → 0.10.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
@@ -32,14 +32,14 @@ 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`, `ports.list` |
38
- | `machines:write` | `create`, `connect` (resume), `pause`, `resume`, `stop`, `setAutoSuspend`, `setMetadata`, `disableVault`, `pushVault`, `commands`, `files`, `sshCredentials`, `ports.publish`, `ports.unpublish` |
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`, `ports.list`, `listGpuQueue` |
38
+ | `machines:write` | `create`, `connect` (resume), `pause`, `resume`, `stop`, `setAutoSuspend`, `setMetadata`, `resize`, `disableVault`, `pushVault`, `commands`, `files`, `sshCredentials`, `ports.publish`, `ports.unpublish`, `cancelGpuQueue` |
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
 
@@ -191,6 +191,7 @@ const mine = await Sandbox.list({ metadata: { userId: 'u_42' } }) // all pairs m
191
191
 
192
192
  await sandbox.setAutoSuspend(10 * 60_000) // paid plan: pause after 10 idle minutes; 0 keeps it on (free plan: 403)
193
193
  await sandbox.setMetadata({ userId: 'u_42', stage: 'review' }) // replaces it; {} clears
194
+ await sandbox.resize({ vcpus: 8, memMiB: 16384 }) // paid plan: another of its sizes, restarting it if it runs
194
195
 
195
196
  await sandbox.kill() // delete the machine and its disks (sends X-Confirm-Delete); false if already gone
196
197
  await Sandbox.kill(id)
@@ -198,6 +199,8 @@ await Sandbox.kill(id)
198
199
 
199
200
  Every lifecycle call waits for its operation to finish (default limit 10 minutes, `operationTimeoutMs` to change it).
200
201
 
202
+ Resize: `resize({ vcpus, memMiB })` gives the sandbox another of its plan's sizes, on a paid plan (`instabox whoami --json` lists them as `allowedSpecs`). A stopped sandbox takes the new size at its next start. A running or paused one is stopped, resized and started again by one server operation, so its files stay but its running processes and paused memory do not. If it cannot start at the new size, the server starts it again at the old one and `resize` throws the operation's error. A size the plan does not offer throws `InstaboxQuotaError` (`spec_not_allowed`). A server that cannot restart a sandbox for a resize throws `resize_restart_off`: stop the sandbox first.
203
+
201
204
  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.
202
205
 
203
206
  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.
@@ -288,6 +291,28 @@ try {
288
291
 
289
292
  To copy a sandbox, save a snapshot and create from it, as above (InstaBox no longer has a fork call). The copy does not inherit the source's settings: `vault: false` and other `Sandbox.create` options apply to it as to any new sandbox, so a copy of a sandbox without the Vault needs `Sandbox.create(snapshot.id, { vault: false })`.
290
293
 
294
+ ## GPU sandboxes
295
+
296
+ GPU sandboxes are for paid plans; on the free plan a create with `gpu` throws `InstaboxQuotaError` (`403 template_not_allowed`). `gpu` names a GPU type and, after a colon, a count: `'l4'` is one L4, `'h100:2'` two H100s. Without a template argument the server picks the type's GPU template; the size comes from the type, per GPU. GPUs are billed per GPU-hour while the sandbox runs.
297
+
298
+ ```ts
299
+ // The GPU types and counts on offer. Every version of a template is listed; `latest` marks the current one.
300
+ const gpuTemplates = (await Sandbox.listTemplates()).filter((t) => t.gpu && t.latest)
301
+ for (const t of gpuTemplates) for (const g of t.gpuTypes ?? []) console.log(t.id, g.type, g.model, g.counts)
302
+
303
+ const gpuBox = await Sandbox.create({ gpu: 'l4', queue: { maxWaitMs: 2 * 3_600_000 } })
304
+ try {
305
+ console.log((await gpuBox.getInfo()).gpu) // { type: 'l4', count: 1 }
306
+ await gpuBox.commands.run('nvidia-smi')
307
+ } finally {
308
+ await gpuBox.kill()
309
+ }
310
+ ```
311
+
312
+ Without `queue`, a create that finds no GPU of the type free throws `no_capacity`. With `queue: true` (wait up to an hour) or `queue: { maxWaitMs }` (60 s to 24 h) it waits in the GPU queue instead: the sandbox is created stopped, holding no GPU, with `getInfo().queue` set (`id`, `position`, `expiresAt`), and `create` returns once a GPU frees up and the sandbox runs. If none frees up in time, `create` throws `InstaboxError` with code `queue_expired` and the sandbox is deleted. `create` gives up `operationTimeoutMs` after the entry's `expiresAt` with `InstaboxTimeoutError`, leaving the entry queued. A stopped GPU sandbox waits the same way with `sandbox.resume({ queue: true })` or `Sandbox.connect(id, { queue: true })`; past the wait it stays stopped with its disks.
313
+
314
+ To stop waiting, cancel the entry with `Sandbox.cancelGpuQueue(entryId)`, never `kill()`: a `create` entry's sandbox is then deleted, a `start` entry's stays stopped with its disks, while `kill()` deletes a stopped sandbox's disks too. `Sandbox.listGpuQueue({ state, limit, cursor })` lists your entries, newest first: live ones (`queued`, `dispatched`) with their place in line and ended ones with their `reason`. Another code thrown from a wait is that reason: `user` for a cancel, or the error code that refused the start.
315
+
291
316
  ## SSH
292
317
 
293
318
  ```ts
@@ -392,11 +417,11 @@ A port stays published until you unpublish it, and publishing it again keeps its
392
417
  ```ts
393
418
  // CPU and memory, one sample per 30 s, oldest first (default: the last 5 minutes, at most 24 h back)
394
419
  const samples = await sandbox.getMetrics({ since: new Date(Date.now() - 15 * 60_000) })
395
- // [{ timestamp: Date, cpuUsedPct: 12.5, cpuCount: 4, memUsed, memTotal, diskTotal }]
420
+ // [{ timestamp: Date, cpuUsedPct: 12.5, cpuCount: 4, memUsed, memTotal, diskTotal }], plus gpuUsedPct, gpuMemUsed, ... on a GPU sandbox
396
421
 
397
422
  // What the sandbox used, for billing your own customers (default: this calendar month, UTC, to now)
398
423
  const usage = await Sandbox.getUsage(sandbox.sandboxId, { from: new Date('2026-10-01T00:00:00Z') })
399
- // { from, to, runningSeconds, vcpuSeconds, memGiBSeconds, diskGiBSeconds, egressBytes }
424
+ // { from, to, runningSeconds, vcpuSeconds, memGiBSeconds, diskGiBSeconds, egressBytes }, plus gpuSeconds, gpuUSD on a GPU sandbox
400
425
 
401
426
  // Your account: counts, stored bytes (per sandbox in storage.machines, measured hourly) and limits
402
427
  const account = await Sandbox.usage()
package/dist/index.cjs CHANGED
@@ -2576,6 +2576,8 @@ function toInfo(m) {
2576
2576
  if (m.snapshot?.id) info.snapshotId = m.snapshot.id;
2577
2577
  if (m.archiveAt) info.archiveAt = new Date(m.archiveAt);
2578
2578
  if (m.autoSuspendAfterSeconds) info.autoSuspendMs = m.autoSuspendAfterSeconds * 1e3;
2579
+ if (m.spec.gpuType && m.spec.gpus) info.gpu = { type: m.spec.gpuType, count: m.spec.gpus };
2580
+ if (m.queue) info.queue = m.queue;
2579
2581
  return info;
2580
2582
  }
2581
2583
  function timeoutRemoved(what, use) {
@@ -2603,6 +2605,15 @@ function toSeconds(ms, field) {
2603
2605
  }
2604
2606
  return s;
2605
2607
  }
2608
+ function queueBody(q2) {
2609
+ return q2 === true ? {} : { maxWaitSeconds: toSeconds(q2.maxWaitMs, "queue.maxWaitMs") };
2610
+ }
2611
+ function wholeCount(field, n) {
2612
+ if (!Number.isInteger(n) || n < 1) {
2613
+ throw new InstaboxError(`${field} must be a whole number from 1; got ${n}`, { code: "bad_request" });
2614
+ }
2615
+ return n;
2616
+ }
2606
2617
  var METADATA_KEY = /^[A-Za-z0-9_.-]{1,64}$/;
2607
2618
  var enc4 = encodeURIComponent;
2608
2619
  var Sandbox = class _Sandbox {
@@ -2643,8 +2654,10 @@ var Sandbox = class _Sandbox {
2643
2654
  const body = { name: opts.name ?? `sbx-${randomSuffix()}` };
2644
2655
  if (opts.archiveMs !== void 0) body.archiveSeconds = toSeconds(opts.archiveMs, "archiveMs");
2645
2656
  if (opts.autoSuspendMs !== void 0) body.autoSuspendAfterSeconds = toIdleSeconds(opts.autoSuspendMs);
2646
- const template = typeof a === "string" ? a : await defaultTemplate(http);
2647
- Object.assign(body, await resolveSource(http, template));
2657
+ if (opts.queue !== void 0) body.queue = queueBody(opts.queue);
2658
+ if (typeof a === "string") Object.assign(body, await resolveSource(http, a));
2659
+ else if (!opts.gpu) Object.assign(body, await resolveSource(http, await defaultTemplate(http)));
2660
+ if (opts.gpu) body.gpu = opts.gpu;
2648
2661
  if (opts.vcpus !== void 0) body.vcpus = opts.vcpus;
2649
2662
  if (opts.memMiB !== void 0) body.memMiB = opts.memMiB;
2650
2663
  if (opts.diskGiB !== void 0) body.persistentDiskGiB = opts.diskGiB;
@@ -2653,15 +2666,16 @@ var Sandbox = class _Sandbox {
2653
2666
  if (opts.vault === false) body.vault = false;
2654
2667
  const op = await createMachine(http, body);
2655
2668
  const done = await http.waitForOperation(op);
2656
- const machine = await getMachine(http, done.machineId);
2669
+ const machine = await untilPlaced(http, await getMachine(http, done.machineId));
2657
2670
  return new _Sandbox(http, machine, opts);
2658
2671
  }
2659
2672
  /** Attaches to an existing sandbox. Resumes it if it is paused or stopped, unless `resume: false`. */
2660
2673
  static async connect(sandboxId, opts = {}) {
2674
+ const start = startBody(opts.queue);
2661
2675
  const http = new HttpClient(opts);
2662
2676
  const sbx = new _Sandbox(http, await getMachine(http, sandboxId), opts);
2663
2677
  await sbx.settle(false);
2664
- if (opts.resume !== false) await sbx.wake();
2678
+ if (opts.resume !== false) await sbx.wake(start);
2665
2679
  return sbx;
2666
2680
  }
2667
2681
  /** Lists your sandboxes (all pages), optionally only those matching `metadata`. */
@@ -2699,6 +2713,31 @@ var Sandbox = class _Sandbox {
2699
2713
  static async usage(opts = {}) {
2700
2714
  return new HttpClient(opts).request("GET", "/v1/usage");
2701
2715
  }
2716
+ /**
2717
+ * The templates a create may name. Every version of a template is listed; `latest` marks the one a
2718
+ * create gets. GPU templates have `gpu` and list their GPU types in `gpuTypes`.
2719
+ */
2720
+ static async listTemplates(opts = {}) {
2721
+ return (await new HttpClient(opts).request("GET", "/v1/templates")).templates;
2722
+ }
2723
+ /**
2724
+ * A page of your GPU queue entries, newest first: live ones (`queued`, `dispatched`) with their place
2725
+ * in line, and ended ones with their `reason`. Requires machines:read.
2726
+ */
2727
+ static async listGpuQueue(opts = {}) {
2728
+ return new HttpClient(opts).request("GET", "/v1/gpu-queue", {
2729
+ query: { state: opts.state, limit: opts.limit, cursor: opts.cursor }
2730
+ });
2731
+ }
2732
+ /**
2733
+ * Stops a GPU queue entry's wait (`getInfo().queue.id`). A `create` entry's sandbox is deleted; a
2734
+ * `start` entry's stays stopped with its disks. Cancel this way, never with `kill()`, which deletes
2735
+ * a stopped sandbox's disks. Returns the entry, `cancelled`, or still `dispatched` with `cancelling`
2736
+ * when the sandbox was already starting. Requires machines:write.
2737
+ */
2738
+ static async cancelGpuQueue(entryId, opts = {}) {
2739
+ return new HttpClient(opts).request("DELETE", `/v1/gpu-queue/${enc4(entryId)}`);
2740
+ }
2702
2741
  /** Lists the caller's private snapshots. Requires images:read. */
2703
2742
  static async listSnapshots(opts = {}) {
2704
2743
  const result = await new HttpClient(opts).request("GET", "/v1/snapshots");
@@ -2758,6 +2797,27 @@ var Sandbox = class _Sandbox {
2758
2797
  async setTimeout(..._args) {
2759
2798
  throw timeoutRemoved("setTimeout()", "Use setAutoSuspend(ms) to pause the sandbox once it has been idle that long");
2760
2799
  }
2800
+ /**
2801
+ * Gives the sandbox another of its plan's sizes (paid plans). A stopped sandbox takes it at its next
2802
+ * start. A running or paused one is stopped, resized and started again by one server operation: files
2803
+ * stay, running processes and paused memory do not. If it cannot start at the new size, the server
2804
+ * starts it again at the old one and this throws. A size the plan does not offer throws
2805
+ * `InstaboxQuotaError` (`spec_not_allowed`). Requires machines:write.
2806
+ */
2807
+ async resize(opts) {
2808
+ const vcpus = wholeCount("vcpus", opts.vcpus);
2809
+ const memMiB = wholeCount("memMiB", opts.memMiB);
2810
+ await this.settle();
2811
+ if (this.machine.spec.vcpus === vcpus && this.machine.spec.memMiB === memMiB) return;
2812
+ const body = { vcpus, memMiB };
2813
+ if (this.machine.state !== "stopped") body.apply = "restart";
2814
+ const r = await this.http.request("PATCH", `/v1/machines/${enc4(this.sandboxId)}`, { body });
2815
+ try {
2816
+ if ("machineId" in r) await this.http.waitForOperation(r);
2817
+ } finally {
2818
+ this.machine = await getMachine(this.http, this.sandboxId).catch(() => this.machine);
2819
+ }
2820
+ }
2761
2821
  /** Replaces the sandbox's metadata (`{}` clears it). */
2762
2822
  async setMetadata(metadata) {
2763
2823
  this.machine = await this.http.request("PATCH", `/v1/machines/${enc4(this.sandboxId)}`, {
@@ -2796,15 +2856,23 @@ var Sandbox = class _Sandbox {
2796
2856
  async pause() {
2797
2857
  await this.mutate("POST", "suspend");
2798
2858
  }
2799
- /** Resumes a paused sandbox from its snapshot, or starts a stopped one. */
2800
- async resume() {
2859
+ /** Resumes a paused sandbox from its snapshot, or starts a stopped one (waiting for a GPU with `queue`). */
2860
+ async resume(opts = {}) {
2861
+ const start = startBody(opts.queue);
2801
2862
  await this.settle();
2802
- await this.wake();
2863
+ await this.wake(start);
2803
2864
  }
2804
- /** Resumes or starts based on the cached state; callers make sure the cache is fresh. */
2805
- async wake() {
2806
- if (this.machine.state === "suspended") await this.mutate("POST", "resume");
2807
- else if (this.machine.state === "stopped") await this.mutate("POST", "start");
2865
+ /**
2866
+ * Resumes or starts based on the cached state; callers make sure the cache is fresh. A sandbox
2867
+ * already waiting for a GPU is waited for: starting it again would not move it up the line.
2868
+ */
2869
+ async wake(start) {
2870
+ if (this.machine.queue) this.machine = await untilPlaced(this.http, this.machine);
2871
+ else if (this.machine.state === "suspended") await this.mutate("POST", "resume");
2872
+ else if (this.machine.state === "stopped") {
2873
+ await this.mutate("POST", "start", start);
2874
+ this.machine = await untilPlaced(this.http, this.machine);
2875
+ }
2808
2876
  }
2809
2877
  /** Stops the sandbox (guest shutdown; processes end, `/data` is kept). */
2810
2878
  async stop() {
@@ -2877,8 +2945,9 @@ var Sandbox = class _Sandbox {
2877
2945
  this.machine = await getMachine(this.http, this.sandboxId);
2878
2946
  }
2879
2947
  }
2880
- async mutate(method, action) {
2881
- const op = await this.http.request(method, `/v1/machines/${enc4(this.sandboxId)}/${action}`);
2948
+ async mutate(method, action, body) {
2949
+ const path = `/v1/machines/${enc4(this.sandboxId)}/${action}`;
2950
+ const op = await this.http.request(method, path, body ? { body } : {});
2882
2951
  await this.http.waitForOperation(op);
2883
2952
  this.machine = await getMachine(this.http, this.sandboxId);
2884
2953
  }
@@ -2886,6 +2955,66 @@ var Sandbox = class _Sandbox {
2886
2955
  async function getMachine(http, id) {
2887
2956
  return http.request("GET", `/v1/machines/${enc4(id)}`);
2888
2957
  }
2958
+ function startBody(queue) {
2959
+ return queue === void 0 ? void 0 : { queue: queueBody(queue) };
2960
+ }
2961
+ async function untilPlaced(http, m) {
2962
+ let last = m.queue;
2963
+ if (!last) return m;
2964
+ let orgId = m.orgId;
2965
+ let delay = http.pollIntervalMs;
2966
+ let waited;
2967
+ for (; ; ) {
2968
+ if (m.queue) last = m.queue;
2969
+ else if (m.state === "running") return m;
2970
+ else if (m.state !== "starting" && m.state !== "creating") throw await queueEnded(http, last, m, orgId);
2971
+ if (m.operationId && m.operationId !== waited) {
2972
+ waited = m.operationId;
2973
+ const op = await http.request("GET", `/v1/operations/${enc4(m.operationId)}`);
2974
+ await http.waitForOperation(op);
2975
+ } else {
2976
+ const deadline = Date.parse(last.expiresAt) + http.operationTimeoutMs;
2977
+ if (Date.now() + delay > deadline) {
2978
+ throw new InstaboxTimeoutError(
2979
+ `${m.id} was still waiting for a ${last.gpuType ?? ""} GPU ${http.operationTimeoutMs} ms past its queue entry's expiry (${last.expiresAt}); cancel it with Sandbox.cancelGpuQueue('${last.id}')`,
2980
+ { code: "operation_timeout" }
2981
+ );
2982
+ }
2983
+ await sleep(delay);
2984
+ delay = Math.min(Math.round(delay * 1.5), Math.max(5e3, http.pollIntervalMs));
2985
+ }
2986
+ try {
2987
+ m = await getMachine(http, m.id);
2988
+ } catch (err) {
2989
+ if (err instanceof InstaboxError && err.status === 404) throw await queueEnded(http, last, void 0, orgId);
2990
+ throw err;
2991
+ }
2992
+ orgId = m.orgId ?? orgId;
2993
+ }
2994
+ }
2995
+ var QUEUE_ENDS = {
2996
+ expired: "no GPU freed up within the wait",
2997
+ cancelled: "the request was cancelled",
2998
+ failed: "the start failed"
2999
+ };
3000
+ async function queueEnded(http, q2, m, orgId) {
3001
+ let entry;
3002
+ try {
3003
+ let cursor;
3004
+ for (let i = 0; i < 3 && !entry; i++) {
3005
+ const page = await http.request("GET", "/v1/gpu-queue", { query: { orgId, limit: 200, cursor } });
3006
+ entry = page.entries.find((e) => e.id === q2.id);
3007
+ cursor = page.nextCursor;
3008
+ if (!cursor) break;
3009
+ }
3010
+ } catch (err) {
3011
+ if (!(err instanceof InstaboxError)) throw err;
3012
+ }
3013
+ const what = QUEUE_ENDS[entry?.state ?? ""] ?? "the request ended";
3014
+ const left = !m || q2.kind === "create" ? "it was deleted" : `it is ${m.state} with its disks`;
3015
+ const code = entry?.reason || (entry ? `queue_${entry.state}` : "queue_ended");
3016
+ return new InstaboxError(`sandbox stopped waiting for a ${q2.gpuType ?? ""} GPU: ${what}; ${left}`, { code });
3017
+ }
2889
3018
  async function getMetrics(http, id, opts) {
2890
3019
  const out = await http.request("GET", `/v1/machines/${enc4(id)}/metrics`, {
2891
3020
  query: { since: opts.since?.toISOString() }