@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/dist/index.d.ts CHANGED
@@ -83,6 +83,76 @@ interface MachineSpec {
83
83
  memMiB: number;
84
84
  persistentDiskGiB: number;
85
85
  rootDiskGiB?: number;
86
+ /** GPUs of `gpuType` the sandbox has; absent on a sandbox without one. */
87
+ gpus?: number;
88
+ /** The GPU type of its GPUs (a `TemplateGpuType.type`); absent on a sandbox without one. */
89
+ gpuType?: string;
90
+ }
91
+ /**
92
+ * A sandbox's live GPU queue entry (`Machine.queue`): a create or start with `queue` found no GPU of
93
+ * its type free, so the sandbox waits, stopped and holding no GPU, for one.
94
+ */
95
+ interface MachineQueue {
96
+ /** Cancel it with `Sandbox.cancelGpuQueue(id)`, never by killing the sandbox (that deletes a stopped one's disks). */
97
+ id: string;
98
+ /** `create`: the sandbox has no disks yet, and an expiry or a cancel deletes it. `start`: it stays stopped with its disks. */
99
+ kind: 'create' | 'start';
100
+ gpuType?: string;
101
+ gpus?: number;
102
+ /** `queued`: waiting for a GPU. `dispatched`: a GPU is claimed and the sandbox is starting. */
103
+ state: 'queued' | 'offered' | 'dispatched' | (string & {});
104
+ /** Place in line among the type's queued entries, from 1; absent unless queued. */
105
+ position?: number;
106
+ enqueuedAt: string;
107
+ /** When a still queued entry gives up. */
108
+ expiresAt: string;
109
+ /** A cancel was asked while the sandbox was starting: it is stopped (or deleted) when the start ends. */
110
+ cancelling?: boolean;
111
+ }
112
+ /** One entry of `Sandbox.listGpuQueue()`. */
113
+ interface GpuQueueEntry {
114
+ id: string;
115
+ orgId: string;
116
+ machineId: string;
117
+ /** Absent once the sandbox is deleted. */
118
+ machineName?: string;
119
+ kind: 'create' | 'start';
120
+ gpuType: string;
121
+ gpus: number;
122
+ /** `queued` and `dispatched` are live; `placed` (the sandbox ran), `expired`, `cancelled` and `failed` are ends. */
123
+ state: 'queued' | 'dispatched' | 'placed' | 'expired' | 'cancelled' | 'failed' | (string & {});
124
+ position?: number;
125
+ enqueuedAt: string;
126
+ expiresAt: string;
127
+ /** When the entry ended; absent while live. */
128
+ resolvedAt?: string;
129
+ /** Why an ended entry ended: `queue_expired`, `user` or `machine_deleted`, or for `failed` the refusal's error code. */
130
+ reason?: string;
131
+ cancelling?: boolean;
132
+ }
133
+ /** Response of `GET /v1/gpu-queue`. */
134
+ interface GpuQueuePage {
135
+ entries: GpuQueueEntry[];
136
+ /** Pass as `cursor` for the next page; absent on the last page. */
137
+ nextCursor?: string;
138
+ }
139
+ /** A GPU type a GPU template offers (`Template.gpuTypes`). */
140
+ interface TemplateGpuType {
141
+ /** What `gpu` names on create, such as `l4`. */
142
+ type: string;
143
+ /** Such as `NVIDIA L4`. */
144
+ model: string;
145
+ /** GPU memory per GPU. */
146
+ memGiB: number;
147
+ /** The sizes a create may pick, per GPU: N GPUs get N times the vCPUs and memory, and the disk once. */
148
+ sizes: MachineSpec[];
149
+ maxPerMachine: number;
150
+ /** The GPU counts a create may ask for (`l4:2`), such as `[1, 2, 4]`. */
151
+ counts?: number[];
152
+ /** This template is the one a create with this GPU type and no template gets. */
153
+ default?: boolean;
154
+ /** GPUs of this type waiting in the GPU queue now. */
155
+ queued?: number;
86
156
  }
87
157
  interface TemplateRef {
88
158
  id: string;
@@ -100,6 +170,8 @@ interface Machine {
100
170
  snapshot?: {
101
171
  id: string;
102
172
  };
173
+ /** The org the sandbox counts against. */
174
+ orgId?: string;
103
175
  spec: MachineSpec;
104
176
  storage: {
105
177
  sizeGiB: number;
@@ -125,6 +197,8 @@ interface Machine {
125
197
  * Absent on servers without the Vault: treat as true.
126
198
  */
127
199
  vault?: boolean;
200
+ /** The sandbox's live GPU queue entry; absent unless it waits for a GPU. */
201
+ queue?: MachineQueue;
128
202
  createdAt: string;
129
203
  updatedAt: string;
130
204
  }
@@ -205,6 +279,14 @@ interface Template {
205
279
  defaultSpec: MachineSpec;
206
280
  /** True when the server's release no longer builds it: listed, but new sandboxes are refused. */
207
281
  hidden?: boolean;
282
+ /** The version a create naming this template gets. Every version is listed; one per template has this. */
283
+ latest?: boolean;
284
+ /** A GPU template: a create from it needs `gpu`, and a create with `gpu` takes only a GPU template. */
285
+ gpu?: boolean;
286
+ /** On a GPU template: `vm` (absent means `vm`) or `metal` (whole GPUs on bare metal). */
287
+ gpuMode?: 'vm' | 'metal' | (string & {});
288
+ /** On a GPU template, the GPU types a create from it may ask for. */
289
+ gpuTypes?: TemplateGpuType[];
208
290
  }
209
291
  interface SnapshotList {
210
292
  snapshots: Snapshot[];
@@ -235,6 +317,12 @@ interface MachineMetric {
235
317
  /** Not reported yet; absent. */
236
318
  diskUsed?: number;
237
319
  diskTotal: number;
320
+ /** GPU sandboxes: share of the time a kernel ran on its GPUs, averaged over them (0-100). */
321
+ gpuUsedPct?: number;
322
+ /** GPU sandboxes: GPU memory in use, summed over its GPUs. */
323
+ gpuMemUsed?: number;
324
+ gpuCount?: number;
325
+ gpuMemTotal?: number;
238
326
  }
239
327
  /** Response of `GET /v1/machines/{id}/metrics`. */
240
328
  interface MachineMetrics {
@@ -249,6 +337,10 @@ interface MachineUsage {
249
337
  memGiBSeconds: number;
250
338
  diskGiBSeconds: number;
251
339
  egressBytes?: number;
340
+ gpus?: number;
341
+ gpuType?: string;
342
+ gpuSeconds?: number;
343
+ gpuUSD?: number;
252
344
  }
253
345
  /** One sandbox's share of `Usage.storedBytes`. */
254
346
  interface UsageMachineStorage {
@@ -280,6 +372,16 @@ interface UsageLimits {
280
372
  maxBytes: number;
281
373
  };
282
374
  }
375
+ /** One GPU type's usage this month (`UsageCost.gpu`). */
376
+ interface GpuUsage {
377
+ type: string;
378
+ model?: string;
379
+ /** Running time times GPUs. */
380
+ gpuHours: number;
381
+ /** The current price per GPU-hour (0: not priced). */
382
+ hourUSD: number;
383
+ usd: number;
384
+ }
283
385
  /**
284
386
  * `Usage.cost`: the workspace's usage this calendar month (UTC) in USD, as the hourly rating priced
285
387
  * it, with its allowance and credit balance. The same figures as `GET /v1/orgs/{id}` `usage`.
@@ -336,6 +438,10 @@ interface UsageCost {
336
438
  creditsUsedUSD: number;
337
439
  /** Usage beyond the allowance already charged this month (threshold billing). */
338
440
  chargedUSD?: number;
441
+ /** This month's GPU time by GPU type; absent without GPU usage this month. */
442
+ gpu?: GpuUsage[];
443
+ /** The GPU part of `costUSD`. */
444
+ gpuUSD?: number;
339
445
  }
340
446
  /** Response of `GET /v1/usage`: your counts, stored bytes (measured about hourly) and limits. */
341
447
  interface Usage {
@@ -573,6 +679,52 @@ declare class Commands {
573
679
  private waitJob;
574
680
  }
575
681
 
682
+ interface ComputerUseTool {
683
+ name: string;
684
+ description?: string;
685
+ /** JSON Schema of the tool's arguments. */
686
+ inputSchema?: Record<string, unknown>;
687
+ }
688
+ interface ComputerUseImage {
689
+ mimeType: string;
690
+ data: Uint8Array;
691
+ }
692
+ interface ComputerUseResult {
693
+ /** The text parts of the result, joined by newlines. */
694
+ text: string;
695
+ /** The image parts of the result (screenshots), decoded. */
696
+ images: ComputerUseImage[];
697
+ /** The tool reported an error; `text` says what. */
698
+ isError: boolean;
699
+ /** The tool's structured result, when it returns one. */
700
+ structuredContent?: unknown;
701
+ }
702
+ interface ComputerUseCallOptions {
703
+ /** Give up after this long (at most 600 000; default 60 s). */
704
+ timeoutMs?: number;
705
+ signal?: AbortSignal;
706
+ }
707
+ /**
708
+ * The sandbox's computer-use MCP server (`instabox-computer-use mcp`, on Linux, macOS and Windows
709
+ * desktop templates): its tools read apps' accessibility trees, take screenshots, and click and type
710
+ * into windows. Each call starts the server anew in the sandbox, so what one call read does not carry
711
+ * to the next; cua-driver's `run_steps` tool runs several actions in one call.
712
+ */
713
+ declare class ComputerUse {
714
+ private readonly commands;
715
+ /** @internal */
716
+ constructor(commands: Commands);
717
+ /** The server's tools, with their argument schemas. */
718
+ tools(opts?: ComputerUseCallOptions): Promise<ComputerUseTool[]>;
719
+ /**
720
+ * Calls one tool, for example `call('get_desktop_state')` for a screenshot of the whole screen or
721
+ * `call('list_windows')`. A tool that fails resolves with `isError: true`; it does not throw.
722
+ */
723
+ call(name: string, args?: Record<string, unknown>, opts?: ComputerUseCallOptions): Promise<ComputerUseResult>;
724
+ /** One request to a server started for it: the handshake and the request go in as stdin. */
725
+ private request;
726
+ }
727
+
576
728
  /**
577
729
  * Default cap of a buffered `files.read` (raise it with `maxBytes`, or use `readStream`), and the most
578
730
  * `files.write` moves on a server without the file routes (over exec). Over the file routes `write`
@@ -900,6 +1052,13 @@ declare class Ports {
900
1052
  declare const DEFAULT_TEMPLATE = "agent-browser";
901
1053
  /** The default when a server does not offer `DEFAULT_TEMPLATE` (an older or self-hosted one). */
902
1054
  declare const FALLBACK_TEMPLATE = "universal";
1055
+ /**
1056
+ * Wait in the GPU queue when no GPU of the type is free, instead of failing with `no_capacity`.
1057
+ * `true` waits up to an hour; `maxWaitMs` is sent as whole seconds, 60 s to 24 h.
1058
+ */
1059
+ type GpuQueueOpt = true | {
1060
+ maxWaitMs: number;
1061
+ };
903
1062
  interface SandboxOpts extends ConnectionOptions {
904
1063
  /** Machine name: lowercase letters, digits and `-`. Default `sbx-<random>`. */
905
1064
  name?: string;
@@ -931,6 +1090,19 @@ interface SandboxOpts extends ConnectionOptions {
931
1090
  * Default: the sandbox gets them. Cannot be turned on again later.
932
1091
  */
933
1092
  vault?: boolean;
1093
+ /**
1094
+ * GPUs for the sandbox (paid plans): `TYPE` or `TYPE:COUNT`, such as `'l4'` or `'h100:2'`; the types
1095
+ * and counts are in `Sandbox.listTemplates()` (`gpuTypes` of the templates with `gpu`). Without a
1096
+ * template argument the server picks the GPU type's default template.
1097
+ */
1098
+ gpu?: string;
1099
+ /**
1100
+ * With `gpu`: when no GPU of the type is free, the sandbox waits in the GPU queue (stopped,
1101
+ * `getInfo().queue` set) and `create` waits with it until the sandbox runs. If the wait ends first,
1102
+ * `create` throws `InstaboxError` with the entry's reason as `code` (`queue_expired`), and the sandbox
1103
+ * is deleted.
1104
+ */
1105
+ queue?: GpuQueueOpt;
934
1106
  /**
935
1107
  * @deprecated Removed in 0.6.0: sandboxes have no lifetime timeout since 2026-10-20. Passing it throws
936
1108
  * `InstaboxError` (`code: 'retired_option'`); use `autoSuspendMs`, `archiveMs` or `kill()` instead.
@@ -943,6 +1115,23 @@ interface SandboxConnectOpts extends ConnectionOptions {
943
1115
  /** Resume the sandbox if it is paused (suspended) or stopped. Default true. */
944
1116
  resume?: boolean;
945
1117
  envs?: Record<string, string>;
1118
+ /** Starting a stopped GPU sandbox: wait in the GPU queue when no GPU is free (see `SandboxOpts.queue`). */
1119
+ queue?: GpuQueueOpt;
1120
+ }
1121
+ interface ResumeOpts {
1122
+ /**
1123
+ * Starting a stopped GPU sandbox: wait in the GPU queue when no GPU is free. If the wait ends first,
1124
+ * this throws `InstaboxError` with the entry's reason as `code`, and the sandbox stays stopped with
1125
+ * its disks. A paused sandbox resumes on the GPU it holds and ignores it.
1126
+ */
1127
+ queue?: GpuQueueOpt;
1128
+ }
1129
+ interface GpuQueueListOpts extends ConnectionOptions {
1130
+ state?: GpuQueueEntry['state'];
1131
+ /** Page size, 1-200. Default: the server's (50). */
1132
+ limit?: number;
1133
+ /** `nextCursor` of the previous page. */
1134
+ cursor?: string;
946
1135
  }
947
1136
  interface SandboxListOpts extends ConnectionOptions {
948
1137
  /** Only sandboxes whose metadata has every one of these key/value pairs. */
@@ -965,6 +1154,13 @@ interface SandboxInfo {
965
1154
  /** Idle time after which the server pauses the sandbox; undefined when it never does. */
966
1155
  autoSuspendMs?: number;
967
1156
  state: MachineState;
1157
+ /** The sandbox's GPUs; absent on a sandbox without one. */
1158
+ gpu?: {
1159
+ type: string;
1160
+ count: number;
1161
+ };
1162
+ /** Its live GPU queue entry; absent unless it waits for a GPU. */
1163
+ queue?: MachineQueue;
968
1164
  /** The raw machine object from the API. */
969
1165
  machine: Machine;
970
1166
  }
@@ -992,6 +1188,13 @@ interface SandboxMetrics {
992
1188
  diskUsed?: number;
993
1189
  /** System disk plus /data disk size. */
994
1190
  diskTotal: number;
1191
+ /** GPU sandboxes: share of the time a kernel ran on its GPUs, averaged over them (0-100). Absent where the host did not read it. */
1192
+ gpuUsedPct?: number;
1193
+ /** GPU sandboxes: GPU memory in use, summed over its GPUs. */
1194
+ gpuMemUsed?: number;
1195
+ gpuCount?: number;
1196
+ /** GPU sandboxes: the GPU type's memory times `gpuCount`. */
1197
+ gpuMemTotal?: number;
995
1198
  }
996
1199
  interface SandboxMetricsOpts {
997
1200
  /** Start of the samples, at most 24 h ago. Default: 5 minutes ago. */
@@ -1014,6 +1217,13 @@ interface SandboxUsage {
1014
1217
  * Billed or not (the plan's free egress and free sandboxes included). Absent from older servers.
1015
1218
  */
1016
1219
  egressBytes?: number;
1220
+ /** The sandbox's GPUs and their type; absent without one. */
1221
+ gpus?: number;
1222
+ gpuType?: string;
1223
+ /** GPUs times running seconds. */
1224
+ gpuSeconds?: number;
1225
+ /** That GPU time at the type's price per GPU-hour. */
1226
+ gpuUSD?: number;
1017
1227
  }
1018
1228
  interface SandboxUsageOpts {
1019
1229
  /** Default: the start of the current calendar month (UTC). */
@@ -1044,6 +1254,8 @@ declare class Sandbox {
1044
1254
  readonly files: Files;
1045
1255
  /** See and control the sandbox's graphical desktop (screenshots, mouse, keyboard, a link to watch it). */
1046
1256
  readonly desktop: Desktop;
1257
+ /** The sandbox's computer-use MCP tools: accessibility trees, screenshots, clicks and typing in apps. */
1258
+ readonly computerUse: ComputerUse;
1047
1259
  /** Publish a port at an HTTPS URL, list published ports, unpublish them. */
1048
1260
  readonly ports: Ports;
1049
1261
  private machine;
@@ -1070,6 +1282,23 @@ declare class Sandbox {
1070
1282
  static getUsage(sandboxId: string, opts?: SandboxUsageOpts & ConnectionOptions): Promise<SandboxUsage>;
1071
1283
  /** Your account's counts, stored bytes (per sandbox in `storage`) and limits. Requires machines:read or images:read. */
1072
1284
  static usage(opts?: ConnectionOptions): Promise<Usage>;
1285
+ /**
1286
+ * The templates a create may name. Every version of a template is listed; `latest` marks the one a
1287
+ * create gets. GPU templates have `gpu` and list their GPU types in `gpuTypes`.
1288
+ */
1289
+ static listTemplates(opts?: ConnectionOptions): Promise<Template[]>;
1290
+ /**
1291
+ * A page of your GPU queue entries, newest first: live ones (`queued`, `dispatched`) with their place
1292
+ * in line, and ended ones with their `reason`. Requires machines:read.
1293
+ */
1294
+ static listGpuQueue(opts?: GpuQueueListOpts): Promise<GpuQueuePage>;
1295
+ /**
1296
+ * Stops a GPU queue entry's wait (`getInfo().queue.id`). A `create` entry's sandbox is deleted; a
1297
+ * `start` entry's stays stopped with its disks. Cancel this way, never with `kill()`, which deletes
1298
+ * a stopped sandbox's disks. Returns the entry, `cancelled`, or still `dispatched` with `cancelling`
1299
+ * when the sandbox was already starting. Requires machines:write.
1300
+ */
1301
+ static cancelGpuQueue(entryId: string, opts?: ConnectionOptions): Promise<GpuQueueEntry>;
1073
1302
  /** Lists the caller's private snapshots. Requires images:read. */
1074
1303
  static listSnapshots(opts?: ConnectionOptions): Promise<Snapshot[]>;
1075
1304
  /** Fetches a snapshot by ID. Requires images:read. */
@@ -1129,9 +1358,12 @@ declare class Sandbox {
1129
1358
  isRunning(): Promise<boolean>;
1130
1359
  /** Snapshots memory and stops the sandbox (suspend). `resume()` or `Sandbox.connect()` brings it back. */
1131
1360
  pause(): Promise<void>;
1132
- /** Resumes a paused sandbox from its snapshot, or starts a stopped one. */
1133
- resume(): Promise<void>;
1134
- /** Resumes or starts based on the cached state; callers make sure the cache is fresh. */
1361
+ /** Resumes a paused sandbox from its snapshot, or starts a stopped one (waiting for a GPU with `queue`). */
1362
+ resume(opts?: ResumeOpts): Promise<void>;
1363
+ /**
1364
+ * Resumes or starts based on the cached state; callers make sure the cache is fresh. A sandbox
1365
+ * already waiting for a GPU is waited for: starting it again would not move it up the line.
1366
+ */
1135
1367
  private wake;
1136
1368
  /** Stops the sandbox (guest shutdown; processes end, `/data` is kept). */
1137
1369
  stop(): Promise<void>;
@@ -1162,4 +1394,4 @@ declare class Sandbox {
1162
1394
  private mutate;
1163
1395
  }
1164
1396
 
1165
- export { type ApiError, CommandExitError, type CommandHandle, type CommandOptions, type CommandResult, type CommandWaitOptions, Commands, type Connection, type ConnectionOptions, type CreateSnapshotOpts, DEFAULT_API_URL, DEFAULT_TEMPLATE, DESKTOP_DISPLAY, Desktop, type DesktopStatus, type DesktopStream, type DownloadInfo, type DownloadOptions, type EntryInfo, type ExecResponse, FALLBACK_TEMPLATE, type FileStream, Files, type HostTrust, InstaboxAuthError, InstaboxError, type InstaboxErrorInit, InstaboxNotUtf8Error, InstaboxQuotaError, InstaboxTimeoutError, LIMIT_CODES, MAX_FILE_BYTES, MAX_STDIN_BYTES, MAX_UPLOAD_BYTES, type Machine, type MachineList, type MachineMetric, type MachineMetrics, type MachineSpec, type MachineState, type MachineUsage, type MachineVault, type MachineVaultItem, type MouseButton, type Operation, type PortAccess, Ports, type PublicPort, type PublishPortOpts, type ReadStreamOptions, type ResizeOpts, Sandbox, type SandboxConnectOpts, type SandboxInfo, type SandboxListOpts, type SandboxMetrics, type SandboxMetricsOpts, type SandboxOpts, type SandboxUsage, type SandboxUsageOpts, type ScrollDirection, type Snapshot, type SnapshotList, type SshCredentials, type Template, type TemplateRef, type UploadInfo, type UploadOptions, type Usage, type UsageCost, type UsageLimits, type UsageMachineStorage, type UsageStorage, type VaultApplied, type VaultFile, type VaultKept, type WriteData, type WriteInfo, type WriteOptions, isLimitCode };
1397
+ export { type ApiError, CommandExitError, type CommandHandle, type CommandOptions, type CommandResult, type CommandWaitOptions, Commands, ComputerUse, type ComputerUseCallOptions, type ComputerUseImage, type ComputerUseResult, type ComputerUseTool, type Connection, type ConnectionOptions, type CreateSnapshotOpts, DEFAULT_API_URL, DEFAULT_TEMPLATE, DESKTOP_DISPLAY, Desktop, type DesktopStatus, type DesktopStream, type DownloadInfo, type DownloadOptions, type EntryInfo, type ExecResponse, FALLBACK_TEMPLATE, type FileStream, Files, type GpuQueueEntry, type GpuQueueListOpts, type GpuQueueOpt, type GpuQueuePage, type GpuUsage, type HostTrust, InstaboxAuthError, InstaboxError, type InstaboxErrorInit, InstaboxNotUtf8Error, InstaboxQuotaError, InstaboxTimeoutError, LIMIT_CODES, MAX_FILE_BYTES, MAX_STDIN_BYTES, MAX_UPLOAD_BYTES, type Machine, type MachineList, type MachineMetric, type MachineMetrics, type MachineQueue, type MachineSpec, type MachineState, type MachineUsage, type MachineVault, type MachineVaultItem, type MouseButton, type Operation, type PortAccess, Ports, type PublicPort, type PublishPortOpts, type ReadStreamOptions, type ResizeOpts, type ResumeOpts, Sandbox, type SandboxConnectOpts, type SandboxInfo, type SandboxListOpts, type SandboxMetrics, type SandboxMetricsOpts, type SandboxOpts, type SandboxUsage, type SandboxUsageOpts, type ScrollDirection, type Snapshot, type SnapshotList, type SshCredentials, type Template, type TemplateGpuType, type TemplateRef, type UploadInfo, type UploadOptions, type Usage, type UsageCost, type UsageLimits, type UsageMachineStorage, type UsageStorage, type VaultApplied, type VaultFile, type VaultKept, type WriteData, type WriteInfo, type WriteOptions, isLimitCode };
package/dist/index.js CHANGED
@@ -616,6 +616,92 @@ ${value}`;
616
616
  }
617
617
  };
618
618
 
619
+ // src/computer-use.ts
620
+ var ComputerUse = class {
621
+ /** @internal */
622
+ constructor(commands) {
623
+ this.commands = commands;
624
+ }
625
+ commands;
626
+ /** The server's tools, with their argument schemas. */
627
+ async tools(opts = {}) {
628
+ const r = await this.request("tools/list", void 0, opts);
629
+ return r.tools ?? [];
630
+ }
631
+ /**
632
+ * Calls one tool, for example `call('get_desktop_state')` for a screenshot of the whole screen or
633
+ * `call('list_windows')`. A tool that fails resolves with `isError: true`; it does not throw.
634
+ */
635
+ async call(name, args = {}, opts = {}) {
636
+ if (typeof name !== "string" || !name) {
637
+ throw new InstaboxError("call needs a tool name", { code: "bad_request" });
638
+ }
639
+ if (typeof args !== "object" || args === null || Array.isArray(args)) {
640
+ throw new InstaboxError("a tool's arguments must be an object", { code: "bad_request" });
641
+ }
642
+ const r = await this.request("tools/call", { name, arguments: args }, opts);
643
+ const content = r.content ?? [];
644
+ const out = {
645
+ text: content.filter((c) => c.type === "text").map((c) => c.text ?? "").join("\n"),
646
+ images: content.filter((c) => c.type === "image").map((c) => ({ mimeType: c.mimeType ?? "", data: base64ToBytes(c.data ?? "") })),
647
+ isError: r.isError === true
648
+ };
649
+ if (r.structuredContent !== void 0) out.structuredContent = r.structuredContent;
650
+ return out;
651
+ }
652
+ /** One request to a server started for it: the handshake and the request go in as stdin. */
653
+ async request(method, params, opts) {
654
+ const msgs = [
655
+ {
656
+ jsonrpc: "2.0",
657
+ id: 1,
658
+ method: "initialize",
659
+ params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "instabox-sdk", version: "1" } }
660
+ },
661
+ { jsonrpc: "2.0", method: "notifications/initialized" },
662
+ { jsonrpc: "2.0", id: 2, method, ...params === void 0 ? {} : { params } }
663
+ ];
664
+ let stdout;
665
+ let stderr = "";
666
+ try {
667
+ const r = await this.commands.run("instabox-computer-use mcp", {
668
+ stdin: msgs.map((m) => JSON.stringify(m)).join("\n") + "\n",
669
+ onStdout: () => {
670
+ },
671
+ timeoutMs: opts.timeoutMs,
672
+ signal: opts.signal
673
+ });
674
+ stdout = r.stdout;
675
+ } catch (e) {
676
+ if (!(e instanceof CommandExitError)) throw e;
677
+ if (e.timedOut) {
678
+ throw new InstaboxTimeoutError(`the computer-use call ran past its timeout`, { code: "command_timeout" });
679
+ }
680
+ stdout = e.stdout;
681
+ stderr = e.stderr;
682
+ }
683
+ for (const line of stdout.split("\n")) {
684
+ let msg;
685
+ try {
686
+ msg = JSON.parse(line);
687
+ } catch {
688
+ continue;
689
+ }
690
+ if (msg?.id !== 2 || msg.method !== void 0) continue;
691
+ if (msg.error) {
692
+ throw new InstaboxError(`computer-use server: ${msg.error.message} (code ${msg.error.code})`, {
693
+ code: "computer_use_error"
694
+ });
695
+ }
696
+ return msg.result ?? {};
697
+ }
698
+ throw new InstaboxError(
699
+ `the sandbox's computer-use server ended without answering; is its template one with computer use?${stderr ? ` ${stderr.trim().slice(-500)}` : ""}`,
700
+ { code: "computer_use_unavailable" }
701
+ );
702
+ }
703
+ };
704
+
619
705
  // src/desktop.ts
620
706
  var DESKTOP_DISPLAY = ":1";
621
707
  var BUTTONS = { left: 1, middle: 2, right: 3 };
@@ -2521,6 +2607,8 @@ function toInfo(m) {
2521
2607
  if (m.snapshot?.id) info.snapshotId = m.snapshot.id;
2522
2608
  if (m.archiveAt) info.archiveAt = new Date(m.archiveAt);
2523
2609
  if (m.autoSuspendAfterSeconds) info.autoSuspendMs = m.autoSuspendAfterSeconds * 1e3;
2610
+ if (m.spec.gpuType && m.spec.gpus) info.gpu = { type: m.spec.gpuType, count: m.spec.gpus };
2611
+ if (m.queue) info.queue = m.queue;
2524
2612
  return info;
2525
2613
  }
2526
2614
  function timeoutRemoved(what, use) {
@@ -2548,6 +2636,9 @@ function toSeconds(ms, field) {
2548
2636
  }
2549
2637
  return s;
2550
2638
  }
2639
+ function queueBody(q2) {
2640
+ return q2 === true ? {} : { maxWaitSeconds: toSeconds(q2.maxWaitMs, "queue.maxWaitMs") };
2641
+ }
2551
2642
  function wholeCount(field, n) {
2552
2643
  if (!Number.isInteger(n) || n < 1) {
2553
2644
  throw new InstaboxError(`${field} must be a whole number from 1; got ${n}`, { code: "bad_request" });
@@ -2565,6 +2656,7 @@ var Sandbox = class _Sandbox {
2565
2656
  this.files = new Files(this.commands, http, machine.id);
2566
2657
  this.commands.stageStdin = (bytes, signal) => this.files.stageStdin(bytes, signal);
2567
2658
  this.desktop = new Desktop(http, machine.id, this.commands, this.files);
2659
+ this.computerUse = new ComputerUse(this.commands);
2568
2660
  this.ports = new Ports(http, machine.id);
2569
2661
  }
2570
2662
  http;
@@ -2576,6 +2668,8 @@ var Sandbox = class _Sandbox {
2576
2668
  files;
2577
2669
  /** See and control the sandbox's graphical desktop (screenshots, mouse, keyboard, a link to watch it). */
2578
2670
  desktop;
2671
+ /** The sandbox's computer-use MCP tools: accessibility trees, screenshots, clicks and typing in apps. */
2672
+ computerUse;
2579
2673
  /** Publish a port at an HTTPS URL, list published ports, unpublish them. */
2580
2674
  ports;
2581
2675
  machine;
@@ -2594,8 +2688,10 @@ var Sandbox = class _Sandbox {
2594
2688
  const body = { name: opts.name ?? `sbx-${randomSuffix()}` };
2595
2689
  if (opts.archiveMs !== void 0) body.archiveSeconds = toSeconds(opts.archiveMs, "archiveMs");
2596
2690
  if (opts.autoSuspendMs !== void 0) body.autoSuspendAfterSeconds = toIdleSeconds(opts.autoSuspendMs);
2597
- const template = typeof a === "string" ? a : await defaultTemplate(http);
2598
- Object.assign(body, await resolveSource(http, template));
2691
+ if (opts.queue !== void 0) body.queue = queueBody(opts.queue);
2692
+ if (typeof a === "string") Object.assign(body, await resolveSource(http, a));
2693
+ else if (!opts.gpu) Object.assign(body, await resolveSource(http, await defaultTemplate(http)));
2694
+ if (opts.gpu) body.gpu = opts.gpu;
2599
2695
  if (opts.vcpus !== void 0) body.vcpus = opts.vcpus;
2600
2696
  if (opts.memMiB !== void 0) body.memMiB = opts.memMiB;
2601
2697
  if (opts.diskGiB !== void 0) body.persistentDiskGiB = opts.diskGiB;
@@ -2604,15 +2700,16 @@ var Sandbox = class _Sandbox {
2604
2700
  if (opts.vault === false) body.vault = false;
2605
2701
  const op = await createMachine(http, body);
2606
2702
  const done = await http.waitForOperation(op);
2607
- const machine = await getMachine(http, done.machineId);
2703
+ const machine = await untilPlaced(http, await getMachine(http, done.machineId));
2608
2704
  return new _Sandbox(http, machine, opts);
2609
2705
  }
2610
2706
  /** Attaches to an existing sandbox. Resumes it if it is paused or stopped, unless `resume: false`. */
2611
2707
  static async connect(sandboxId, opts = {}) {
2708
+ const start = startBody(opts.queue);
2612
2709
  const http = new HttpClient(opts);
2613
2710
  const sbx = new _Sandbox(http, await getMachine(http, sandboxId), opts);
2614
2711
  await sbx.settle(false);
2615
- if (opts.resume !== false) await sbx.wake();
2712
+ if (opts.resume !== false) await sbx.wake(start);
2616
2713
  return sbx;
2617
2714
  }
2618
2715
  /** Lists your sandboxes (all pages), optionally only those matching `metadata`. */
@@ -2650,6 +2747,31 @@ var Sandbox = class _Sandbox {
2650
2747
  static async usage(opts = {}) {
2651
2748
  return new HttpClient(opts).request("GET", "/v1/usage");
2652
2749
  }
2750
+ /**
2751
+ * The templates a create may name. Every version of a template is listed; `latest` marks the one a
2752
+ * create gets. GPU templates have `gpu` and list their GPU types in `gpuTypes`.
2753
+ */
2754
+ static async listTemplates(opts = {}) {
2755
+ return (await new HttpClient(opts).request("GET", "/v1/templates")).templates;
2756
+ }
2757
+ /**
2758
+ * A page of your GPU queue entries, newest first: live ones (`queued`, `dispatched`) with their place
2759
+ * in line, and ended ones with their `reason`. Requires machines:read.
2760
+ */
2761
+ static async listGpuQueue(opts = {}) {
2762
+ return new HttpClient(opts).request("GET", "/v1/gpu-queue", {
2763
+ query: { state: opts.state, limit: opts.limit, cursor: opts.cursor }
2764
+ });
2765
+ }
2766
+ /**
2767
+ * Stops a GPU queue entry's wait (`getInfo().queue.id`). A `create` entry's sandbox is deleted; a
2768
+ * `start` entry's stays stopped with its disks. Cancel this way, never with `kill()`, which deletes
2769
+ * a stopped sandbox's disks. Returns the entry, `cancelled`, or still `dispatched` with `cancelling`
2770
+ * when the sandbox was already starting. Requires machines:write.
2771
+ */
2772
+ static async cancelGpuQueue(entryId, opts = {}) {
2773
+ return new HttpClient(opts).request("DELETE", `/v1/gpu-queue/${enc4(entryId)}`);
2774
+ }
2653
2775
  /** Lists the caller's private snapshots. Requires images:read. */
2654
2776
  static async listSnapshots(opts = {}) {
2655
2777
  const result = await new HttpClient(opts).request("GET", "/v1/snapshots");
@@ -2768,15 +2890,23 @@ var Sandbox = class _Sandbox {
2768
2890
  async pause() {
2769
2891
  await this.mutate("POST", "suspend");
2770
2892
  }
2771
- /** Resumes a paused sandbox from its snapshot, or starts a stopped one. */
2772
- async resume() {
2893
+ /** Resumes a paused sandbox from its snapshot, or starts a stopped one (waiting for a GPU with `queue`). */
2894
+ async resume(opts = {}) {
2895
+ const start = startBody(opts.queue);
2773
2896
  await this.settle();
2774
- await this.wake();
2897
+ await this.wake(start);
2775
2898
  }
2776
- /** Resumes or starts based on the cached state; callers make sure the cache is fresh. */
2777
- async wake() {
2778
- if (this.machine.state === "suspended") await this.mutate("POST", "resume");
2779
- else if (this.machine.state === "stopped") await this.mutate("POST", "start");
2899
+ /**
2900
+ * Resumes or starts based on the cached state; callers make sure the cache is fresh. A sandbox
2901
+ * already waiting for a GPU is waited for: starting it again would not move it up the line.
2902
+ */
2903
+ async wake(start) {
2904
+ if (this.machine.queue) this.machine = await untilPlaced(this.http, this.machine);
2905
+ else if (this.machine.state === "suspended") await this.mutate("POST", "resume");
2906
+ else if (this.machine.state === "stopped") {
2907
+ await this.mutate("POST", "start", start);
2908
+ this.machine = await untilPlaced(this.http, this.machine);
2909
+ }
2780
2910
  }
2781
2911
  /** Stops the sandbox (guest shutdown; processes end, `/data` is kept). */
2782
2912
  async stop() {
@@ -2849,8 +2979,9 @@ var Sandbox = class _Sandbox {
2849
2979
  this.machine = await getMachine(this.http, this.sandboxId);
2850
2980
  }
2851
2981
  }
2852
- async mutate(method, action) {
2853
- const op = await this.http.request(method, `/v1/machines/${enc4(this.sandboxId)}/${action}`);
2982
+ async mutate(method, action, body) {
2983
+ const path = `/v1/machines/${enc4(this.sandboxId)}/${action}`;
2984
+ const op = await this.http.request(method, path, body ? { body } : {});
2854
2985
  await this.http.waitForOperation(op);
2855
2986
  this.machine = await getMachine(this.http, this.sandboxId);
2856
2987
  }
@@ -2858,6 +2989,66 @@ var Sandbox = class _Sandbox {
2858
2989
  async function getMachine(http, id) {
2859
2990
  return http.request("GET", `/v1/machines/${enc4(id)}`);
2860
2991
  }
2992
+ function startBody(queue) {
2993
+ return queue === void 0 ? void 0 : { queue: queueBody(queue) };
2994
+ }
2995
+ async function untilPlaced(http, m) {
2996
+ let last = m.queue;
2997
+ if (!last) return m;
2998
+ let orgId = m.orgId;
2999
+ let delay = http.pollIntervalMs;
3000
+ let waited;
3001
+ for (; ; ) {
3002
+ if (m.queue) last = m.queue;
3003
+ else if (m.state === "running") return m;
3004
+ else if (m.state !== "starting" && m.state !== "creating") throw await queueEnded(http, last, m, orgId);
3005
+ if (m.operationId && m.operationId !== waited) {
3006
+ waited = m.operationId;
3007
+ const op = await http.request("GET", `/v1/operations/${enc4(m.operationId)}`);
3008
+ await http.waitForOperation(op);
3009
+ } else {
3010
+ const deadline = Date.parse(last.expiresAt) + http.operationTimeoutMs;
3011
+ if (Date.now() + delay > deadline) {
3012
+ throw new InstaboxTimeoutError(
3013
+ `${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}')`,
3014
+ { code: "operation_timeout" }
3015
+ );
3016
+ }
3017
+ await sleep(delay);
3018
+ delay = Math.min(Math.round(delay * 1.5), Math.max(5e3, http.pollIntervalMs));
3019
+ }
3020
+ try {
3021
+ m = await getMachine(http, m.id);
3022
+ } catch (err) {
3023
+ if (err instanceof InstaboxError && err.status === 404) throw await queueEnded(http, last, void 0, orgId);
3024
+ throw err;
3025
+ }
3026
+ orgId = m.orgId ?? orgId;
3027
+ }
3028
+ }
3029
+ var QUEUE_ENDS = {
3030
+ expired: "no GPU freed up within the wait",
3031
+ cancelled: "the request was cancelled",
3032
+ failed: "the start failed"
3033
+ };
3034
+ async function queueEnded(http, q2, m, orgId) {
3035
+ let entry;
3036
+ try {
3037
+ let cursor;
3038
+ for (let i = 0; i < 3 && !entry; i++) {
3039
+ const page = await http.request("GET", "/v1/gpu-queue", { query: { orgId, limit: 200, cursor } });
3040
+ entry = page.entries.find((e) => e.id === q2.id);
3041
+ cursor = page.nextCursor;
3042
+ if (!cursor) break;
3043
+ }
3044
+ } catch (err) {
3045
+ if (!(err instanceof InstaboxError)) throw err;
3046
+ }
3047
+ const what = QUEUE_ENDS[entry?.state ?? ""] ?? "the request ended";
3048
+ const left = !m || q2.kind === "create" ? "it was deleted" : `it is ${m.state} with its disks`;
3049
+ const code = entry?.reason || (entry ? `queue_${entry.state}` : "queue_ended");
3050
+ return new InstaboxError(`sandbox stopped waiting for a ${q2.gpuType ?? ""} GPU: ${what}; ${left}`, { code });
3051
+ }
2861
3052
  async function getMetrics(http, id, opts) {
2862
3053
  const out = await http.request("GET", `/v1/machines/${enc4(id)}/metrics`, {
2863
3054
  query: { since: opts.since?.toISOString() }
@@ -2921,6 +3112,7 @@ async function resolveSource(http, ref) {
2921
3112
  export {
2922
3113
  CommandExitError,
2923
3114
  Commands,
3115
+ ComputerUse,
2924
3116
  DEFAULT_API_URL,
2925
3117
  DEFAULT_TEMPLATE,
2926
3118
  DESKTOP_DISPLAY,