@insforge/instabox-sdk 0.3.0 → 0.5.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
@@ -1,6 +1,6 @@
1
1
  # @insforge/instabox-sdk
2
2
 
3
- TypeScript SDK for [InstaBox](https://github.com/InsForge/instabox): create sandboxes on Firecracker dev machines, run commands in them, read and write files, pause and resume them, fork them and SSH in.
3
+ TypeScript SDK for [InstaBox](https://github.com/InsForge/instabox): create sandboxes on Firecracker dev machines, run commands in them, read and write files, pause and resume them, save and restore snapshots and SSH in.
4
4
 
5
5
  - Zero runtime dependencies. Uses the global `fetch` (Node 18+, Bun, Deno).
6
6
  - ESM and CommonJS builds with type declarations.
@@ -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`, `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` |
33
+ | Scope | Allows |
34
+ | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
35
+ | `machines:read` | `Sandbox.list`, `getInfo`, `isRunning`, `vault` |
36
+ | `machines:write` | `create`, `connect` (resume), `pause`, `resume`, `stop`, `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
 
@@ -149,14 +149,6 @@ A timeout is enforced by the server: at `endAt` it suspends the sandbox (`onTime
149
149
 
150
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.
151
151
 
152
- ### Fork
153
-
154
- ```ts
155
- const copy = await sandbox.fork({ name: 'copy' })
156
- ```
157
-
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.
159
-
160
152
  ## Vault
161
153
 
162
154
  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,11 +157,10 @@ What an API key can do is keep a sandbox out of it, which **a program creating s
165
157
 
166
158
  ```ts
167
159
  const tenant = await Sandbox.create('universal', { vault: false }) // never gets the account's items
168
- const copy = await sandbox.fork({ vault: false })
169
160
  await sandbox.disableVault() // for good, in any state
170
161
  ```
171
162
 
172
- `vault: false` is for good: such a sandbox, and its forks, never get items. On a sandbox that takes the Vault:
163
+ `vault: false` is for good: such a sandbox never gets items. On a sandbox that takes the Vault:
173
164
 
174
165
  ```ts
175
166
  const v = await sandbox.vault() // { enabled, items: [{ name, kind, path? }], applied: { at, env, files, removed?, kept?, error? } | null }
@@ -198,6 +189,8 @@ try {
198
189
 
199
190
  `deleteSnapshot` returns false if the snapshot is already absent. Snapshots do not save running processes; use pause/resume for memory preservation.
200
191
 
192
+ 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 })`.
193
+
201
194
  ## SSH
202
195
 
203
196
  ```ts
@@ -243,6 +236,26 @@ await sandbox.desktop.revokeStreamUrls() // every link stops working; open viewe
243
236
 
244
237
  `streamUrl` needs no instabox account to open: anyone with the link can connect until `expiresAt` (60 s to 24 h, default 1 h). Expiry stops new connections; revoke ends open sessions: a viewer already watching stays until they leave or you call `revokeStreamUrls()`, which ends every link of the sandbox and disconnects its viewers within a few seconds. Revoke when someone's access should end, for example when a tenant's session or subscription ends. Links are view-only by default, enforced by the server; `viewOnly: false` lets the viewer use the mouse and keyboard. The sandbox and its desktop must be running when the link is opened.
245
238
 
239
+ ## Metrics and usage
240
+
241
+ ```ts
242
+ // CPU and memory, one sample per 30 s, oldest first (default: the last 5 minutes, at most 24 h back)
243
+ const samples = await sandbox.getMetrics({ since: new Date(Date.now() - 15 * 60_000) })
244
+ // [{ timestamp: Date, cpuUsedPct: 12.5, cpuCount: 4, memUsed, memTotal, diskTotal }]
245
+
246
+ // What the sandbox used, for billing your own customers (default: this calendar month, UTC, to now)
247
+ const usage = await Sandbox.getUsage(sandbox.sandboxId, { from: new Date('2026-10-01T00:00:00Z') })
248
+ // { from, to, runningSeconds, vcpuSeconds, memGiBSeconds, diskGiBSeconds }
249
+
250
+ // Your account: counts, stored bytes (per sandbox in storage.machines, measured hourly) and limits
251
+ const account = await Sandbox.usage()
252
+ ```
253
+
254
+ All three need `machines:read` (`Sandbox.usage()` also works with `images:read`).
255
+
256
+ - Metrics are measured on the host: `cpuUsedPct` is CPU time over the sandbox's vCPUs (0-100), `memUsed` the guest memory it has touched, in bytes. `diskUsed` is not reported yet. The list is empty while the sandbox is not running.
257
+ - `runningSeconds` counts time running, not paused or stopped; `vcpuSeconds` and `memGiBSeconds` multiply it by the sandbox's size. `diskGiBSeconds` is its disk size (system disk plus `/data`) times the time it existed in the window, paused or stopped included. Running time is recorded from the server release that added this route; earlier time is not counted. A deleted sandbox's usage stays readable by its ID.
258
+
246
259
  ## Errors
247
260
 
248
261
  | Class | When |
@@ -283,7 +296,7 @@ INSTABOX_LIVE=1 INSTABOX_API_KEY=... npm run test:live # creates and deletes o
283
296
  Bump `version` in `package.json` in a PR. After it merges, tag that commit and push the tag:
284
297
 
285
298
  ```bash
286
- git tag v0.3.0 && git push origin v0.3.0
299
+ git tag v0.4.0 && git push origin v0.4.0
287
300
  ```
288
301
 
289
302
  The Release workflow checks that the tag is the package's version and that it is not on npm yet, runs the
package/dist/index.cjs CHANGED
@@ -833,6 +833,18 @@ var Sandbox = class _Sandbox {
833
833
  static async kill(sandboxId, opts = {}) {
834
834
  return killMachine(new HttpClient(opts), sandboxId);
835
835
  }
836
+ /** A sandbox's recent CPU and memory samples, oldest first (empty while it is not running). Requires machines:read. */
837
+ static async getMetrics(sandboxId, opts = {}) {
838
+ return getMetrics(new HttpClient(opts), sandboxId, opts);
839
+ }
840
+ /** What a sandbox used over a window (default: this calendar month); works for a deleted one by ID. Requires machines:read. */
841
+ static async getUsage(sandboxId, opts = {}) {
842
+ return getUsage(new HttpClient(opts), sandboxId, opts);
843
+ }
844
+ /** Your account's counts, stored bytes (per sandbox in `storage`) and limits. Requires machines:read or images:read. */
845
+ static async usage(opts = {}) {
846
+ return new HttpClient(opts).request("GET", "/v1/usage");
847
+ }
836
848
  /** Lists the caller's private snapshots. Requires images:read. */
837
849
  static async listSnapshots(opts = {}) {
838
850
  const result = await new HttpClient(opts).request("GET", "/v1/snapshots");
@@ -862,6 +874,14 @@ var Sandbox = class _Sandbox {
862
874
  await this.untilSynced();
863
875
  return this.http.request("POST", `/v1/machines/${enc2(this.sandboxId)}/snapshots`, { body: opts });
864
876
  }
877
+ /** This sandbox's recent CPU and memory samples; see `Sandbox.getMetrics`. */
878
+ async getMetrics(opts = {}) {
879
+ return getMetrics(this.http, this.sandboxId, opts);
880
+ }
881
+ /** What this sandbox used over a window; see `Sandbox.getUsage`. */
882
+ async getUsage(opts = {}) {
883
+ return getUsage(this.http, this.sandboxId, opts);
884
+ }
865
885
  /** Fetches the current state of the sandbox. */
866
886
  async getInfo() {
867
887
  this.machine = await getMachine(this.http, this.sandboxId);
@@ -939,34 +959,6 @@ var Sandbox = class _Sandbox {
939
959
  if (this.machine.state === "suspended") await this.mutate("POST", "start");
940
960
  await this.mutate("POST", "stop");
941
961
  }
942
- /** Copies this sandbox (root disk and `/data`) into a new sandbox and waits until it runs. */
943
- async fork(opts = {}) {
944
- if (opts.timeoutMs !== void 0) toSeconds(opts.timeoutMs);
945
- if (opts.autoSuspendMs !== void 0) toIdleSeconds(opts.autoSuspendMs);
946
- await this.settle();
947
- if (this.machine.state !== "stopped") {
948
- if (opts.stopSource === false) {
949
- throw new InstaboxError(`fork needs a stopped sandbox; ${this.sandboxId} is ${this.machine.state}`, {
950
- code: "operation_conflict"
951
- });
952
- }
953
- await this.stop();
954
- }
955
- await this.untilSynced();
956
- const body = { name: opts.name ?? `${this.machine.name}-fork-${randomSuffix(4)}` };
957
- if (opts.vcpus !== void 0) body.vcpus = opts.vcpus;
958
- if (opts.memMiB !== void 0) body.memMiB = opts.memMiB;
959
- if (opts.diskGiB !== void 0) body.persistentDiskGiB = opts.diskGiB;
960
- if (opts.rootDiskGiB !== void 0) body.rootDiskGiB = opts.rootDiskGiB;
961
- if (opts.timeoutMs !== void 0) body.timeoutSeconds = toSeconds(opts.timeoutMs);
962
- if (opts.onTimeout) body.onTimeout = opts.onTimeout;
963
- if (opts.autoSuspendMs !== void 0) body.autoSuspendAfterSeconds = toIdleSeconds(opts.autoSuspendMs);
964
- if (opts.metadata) body.metadata = opts.metadata;
965
- if (opts.vault === false) body.vault = false;
966
- const op = await this.http.request("POST", `/v1/machines/${enc2(this.sandboxId)}/fork`, { body });
967
- const done = await this.http.waitForOperation(op);
968
- return new _Sandbox(this.http, await getMachine(this.http, done.machineId));
969
- }
970
962
  /** Deletes the sandbox and its disks. Returns false if it was already gone. */
971
963
  async kill() {
972
964
  return killMachine(this.http, this.sandboxId);
@@ -1013,7 +1005,7 @@ var Sandbox = class _Sandbox {
1013
1005
  }
1014
1006
  /**
1015
1007
  * Waits until a stopped sandbox's disks are in object storage (`storage.synced`). A stop returns
1016
- * once the host has the snapshot and uploads it after, so a fork or snapshot right after a stop
1008
+ * once the host has the snapshot and uploads it after, so a snapshot right after a stop
1017
1009
  * was refused ("not uploaded to object storage"), which took long enough after a pause and resume
1018
1010
  * to fail every time. Only a stopped sandbox is waited for; the server says what else is wrong.
1019
1011
  */
@@ -1041,6 +1033,18 @@ var Sandbox = class _Sandbox {
1041
1033
  async function getMachine(http, id) {
1042
1034
  return http.request("GET", `/v1/machines/${enc2(id)}`);
1043
1035
  }
1036
+ async function getMetrics(http, id, opts) {
1037
+ const out = await http.request("GET", `/v1/machines/${enc2(id)}/metrics`, {
1038
+ query: { since: opts.since?.toISOString() }
1039
+ });
1040
+ return out.metrics.map((s) => ({ ...s, timestamp: new Date(s.timestamp) }));
1041
+ }
1042
+ async function getUsage(http, id, opts) {
1043
+ const u = await http.request("GET", `/v1/machines/${enc2(id)}/usage`, {
1044
+ query: { from: opts.from?.toISOString(), to: opts.to?.toISOString() }
1045
+ });
1046
+ return { ...u, from: new Date(u.from), to: new Date(u.to) };
1047
+ }
1044
1048
  async function killMachine(http, id) {
1045
1049
  try {
1046
1050
  const op = await http.request("DELETE", `/v1/machines/${enc2(id)}`);