@insforge/instabox-sdk 0.7.1 → 0.9.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` |
38
- | `machines:write` | `create`, `connect` (resume), `pause`, `resume`, `stop`, `setAutoSuspend`, `setMetadata`, `disableVault`, `pushVault`, `commands`, `files`, `sshCredentials` |
39
- | `machines:delete` | `kill` |
40
- | `images:read` | Resolve private snapshot names, `listSnapshots`, `getSnapshot` |
41
- | `images:write` | `createSnapshot` |
42
- | `images:delete` | `deleteSnapshot` |
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` |
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.
@@ -372,6 +375,21 @@ async function onCancel(userId: string) {
372
375
 
373
376
  The desktop must be running when the link is opened: a link to a paused sandbox does not wake it, so `connect()` before you hand it out. An open viewer does not count as activity, so with the default idle pause a sandbox someone only watches still pauses after 30 idle minutes. Each open viewer counts toward your account's limit of open terminals and desktops (8 unless we raised it for you). Keep `vault: false` for sandboxes your users can use: anything running in one can read what the Vault writes.
374
377
 
378
+ ## Ports: a URL for a server in the sandbox
379
+
380
+ `sandbox.ports` gives a server listening in the sandbox an HTTPS URL, as `instabox port publish` does. WebSockets and streaming responses pass through.
381
+
382
+ ```ts
383
+ const { url } = await sandbox.ports.publish(3000) // https://3000-<id>.instabox.tech on the hosted service
384
+ const web = await sandbox.ports.publish(8080, { name: 'web', access: 'private' })
385
+ console.log(web.tokenUrl) // the URL with ?_token=ibp_..., the link to share
386
+ await sandbox.ports.publish(8080, { access: 'private', rotateToken: true }) // new token, the old one stops working
387
+ await sandbox.ports.list() // [{ port, name, protocol, url, access, createdAt }]
388
+ await sandbox.ports.unpublish(3000) // false if it was not published
389
+ ```
390
+
391
+ A port stays published until you unpublish it, and publishing it again keeps its URL. The URL answers while the sandbox runs. Ports run from 1024 to 65535, except the desktop's and Orca's control ports. A new port is public: anyone with the URL reaches it. A private port answers only requests that carry its token, as the link's `_token` parameter (the browser then keeps it in a cookie) or an `Authorization: Bearer` header. Only the publish that creates or rotates a token returns it. The domain is the server's, so use the returned `url` instead of building one. Publishing and unpublishing need `machines:write`, listing needs `machines:read`.
392
+
375
393
  ## Metrics and usage
376
394
 
377
395
  ```ts
@@ -422,6 +440,7 @@ Reads, and mutations (which always carry an `Idempotency-Key`), are retried up t
422
440
  - At most 32 requests per user run at once, across all your sandboxes. Commands, file reads, desktop, port-forward and vault-push calls share this limit. A `background: true` command counts only while it starts; each `wait()` holds one while it waits (it polls the job's log, up to 25 seconds per request). More throw `InstaboxQuotaError` (429, retryable).
423
441
  - A command started with `run` runs for at most 10 minutes; longer ones need `background: true`. A background command takes no `stdin`, and its stdout and stderr share one log.
424
442
  - A file moves at up to 5 GiB per `write` (the server's limit) in one request; the CLI's `instabox push` splits a file of 64 MiB or more into 4 parallel uploads, which the SDK does not do yet.
443
+ - Published ports serve at most 128 requests at once per account, across all its sandboxes. Open WebSockets and streams count until they close. A request over the limit waits up to 2 seconds for a slot, then gets `429`.
425
444
 
426
445
  ## Agent skill
427
446
 
@@ -449,4 +468,10 @@ git tag v0.4.0 && git push origin v0.4.0
449
468
  The Release workflow checks that the tag is the package's version and that it is not on npm yet, runs the
450
469
  checks and publishes through npm trusted publishing (OIDC): no token is stored anywhere. Once, a maintainer
451
470
  adds the trusted publisher on npmjs.com (the package's Settings, Trusted Publisher, GitHub Actions: organization
452
- `InsForge`, repository `instabox-sdk`, workflow `release.yml`, no environment).
471
+ `InsForge`, repository `instabox-sdk`, workflow `release.yml`, no environment) with **Allow npm dist-tag** on.
472
+
473
+ The new version is published under the `staging` dist-tag. `latest` (`next` for a prerelease) moves to it only
474
+ once its tarball downloads and installs from a clean cache, which can take a few minutes after the publish
475
+ (`scripts/npm-promote-latest.sh`, at most 15 minutes). If it never installs in that time, or npm refuses the
476
+ dist-tag, `latest` stays on the previous version and the run fails; re-run it once npm serves the tarball and it
477
+ promotes the version without publishing it again. `npm view @insforge/instabox-sdk dist-tags` shows both tags.
package/dist/index.cjs CHANGED
@@ -47,6 +47,7 @@ __export(index_exports, {
47
47
  MAX_FILE_BYTES: () => MAX_FILE_BYTES,
48
48
  MAX_STDIN_BYTES: () => MAX_STDIN_BYTES,
49
49
  MAX_UPLOAD_BYTES: () => MAX_UPLOAD_BYTES,
50
+ Ports: () => Ports,
50
51
  Sandbox: () => Sandbox,
51
52
  isLimitCode: () => isLimitCode
52
53
  });
@@ -2495,6 +2496,69 @@ var HttpClient = class {
2495
2496
  }
2496
2497
  };
2497
2498
 
2499
+ // src/ports.ts
2500
+ var enc3 = encodeURIComponent;
2501
+ function checkPort(port) {
2502
+ if (!Number.isInteger(port)) {
2503
+ throw new InstaboxError(`port must be a whole number; got ${port}`, { code: "bad_request" });
2504
+ }
2505
+ return port;
2506
+ }
2507
+ function fromServer(p) {
2508
+ const out = {
2509
+ port: p.port,
2510
+ name: p.name,
2511
+ protocol: p.protocol,
2512
+ url: p.url,
2513
+ access: p.access,
2514
+ createdAt: new Date(p.createdAt)
2515
+ };
2516
+ if (p.token) {
2517
+ out.token = p.token;
2518
+ out.tokenUrl = p.tokenUrl;
2519
+ }
2520
+ return out;
2521
+ }
2522
+ var Ports = class {
2523
+ /** @internal */
2524
+ constructor(http, sandboxId) {
2525
+ this.http = http;
2526
+ this.sandboxId = sandboxId;
2527
+ }
2528
+ http;
2529
+ sandboxId;
2530
+ /**
2531
+ * Publishes `port` (1024-65535) until `unpublish()`; publishing it again keeps its URL. The URL answers
2532
+ * while the sandbox runs, WebSockets included. Requires machines:write.
2533
+ */
2534
+ async publish(port, opts = {}) {
2535
+ const body = { port: checkPort(port) };
2536
+ if (opts.name !== void 0) body.name = opts.name;
2537
+ if (opts.access !== void 0) body.access = opts.access;
2538
+ if (opts.rotateToken) body.rotateToken = true;
2539
+ const r = await this.http.request("POST", `/v1/machines/${enc3(this.sandboxId)}/ports`, { body });
2540
+ return fromServer(r);
2541
+ }
2542
+ /** The sandbox's published ports. Tokens are not included. Requires machines:read. */
2543
+ async list() {
2544
+ const r = await this.http.request("GET", `/v1/machines/${enc3(this.sandboxId)}/ports`);
2545
+ return r.ports.map(fromServer);
2546
+ }
2547
+ /**
2548
+ * Removes the port's URL and closes its open connections. Returns false if the port was not published.
2549
+ * Requires machines:write.
2550
+ */
2551
+ async unpublish(port) {
2552
+ try {
2553
+ await this.http.request("DELETE", `/v1/machines/${enc3(this.sandboxId)}/ports/${checkPort(port)}`);
2554
+ return true;
2555
+ } catch (err) {
2556
+ if (err instanceof InstaboxError && err.status === 404 && err.code === "not_found") return false;
2557
+ throw err;
2558
+ }
2559
+ }
2560
+ };
2561
+
2498
2562
  // src/sandbox.ts
2499
2563
  var DEFAULT_TEMPLATE = "agent-browser";
2500
2564
  var FALLBACK_TEMPLATE = "universal";
@@ -2539,8 +2603,14 @@ function toSeconds(ms, field) {
2539
2603
  }
2540
2604
  return s;
2541
2605
  }
2606
+ function wholeCount(field, n) {
2607
+ if (!Number.isInteger(n) || n < 1) {
2608
+ throw new InstaboxError(`${field} must be a whole number from 1; got ${n}`, { code: "bad_request" });
2609
+ }
2610
+ return n;
2611
+ }
2542
2612
  var METADATA_KEY = /^[A-Za-z0-9_.-]{1,64}$/;
2543
- var enc3 = encodeURIComponent;
2613
+ var enc4 = encodeURIComponent;
2544
2614
  var Sandbox = class _Sandbox {
2545
2615
  constructor(http, machine, opts = {}) {
2546
2616
  this.http = http;
@@ -2550,6 +2620,7 @@ var Sandbox = class _Sandbox {
2550
2620
  this.files = new Files(this.commands, http, machine.id);
2551
2621
  this.commands.stageStdin = (bytes, signal) => this.files.stageStdin(bytes, signal);
2552
2622
  this.desktop = new Desktop(http, machine.id, this.commands, this.files);
2623
+ this.ports = new Ports(http, machine.id);
2553
2624
  }
2554
2625
  http;
2555
2626
  /** The machine ID (`m_...`). */
@@ -2560,6 +2631,8 @@ var Sandbox = class _Sandbox {
2560
2631
  files;
2561
2632
  /** See and control the sandbox's graphical desktop (screenshots, mouse, keyboard, a link to watch it). */
2562
2633
  desktop;
2634
+ /** Publish a port at an HTTPS URL, list published ports, unpublish them. */
2635
+ ports;
2563
2636
  machine;
2564
2637
  static async create(a, b) {
2565
2638
  const opts = (typeof a === "string" ? b : a) ?? {};
@@ -2639,12 +2712,12 @@ var Sandbox = class _Sandbox {
2639
2712
  }
2640
2713
  /** Fetches a snapshot by ID. Requires images:read. */
2641
2714
  static async getSnapshot(snapshotId, opts = {}) {
2642
- return new HttpClient(opts).request("GET", `/v1/snapshots/${enc3(snapshotId)}`);
2715
+ return new HttpClient(opts).request("GET", `/v1/snapshots/${enc4(snapshotId)}`);
2643
2716
  }
2644
2717
  /** Deletes a snapshot. Returns false if absent. Requires images:delete. */
2645
2718
  static async deleteSnapshot(snapshotId, opts = {}) {
2646
2719
  try {
2647
- await new HttpClient(opts).request("DELETE", `/v1/snapshots/${enc3(snapshotId)}`);
2720
+ await new HttpClient(opts).request("DELETE", `/v1/snapshots/${enc4(snapshotId)}`);
2648
2721
  return true;
2649
2722
  } catch (err) {
2650
2723
  if (err instanceof InstaboxError && err.status === 404 && err.code === "not_found") return false;
@@ -2659,7 +2732,7 @@ var Sandbox = class _Sandbox {
2659
2732
  async createSnapshot(opts) {
2660
2733
  await this.settle();
2661
2734
  await this.untilSynced();
2662
- return this.http.request("POST", `/v1/machines/${enc3(this.sandboxId)}/snapshots`, { body: opts });
2735
+ return this.http.request("POST", `/v1/machines/${enc4(this.sandboxId)}/snapshots`, { body: opts });
2663
2736
  }
2664
2737
  /** This sandbox's recent CPU and memory samples; see `Sandbox.getMetrics`. */
2665
2738
  async getMetrics(opts = {}) {
@@ -2679,7 +2752,7 @@ var Sandbox = class _Sandbox {
2679
2752
  * pause off. The setting stays across pause and resume.
2680
2753
  */
2681
2754
  async setAutoSuspend(idleMs) {
2682
- this.machine = await this.http.request("PATCH", `/v1/machines/${enc3(this.sandboxId)}`, {
2755
+ this.machine = await this.http.request("PATCH", `/v1/machines/${enc4(this.sandboxId)}`, {
2683
2756
  body: { autoSuspendAfterSeconds: toIdleSeconds(idleMs) }
2684
2757
  });
2685
2758
  }
@@ -2691,9 +2764,30 @@ var Sandbox = class _Sandbox {
2691
2764
  async setTimeout(..._args) {
2692
2765
  throw timeoutRemoved("setTimeout()", "Use setAutoSuspend(ms) to pause the sandbox once it has been idle that long");
2693
2766
  }
2767
+ /**
2768
+ * Gives the sandbox another of its plan's sizes (paid plans). A stopped sandbox takes it at its next
2769
+ * start. A running or paused one is stopped, resized and started again by one server operation: files
2770
+ * stay, running processes and paused memory do not. If it cannot start at the new size, the server
2771
+ * starts it again at the old one and this throws. A size the plan does not offer throws
2772
+ * `InstaboxQuotaError` (`spec_not_allowed`). Requires machines:write.
2773
+ */
2774
+ async resize(opts) {
2775
+ const vcpus = wholeCount("vcpus", opts.vcpus);
2776
+ const memMiB = wholeCount("memMiB", opts.memMiB);
2777
+ await this.settle();
2778
+ if (this.machine.spec.vcpus === vcpus && this.machine.spec.memMiB === memMiB) return;
2779
+ const body = { vcpus, memMiB };
2780
+ if (this.machine.state !== "stopped") body.apply = "restart";
2781
+ const r = await this.http.request("PATCH", `/v1/machines/${enc4(this.sandboxId)}`, { body });
2782
+ try {
2783
+ if ("machineId" in r) await this.http.waitForOperation(r);
2784
+ } finally {
2785
+ this.machine = await getMachine(this.http, this.sandboxId).catch(() => this.machine);
2786
+ }
2787
+ }
2694
2788
  /** Replaces the sandbox's metadata (`{}` clears it). */
2695
2789
  async setMetadata(metadata) {
2696
- this.machine = await this.http.request("PATCH", `/v1/machines/${enc3(this.sandboxId)}`, {
2790
+ this.machine = await this.http.request("PATCH", `/v1/machines/${enc4(this.sandboxId)}`, {
2697
2791
  body: { metadata }
2698
2792
  });
2699
2793
  }
@@ -2703,21 +2797,21 @@ var Sandbox = class _Sandbox {
2703
2797
  * Throws `not_found` on a server without the Vault.
2704
2798
  */
2705
2799
  async vault() {
2706
- return this.http.request("GET", `/v1/machines/${enc3(this.sandboxId)}/vault`);
2800
+ return this.http.request("GET", `/v1/machines/${enc4(this.sandboxId)}/vault`);
2707
2801
  }
2708
2802
  /**
2709
2803
  * Writes the account's current Vault items into the running sandbox now, the same write as after a boot,
2710
2804
  * and returns its record (`error` set when the guest refused it). Requires machines:write.
2711
2805
  */
2712
2806
  async pushVault() {
2713
- return this.http.request("POST", `/v1/machines/${enc3(this.sandboxId)}/vault`);
2807
+ return this.http.request("POST", `/v1/machines/${enc4(this.sandboxId)}/vault`);
2714
2808
  }
2715
2809
  /**
2716
2810
  * Turns the Vault off for this sandbox, for good, in any state: its next boot, resume or push removes
2717
2811
  * what the Vault wrote and nothing is written again. Requires machines:write.
2718
2812
  */
2719
2813
  async disableVault() {
2720
- this.machine = await this.http.request("PATCH", `/v1/machines/${enc3(this.sandboxId)}`, {
2814
+ this.machine = await this.http.request("PATCH", `/v1/machines/${enc4(this.sandboxId)}`, {
2721
2815
  body: { vault: false }
2722
2816
  });
2723
2817
  }
@@ -2764,7 +2858,7 @@ var Sandbox = class _Sandbox {
2764
2858
  }
2765
2859
  body.ttlSeconds = opts.ttlSeconds;
2766
2860
  }
2767
- const c = await this.http.request("POST", `/v1/machines/${enc3(this.sandboxId)}/connections`, { body });
2861
+ const c = await this.http.request("POST", `/v1/machines/${enc4(this.sandboxId)}/connections`, { body });
2768
2862
  return {
2769
2863
  host: c.host,
2770
2864
  port: c.port,
@@ -2783,7 +2877,7 @@ var Sandbox = class _Sandbox {
2783
2877
  async settle(refresh = true) {
2784
2878
  if (refresh) this.machine = await getMachine(this.http, this.sandboxId);
2785
2879
  if (this.machine.operationId) {
2786
- const op = await this.http.request("GET", `/v1/operations/${enc3(this.machine.operationId)}`);
2880
+ const op = await this.http.request("GET", `/v1/operations/${enc4(this.machine.operationId)}`);
2787
2881
  await this.http.waitForOperation(op).catch(() => {
2788
2882
  });
2789
2883
  this.machine = await getMachine(this.http, this.sandboxId);
@@ -2811,29 +2905,29 @@ var Sandbox = class _Sandbox {
2811
2905
  }
2812
2906
  }
2813
2907
  async mutate(method, action) {
2814
- const op = await this.http.request(method, `/v1/machines/${enc3(this.sandboxId)}/${action}`);
2908
+ const op = await this.http.request(method, `/v1/machines/${enc4(this.sandboxId)}/${action}`);
2815
2909
  await this.http.waitForOperation(op);
2816
2910
  this.machine = await getMachine(this.http, this.sandboxId);
2817
2911
  }
2818
2912
  };
2819
2913
  async function getMachine(http, id) {
2820
- return http.request("GET", `/v1/machines/${enc3(id)}`);
2914
+ return http.request("GET", `/v1/machines/${enc4(id)}`);
2821
2915
  }
2822
2916
  async function getMetrics(http, id, opts) {
2823
- const out = await http.request("GET", `/v1/machines/${enc3(id)}/metrics`, {
2917
+ const out = await http.request("GET", `/v1/machines/${enc4(id)}/metrics`, {
2824
2918
  query: { since: opts.since?.toISOString() }
2825
2919
  });
2826
2920
  return out.metrics.map((s) => ({ ...s, timestamp: new Date(s.timestamp) }));
2827
2921
  }
2828
2922
  async function getUsage(http, id, opts) {
2829
- const u = await http.request("GET", `/v1/machines/${enc3(id)}/usage`, {
2923
+ const u = await http.request("GET", `/v1/machines/${enc4(id)}/usage`, {
2830
2924
  query: { from: opts.from?.toISOString(), to: opts.to?.toISOString() }
2831
2925
  });
2832
2926
  return { ...u, from: new Date(u.from), to: new Date(u.to) };
2833
2927
  }
2834
2928
  async function killMachine(http, id) {
2835
2929
  try {
2836
- const op = await http.request("DELETE", `/v1/machines/${enc3(id)}`, {
2930
+ const op = await http.request("DELETE", `/v1/machines/${enc4(id)}`, {
2837
2931
  headers: { "X-Confirm-Delete": id }
2838
2932
  });
2839
2933
  await http.waitForOperation(op);