@insforge/instabox-sdk 0.9.0 → 0.11.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 +57 -10
- package/dist/index.cjs +205 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +236 -4
- package/dist/index.d.ts +236 -4
- package/dist/index.js +205 -13
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/skills/instabox/SKILL.md +1 -1
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
|
|
@@ -336,6 +358,31 @@ await sandbox.desktop.revokeStreamUrls() // every link stops working; open viewe
|
|
|
336
358
|
|
|
337
359
|
`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.
|
|
338
360
|
|
|
361
|
+
### Computer use: apps, windows and accessibility trees
|
|
362
|
+
|
|
363
|
+
`sandbox.computerUse` calls the tools of the sandbox's computer-use MCP server, on Linux, macOS and Windows sandboxes (`desktop` input above is Linux only). The tool names are the server's: `tools()` lists them; the examples are cua-driver's, the server of current templates. Its tools list windows and apps, read a window's accessibility tree, take screenshots, and click and type into a window by element or by pixel.
|
|
364
|
+
|
|
365
|
+
```ts
|
|
366
|
+
const tools = await sandbox.computerUse.tools() // [{ name, description, inputSchema }]
|
|
367
|
+
|
|
368
|
+
const shot = await sandbox.computerUse.call('get_desktop_state')
|
|
369
|
+
shot.text // what the tool wrote: the screen size and the windows, with pid and window_id
|
|
370
|
+
shot.images[0] // { mimeType: 'image/png', data: Uint8Array }
|
|
371
|
+
|
|
372
|
+
const r = await sandbox.computerUse.call('run_steps', {
|
|
373
|
+
pid: 1234,
|
|
374
|
+
window_id: 5678,
|
|
375
|
+
steps: [
|
|
376
|
+
{ tool: 'type_text', args: { text: 'hello' } },
|
|
377
|
+
{ tool: 'press_key', args: { key: 'return' } },
|
|
378
|
+
],
|
|
379
|
+
observe: { include_screenshot: true },
|
|
380
|
+
})
|
|
381
|
+
if (r.isError) console.error(r.text)
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
`call(name, args?, { timeoutMs })` resolves with `{ text, images, isError, structuredContent }`; a tool that fails resolves with `isError: true` and says why in `text`, a protocol error throws `InstaboxError` with code `computer_use_error`, a call past `timeoutMs` throws `InstaboxTimeoutError`, and a sandbox without the server throws `InstaboxError` with code `computer_use_unavailable`. Each call starts the server anew in the sandbox, so what one call read (element tokens, a window's screenshot for pixel clicks) does not carry to the next: run the actions in one call with the `run_steps` tool, whose steps can name their target by role and name, and its `observe` reads the window after them. Calls run as commands, so they need the `machines:exec` (or `machines:write`) scope. On Linux, while a person controls the desktop from the dashboard, only the tools that look at it work.
|
|
385
|
+
|
|
339
386
|
### One sandbox per user, shown over VNC
|
|
340
387
|
|
|
341
388
|
A product that gives each of its users a computer they watch, or drive, in its own page:
|
|
@@ -395,11 +442,11 @@ A port stays published until you unpublish it, and publishing it again keeps its
|
|
|
395
442
|
```ts
|
|
396
443
|
// CPU and memory, one sample per 30 s, oldest first (default: the last 5 minutes, at most 24 h back)
|
|
397
444
|
const samples = await sandbox.getMetrics({ since: new Date(Date.now() - 15 * 60_000) })
|
|
398
|
-
// [{ timestamp: Date, cpuUsedPct: 12.5, cpuCount: 4, memUsed, memTotal, diskTotal }]
|
|
445
|
+
// [{ timestamp: Date, cpuUsedPct: 12.5, cpuCount: 4, memUsed, memTotal, diskTotal }], plus gpuUsedPct, gpuMemUsed, ... on a GPU sandbox
|
|
399
446
|
|
|
400
447
|
// What the sandbox used, for billing your own customers (default: this calendar month, UTC, to now)
|
|
401
448
|
const usage = await Sandbox.getUsage(sandbox.sandboxId, { from: new Date('2026-10-01T00:00:00Z') })
|
|
402
|
-
// { from, to, runningSeconds, vcpuSeconds, memGiBSeconds, diskGiBSeconds, egressBytes }
|
|
449
|
+
// { from, to, runningSeconds, vcpuSeconds, memGiBSeconds, diskGiBSeconds, egressBytes }, plus gpuSeconds, gpuUSD on a GPU sandbox
|
|
403
450
|
|
|
404
451
|
// Your account: counts, stored bytes (per sandbox in storage.machines, measured hourly) and limits
|
|
405
452
|
const account = await Sandbox.usage()
|
package/dist/index.cjs
CHANGED
|
@@ -32,6 +32,7 @@ var index_exports = {};
|
|
|
32
32
|
__export(index_exports, {
|
|
33
33
|
CommandExitError: () => CommandExitError,
|
|
34
34
|
Commands: () => Commands,
|
|
35
|
+
ComputerUse: () => ComputerUse,
|
|
35
36
|
DEFAULT_API_URL: () => DEFAULT_API_URL,
|
|
36
37
|
DEFAULT_TEMPLATE: () => DEFAULT_TEMPLATE,
|
|
37
38
|
DESKTOP_DISPLAY: () => DESKTOP_DISPLAY,
|
|
@@ -671,6 +672,92 @@ ${value}`;
|
|
|
671
672
|
}
|
|
672
673
|
};
|
|
673
674
|
|
|
675
|
+
// src/computer-use.ts
|
|
676
|
+
var ComputerUse = class {
|
|
677
|
+
/** @internal */
|
|
678
|
+
constructor(commands) {
|
|
679
|
+
this.commands = commands;
|
|
680
|
+
}
|
|
681
|
+
commands;
|
|
682
|
+
/** The server's tools, with their argument schemas. */
|
|
683
|
+
async tools(opts = {}) {
|
|
684
|
+
const r = await this.request("tools/list", void 0, opts);
|
|
685
|
+
return r.tools ?? [];
|
|
686
|
+
}
|
|
687
|
+
/**
|
|
688
|
+
* Calls one tool, for example `call('get_desktop_state')` for a screenshot of the whole screen or
|
|
689
|
+
* `call('list_windows')`. A tool that fails resolves with `isError: true`; it does not throw.
|
|
690
|
+
*/
|
|
691
|
+
async call(name, args = {}, opts = {}) {
|
|
692
|
+
if (typeof name !== "string" || !name) {
|
|
693
|
+
throw new InstaboxError("call needs a tool name", { code: "bad_request" });
|
|
694
|
+
}
|
|
695
|
+
if (typeof args !== "object" || args === null || Array.isArray(args)) {
|
|
696
|
+
throw new InstaboxError("a tool's arguments must be an object", { code: "bad_request" });
|
|
697
|
+
}
|
|
698
|
+
const r = await this.request("tools/call", { name, arguments: args }, opts);
|
|
699
|
+
const content = r.content ?? [];
|
|
700
|
+
const out = {
|
|
701
|
+
text: content.filter((c) => c.type === "text").map((c) => c.text ?? "").join("\n"),
|
|
702
|
+
images: content.filter((c) => c.type === "image").map((c) => ({ mimeType: c.mimeType ?? "", data: base64ToBytes(c.data ?? "") })),
|
|
703
|
+
isError: r.isError === true
|
|
704
|
+
};
|
|
705
|
+
if (r.structuredContent !== void 0) out.structuredContent = r.structuredContent;
|
|
706
|
+
return out;
|
|
707
|
+
}
|
|
708
|
+
/** One request to a server started for it: the handshake and the request go in as stdin. */
|
|
709
|
+
async request(method, params, opts) {
|
|
710
|
+
const msgs = [
|
|
711
|
+
{
|
|
712
|
+
jsonrpc: "2.0",
|
|
713
|
+
id: 1,
|
|
714
|
+
method: "initialize",
|
|
715
|
+
params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "instabox-sdk", version: "1" } }
|
|
716
|
+
},
|
|
717
|
+
{ jsonrpc: "2.0", method: "notifications/initialized" },
|
|
718
|
+
{ jsonrpc: "2.0", id: 2, method, ...params === void 0 ? {} : { params } }
|
|
719
|
+
];
|
|
720
|
+
let stdout;
|
|
721
|
+
let stderr = "";
|
|
722
|
+
try {
|
|
723
|
+
const r = await this.commands.run("instabox-computer-use mcp", {
|
|
724
|
+
stdin: msgs.map((m) => JSON.stringify(m)).join("\n") + "\n",
|
|
725
|
+
onStdout: () => {
|
|
726
|
+
},
|
|
727
|
+
timeoutMs: opts.timeoutMs,
|
|
728
|
+
signal: opts.signal
|
|
729
|
+
});
|
|
730
|
+
stdout = r.stdout;
|
|
731
|
+
} catch (e) {
|
|
732
|
+
if (!(e instanceof CommandExitError)) throw e;
|
|
733
|
+
if (e.timedOut) {
|
|
734
|
+
throw new InstaboxTimeoutError(`the computer-use call ran past its timeout`, { code: "command_timeout" });
|
|
735
|
+
}
|
|
736
|
+
stdout = e.stdout;
|
|
737
|
+
stderr = e.stderr;
|
|
738
|
+
}
|
|
739
|
+
for (const line of stdout.split("\n")) {
|
|
740
|
+
let msg;
|
|
741
|
+
try {
|
|
742
|
+
msg = JSON.parse(line);
|
|
743
|
+
} catch {
|
|
744
|
+
continue;
|
|
745
|
+
}
|
|
746
|
+
if (msg?.id !== 2 || msg.method !== void 0) continue;
|
|
747
|
+
if (msg.error) {
|
|
748
|
+
throw new InstaboxError(`computer-use server: ${msg.error.message} (code ${msg.error.code})`, {
|
|
749
|
+
code: "computer_use_error"
|
|
750
|
+
});
|
|
751
|
+
}
|
|
752
|
+
return msg.result ?? {};
|
|
753
|
+
}
|
|
754
|
+
throw new InstaboxError(
|
|
755
|
+
`the sandbox's computer-use server ended without answering; is its template one with computer use?${stderr ? ` ${stderr.trim().slice(-500)}` : ""}`,
|
|
756
|
+
{ code: "computer_use_unavailable" }
|
|
757
|
+
);
|
|
758
|
+
}
|
|
759
|
+
};
|
|
760
|
+
|
|
674
761
|
// src/desktop.ts
|
|
675
762
|
var DESKTOP_DISPLAY = ":1";
|
|
676
763
|
var BUTTONS = { left: 1, middle: 2, right: 3 };
|
|
@@ -2576,6 +2663,8 @@ function toInfo(m) {
|
|
|
2576
2663
|
if (m.snapshot?.id) info.snapshotId = m.snapshot.id;
|
|
2577
2664
|
if (m.archiveAt) info.archiveAt = new Date(m.archiveAt);
|
|
2578
2665
|
if (m.autoSuspendAfterSeconds) info.autoSuspendMs = m.autoSuspendAfterSeconds * 1e3;
|
|
2666
|
+
if (m.spec.gpuType && m.spec.gpus) info.gpu = { type: m.spec.gpuType, count: m.spec.gpus };
|
|
2667
|
+
if (m.queue) info.queue = m.queue;
|
|
2579
2668
|
return info;
|
|
2580
2669
|
}
|
|
2581
2670
|
function timeoutRemoved(what, use) {
|
|
@@ -2603,6 +2692,9 @@ function toSeconds(ms, field) {
|
|
|
2603
2692
|
}
|
|
2604
2693
|
return s;
|
|
2605
2694
|
}
|
|
2695
|
+
function queueBody(q2) {
|
|
2696
|
+
return q2 === true ? {} : { maxWaitSeconds: toSeconds(q2.maxWaitMs, "queue.maxWaitMs") };
|
|
2697
|
+
}
|
|
2606
2698
|
function wholeCount(field, n) {
|
|
2607
2699
|
if (!Number.isInteger(n) || n < 1) {
|
|
2608
2700
|
throw new InstaboxError(`${field} must be a whole number from 1; got ${n}`, { code: "bad_request" });
|
|
@@ -2620,6 +2712,7 @@ var Sandbox = class _Sandbox {
|
|
|
2620
2712
|
this.files = new Files(this.commands, http, machine.id);
|
|
2621
2713
|
this.commands.stageStdin = (bytes, signal) => this.files.stageStdin(bytes, signal);
|
|
2622
2714
|
this.desktop = new Desktop(http, machine.id, this.commands, this.files);
|
|
2715
|
+
this.computerUse = new ComputerUse(this.commands);
|
|
2623
2716
|
this.ports = new Ports(http, machine.id);
|
|
2624
2717
|
}
|
|
2625
2718
|
http;
|
|
@@ -2631,6 +2724,8 @@ var Sandbox = class _Sandbox {
|
|
|
2631
2724
|
files;
|
|
2632
2725
|
/** See and control the sandbox's graphical desktop (screenshots, mouse, keyboard, a link to watch it). */
|
|
2633
2726
|
desktop;
|
|
2727
|
+
/** The sandbox's computer-use MCP tools: accessibility trees, screenshots, clicks and typing in apps. */
|
|
2728
|
+
computerUse;
|
|
2634
2729
|
/** Publish a port at an HTTPS URL, list published ports, unpublish them. */
|
|
2635
2730
|
ports;
|
|
2636
2731
|
machine;
|
|
@@ -2649,8 +2744,10 @@ var Sandbox = class _Sandbox {
|
|
|
2649
2744
|
const body = { name: opts.name ?? `sbx-${randomSuffix()}` };
|
|
2650
2745
|
if (opts.archiveMs !== void 0) body.archiveSeconds = toSeconds(opts.archiveMs, "archiveMs");
|
|
2651
2746
|
if (opts.autoSuspendMs !== void 0) body.autoSuspendAfterSeconds = toIdleSeconds(opts.autoSuspendMs);
|
|
2652
|
-
|
|
2653
|
-
Object.assign(body, await resolveSource(http,
|
|
2747
|
+
if (opts.queue !== void 0) body.queue = queueBody(opts.queue);
|
|
2748
|
+
if (typeof a === "string") Object.assign(body, await resolveSource(http, a));
|
|
2749
|
+
else if (!opts.gpu) Object.assign(body, await resolveSource(http, await defaultTemplate(http)));
|
|
2750
|
+
if (opts.gpu) body.gpu = opts.gpu;
|
|
2654
2751
|
if (opts.vcpus !== void 0) body.vcpus = opts.vcpus;
|
|
2655
2752
|
if (opts.memMiB !== void 0) body.memMiB = opts.memMiB;
|
|
2656
2753
|
if (opts.diskGiB !== void 0) body.persistentDiskGiB = opts.diskGiB;
|
|
@@ -2659,15 +2756,16 @@ var Sandbox = class _Sandbox {
|
|
|
2659
2756
|
if (opts.vault === false) body.vault = false;
|
|
2660
2757
|
const op = await createMachine(http, body);
|
|
2661
2758
|
const done = await http.waitForOperation(op);
|
|
2662
|
-
const machine = await getMachine(http, done.machineId);
|
|
2759
|
+
const machine = await untilPlaced(http, await getMachine(http, done.machineId));
|
|
2663
2760
|
return new _Sandbox(http, machine, opts);
|
|
2664
2761
|
}
|
|
2665
2762
|
/** Attaches to an existing sandbox. Resumes it if it is paused or stopped, unless `resume: false`. */
|
|
2666
2763
|
static async connect(sandboxId, opts = {}) {
|
|
2764
|
+
const start = startBody(opts.queue);
|
|
2667
2765
|
const http = new HttpClient(opts);
|
|
2668
2766
|
const sbx = new _Sandbox(http, await getMachine(http, sandboxId), opts);
|
|
2669
2767
|
await sbx.settle(false);
|
|
2670
|
-
if (opts.resume !== false) await sbx.wake();
|
|
2768
|
+
if (opts.resume !== false) await sbx.wake(start);
|
|
2671
2769
|
return sbx;
|
|
2672
2770
|
}
|
|
2673
2771
|
/** Lists your sandboxes (all pages), optionally only those matching `metadata`. */
|
|
@@ -2705,6 +2803,31 @@ var Sandbox = class _Sandbox {
|
|
|
2705
2803
|
static async usage(opts = {}) {
|
|
2706
2804
|
return new HttpClient(opts).request("GET", "/v1/usage");
|
|
2707
2805
|
}
|
|
2806
|
+
/**
|
|
2807
|
+
* The templates a create may name. Every version of a template is listed; `latest` marks the one a
|
|
2808
|
+
* create gets. GPU templates have `gpu` and list their GPU types in `gpuTypes`.
|
|
2809
|
+
*/
|
|
2810
|
+
static async listTemplates(opts = {}) {
|
|
2811
|
+
return (await new HttpClient(opts).request("GET", "/v1/templates")).templates;
|
|
2812
|
+
}
|
|
2813
|
+
/**
|
|
2814
|
+
* A page of your GPU queue entries, newest first: live ones (`queued`, `dispatched`) with their place
|
|
2815
|
+
* in line, and ended ones with their `reason`. Requires machines:read.
|
|
2816
|
+
*/
|
|
2817
|
+
static async listGpuQueue(opts = {}) {
|
|
2818
|
+
return new HttpClient(opts).request("GET", "/v1/gpu-queue", {
|
|
2819
|
+
query: { state: opts.state, limit: opts.limit, cursor: opts.cursor }
|
|
2820
|
+
});
|
|
2821
|
+
}
|
|
2822
|
+
/**
|
|
2823
|
+
* Stops a GPU queue entry's wait (`getInfo().queue.id`). A `create` entry's sandbox is deleted; a
|
|
2824
|
+
* `start` entry's stays stopped with its disks. Cancel this way, never with `kill()`, which deletes
|
|
2825
|
+
* a stopped sandbox's disks. Returns the entry, `cancelled`, or still `dispatched` with `cancelling`
|
|
2826
|
+
* when the sandbox was already starting. Requires machines:write.
|
|
2827
|
+
*/
|
|
2828
|
+
static async cancelGpuQueue(entryId, opts = {}) {
|
|
2829
|
+
return new HttpClient(opts).request("DELETE", `/v1/gpu-queue/${enc4(entryId)}`);
|
|
2830
|
+
}
|
|
2708
2831
|
/** Lists the caller's private snapshots. Requires images:read. */
|
|
2709
2832
|
static async listSnapshots(opts = {}) {
|
|
2710
2833
|
const result = await new HttpClient(opts).request("GET", "/v1/snapshots");
|
|
@@ -2823,15 +2946,23 @@ var Sandbox = class _Sandbox {
|
|
|
2823
2946
|
async pause() {
|
|
2824
2947
|
await this.mutate("POST", "suspend");
|
|
2825
2948
|
}
|
|
2826
|
-
/** Resumes a paused sandbox from its snapshot, or starts a stopped one. */
|
|
2827
|
-
async resume() {
|
|
2949
|
+
/** Resumes a paused sandbox from its snapshot, or starts a stopped one (waiting for a GPU with `queue`). */
|
|
2950
|
+
async resume(opts = {}) {
|
|
2951
|
+
const start = startBody(opts.queue);
|
|
2828
2952
|
await this.settle();
|
|
2829
|
-
await this.wake();
|
|
2953
|
+
await this.wake(start);
|
|
2830
2954
|
}
|
|
2831
|
-
/**
|
|
2832
|
-
|
|
2833
|
-
|
|
2834
|
-
|
|
2955
|
+
/**
|
|
2956
|
+
* Resumes or starts based on the cached state; callers make sure the cache is fresh. A sandbox
|
|
2957
|
+
* already waiting for a GPU is waited for: starting it again would not move it up the line.
|
|
2958
|
+
*/
|
|
2959
|
+
async wake(start) {
|
|
2960
|
+
if (this.machine.queue) this.machine = await untilPlaced(this.http, this.machine);
|
|
2961
|
+
else if (this.machine.state === "suspended") await this.mutate("POST", "resume");
|
|
2962
|
+
else if (this.machine.state === "stopped") {
|
|
2963
|
+
await this.mutate("POST", "start", start);
|
|
2964
|
+
this.machine = await untilPlaced(this.http, this.machine);
|
|
2965
|
+
}
|
|
2835
2966
|
}
|
|
2836
2967
|
/** Stops the sandbox (guest shutdown; processes end, `/data` is kept). */
|
|
2837
2968
|
async stop() {
|
|
@@ -2904,8 +3035,9 @@ var Sandbox = class _Sandbox {
|
|
|
2904
3035
|
this.machine = await getMachine(this.http, this.sandboxId);
|
|
2905
3036
|
}
|
|
2906
3037
|
}
|
|
2907
|
-
async mutate(method, action) {
|
|
2908
|
-
const
|
|
3038
|
+
async mutate(method, action, body) {
|
|
3039
|
+
const path = `/v1/machines/${enc4(this.sandboxId)}/${action}`;
|
|
3040
|
+
const op = await this.http.request(method, path, body ? { body } : {});
|
|
2909
3041
|
await this.http.waitForOperation(op);
|
|
2910
3042
|
this.machine = await getMachine(this.http, this.sandboxId);
|
|
2911
3043
|
}
|
|
@@ -2913,6 +3045,66 @@ var Sandbox = class _Sandbox {
|
|
|
2913
3045
|
async function getMachine(http, id) {
|
|
2914
3046
|
return http.request("GET", `/v1/machines/${enc4(id)}`);
|
|
2915
3047
|
}
|
|
3048
|
+
function startBody(queue) {
|
|
3049
|
+
return queue === void 0 ? void 0 : { queue: queueBody(queue) };
|
|
3050
|
+
}
|
|
3051
|
+
async function untilPlaced(http, m) {
|
|
3052
|
+
let last = m.queue;
|
|
3053
|
+
if (!last) return m;
|
|
3054
|
+
let orgId = m.orgId;
|
|
3055
|
+
let delay = http.pollIntervalMs;
|
|
3056
|
+
let waited;
|
|
3057
|
+
for (; ; ) {
|
|
3058
|
+
if (m.queue) last = m.queue;
|
|
3059
|
+
else if (m.state === "running") return m;
|
|
3060
|
+
else if (m.state !== "starting" && m.state !== "creating") throw await queueEnded(http, last, m, orgId);
|
|
3061
|
+
if (m.operationId && m.operationId !== waited) {
|
|
3062
|
+
waited = m.operationId;
|
|
3063
|
+
const op = await http.request("GET", `/v1/operations/${enc4(m.operationId)}`);
|
|
3064
|
+
await http.waitForOperation(op);
|
|
3065
|
+
} else {
|
|
3066
|
+
const deadline = Date.parse(last.expiresAt) + http.operationTimeoutMs;
|
|
3067
|
+
if (Date.now() + delay > deadline) {
|
|
3068
|
+
throw new InstaboxTimeoutError(
|
|
3069
|
+
`${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}')`,
|
|
3070
|
+
{ code: "operation_timeout" }
|
|
3071
|
+
);
|
|
3072
|
+
}
|
|
3073
|
+
await sleep(delay);
|
|
3074
|
+
delay = Math.min(Math.round(delay * 1.5), Math.max(5e3, http.pollIntervalMs));
|
|
3075
|
+
}
|
|
3076
|
+
try {
|
|
3077
|
+
m = await getMachine(http, m.id);
|
|
3078
|
+
} catch (err) {
|
|
3079
|
+
if (err instanceof InstaboxError && err.status === 404) throw await queueEnded(http, last, void 0, orgId);
|
|
3080
|
+
throw err;
|
|
3081
|
+
}
|
|
3082
|
+
orgId = m.orgId ?? orgId;
|
|
3083
|
+
}
|
|
3084
|
+
}
|
|
3085
|
+
var QUEUE_ENDS = {
|
|
3086
|
+
expired: "no GPU freed up within the wait",
|
|
3087
|
+
cancelled: "the request was cancelled",
|
|
3088
|
+
failed: "the start failed"
|
|
3089
|
+
};
|
|
3090
|
+
async function queueEnded(http, q2, m, orgId) {
|
|
3091
|
+
let entry;
|
|
3092
|
+
try {
|
|
3093
|
+
let cursor;
|
|
3094
|
+
for (let i = 0; i < 3 && !entry; i++) {
|
|
3095
|
+
const page = await http.request("GET", "/v1/gpu-queue", { query: { orgId, limit: 200, cursor } });
|
|
3096
|
+
entry = page.entries.find((e) => e.id === q2.id);
|
|
3097
|
+
cursor = page.nextCursor;
|
|
3098
|
+
if (!cursor) break;
|
|
3099
|
+
}
|
|
3100
|
+
} catch (err) {
|
|
3101
|
+
if (!(err instanceof InstaboxError)) throw err;
|
|
3102
|
+
}
|
|
3103
|
+
const what = QUEUE_ENDS[entry?.state ?? ""] ?? "the request ended";
|
|
3104
|
+
const left = !m || q2.kind === "create" ? "it was deleted" : `it is ${m.state} with its disks`;
|
|
3105
|
+
const code = entry?.reason || (entry ? `queue_${entry.state}` : "queue_ended");
|
|
3106
|
+
return new InstaboxError(`sandbox stopped waiting for a ${q2.gpuType ?? ""} GPU: ${what}; ${left}`, { code });
|
|
3107
|
+
}
|
|
2916
3108
|
async function getMetrics(http, id, opts) {
|
|
2917
3109
|
const out = await http.request("GET", `/v1/machines/${enc4(id)}/metrics`, {
|
|
2918
3110
|
query: { since: opts.since?.toISOString() }
|