@insforge/instabox-sdk 0.9.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`, `resize`, `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
 
@@ -291,6 +291,28 @@ try {
291
291
 
292
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 })`.
293
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
+
294
316
  ## SSH
295
317
 
296
318
  ```ts
@@ -395,11 +417,11 @@ A port stays published until you unpublish it, and publishing it again keeps its
395
417
  ```ts
396
418
  // CPU and memory, one sample per 30 s, oldest first (default: the last 5 minutes, at most 24 h back)
397
419
  const samples = await sandbox.getMetrics({ since: new Date(Date.now() - 15 * 60_000) })
398
- // [{ 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
399
421
 
400
422
  // What the sandbox used, for billing your own customers (default: this calendar month, UTC, to now)
401
423
  const usage = await Sandbox.getUsage(sandbox.sandboxId, { from: new Date('2026-10-01T00:00:00Z') })
402
- // { from, to, runningSeconds, vcpuSeconds, memGiBSeconds, diskGiBSeconds, egressBytes }
424
+ // { from, to, runningSeconds, vcpuSeconds, memGiBSeconds, diskGiBSeconds, egressBytes }, plus gpuSeconds, gpuUSD on a GPU sandbox
403
425
 
404
426
  // Your account: counts, stored bytes (per sandbox in storage.machines, measured hourly) and limits
405
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,9 @@ 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
+ }
2606
2611
  function wholeCount(field, n) {
2607
2612
  if (!Number.isInteger(n) || n < 1) {
2608
2613
  throw new InstaboxError(`${field} must be a whole number from 1; got ${n}`, { code: "bad_request" });
@@ -2649,8 +2654,10 @@ var Sandbox = class _Sandbox {
2649
2654
  const body = { name: opts.name ?? `sbx-${randomSuffix()}` };
2650
2655
  if (opts.archiveMs !== void 0) body.archiveSeconds = toSeconds(opts.archiveMs, "archiveMs");
2651
2656
  if (opts.autoSuspendMs !== void 0) body.autoSuspendAfterSeconds = toIdleSeconds(opts.autoSuspendMs);
2652
- const template = typeof a === "string" ? a : await defaultTemplate(http);
2653
- 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;
2654
2661
  if (opts.vcpus !== void 0) body.vcpus = opts.vcpus;
2655
2662
  if (opts.memMiB !== void 0) body.memMiB = opts.memMiB;
2656
2663
  if (opts.diskGiB !== void 0) body.persistentDiskGiB = opts.diskGiB;
@@ -2659,15 +2666,16 @@ var Sandbox = class _Sandbox {
2659
2666
  if (opts.vault === false) body.vault = false;
2660
2667
  const op = await createMachine(http, body);
2661
2668
  const done = await http.waitForOperation(op);
2662
- const machine = await getMachine(http, done.machineId);
2669
+ const machine = await untilPlaced(http, await getMachine(http, done.machineId));
2663
2670
  return new _Sandbox(http, machine, opts);
2664
2671
  }
2665
2672
  /** Attaches to an existing sandbox. Resumes it if it is paused or stopped, unless `resume: false`. */
2666
2673
  static async connect(sandboxId, opts = {}) {
2674
+ const start = startBody(opts.queue);
2667
2675
  const http = new HttpClient(opts);
2668
2676
  const sbx = new _Sandbox(http, await getMachine(http, sandboxId), opts);
2669
2677
  await sbx.settle(false);
2670
- if (opts.resume !== false) await sbx.wake();
2678
+ if (opts.resume !== false) await sbx.wake(start);
2671
2679
  return sbx;
2672
2680
  }
2673
2681
  /** Lists your sandboxes (all pages), optionally only those matching `metadata`. */
@@ -2705,6 +2713,31 @@ var Sandbox = class _Sandbox {
2705
2713
  static async usage(opts = {}) {
2706
2714
  return new HttpClient(opts).request("GET", "/v1/usage");
2707
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
+ }
2708
2741
  /** Lists the caller's private snapshots. Requires images:read. */
2709
2742
  static async listSnapshots(opts = {}) {
2710
2743
  const result = await new HttpClient(opts).request("GET", "/v1/snapshots");
@@ -2823,15 +2856,23 @@ var Sandbox = class _Sandbox {
2823
2856
  async pause() {
2824
2857
  await this.mutate("POST", "suspend");
2825
2858
  }
2826
- /** Resumes a paused sandbox from its snapshot, or starts a stopped one. */
2827
- 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);
2828
2862
  await this.settle();
2829
- await this.wake();
2863
+ await this.wake(start);
2830
2864
  }
2831
- /** Resumes or starts based on the cached state; callers make sure the cache is fresh. */
2832
- async wake() {
2833
- if (this.machine.state === "suspended") await this.mutate("POST", "resume");
2834
- 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
+ }
2835
2876
  }
2836
2877
  /** Stops the sandbox (guest shutdown; processes end, `/data` is kept). */
2837
2878
  async stop() {
@@ -2904,8 +2945,9 @@ var Sandbox = class _Sandbox {
2904
2945
  this.machine = await getMachine(this.http, this.sandboxId);
2905
2946
  }
2906
2947
  }
2907
- async mutate(method, action) {
2908
- 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 } : {});
2909
2951
  await this.http.waitForOperation(op);
2910
2952
  this.machine = await getMachine(this.http, this.sandboxId);
2911
2953
  }
@@ -2913,6 +2955,66 @@ var Sandbox = class _Sandbox {
2913
2955
  async function getMachine(http, id) {
2914
2956
  return http.request("GET", `/v1/machines/${enc4(id)}`);
2915
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
+ }
2916
3018
  async function getMetrics(http, id, opts) {
2917
3019
  const out = await http.request("GET", `/v1/machines/${enc4(id)}/metrics`, {
2918
3020
  query: { since: opts.since?.toISOString() }