@insforge/instabox-sdk 0.2.2 → 0.4.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
@@ -79,10 +79,6 @@ interface Machine {
79
79
  snapshot?: {
80
80
  id: string;
81
81
  };
82
- forkedFrom?: {
83
- machineId: string;
84
- snapshotSeq: number;
85
- };
86
82
  spec: MachineSpec;
87
83
  storage: {
88
84
  sizeGiB: number;
@@ -162,7 +158,7 @@ interface MachineList {
162
158
  interface Operation {
163
159
  id: string;
164
160
  machineId: string;
165
- type: 'create' | 'start' | 'stop' | 'suspend' | 'resume' | 'delete' | 'fork';
161
+ type: 'create' | 'start' | 'stop' | 'suspend' | 'resume' | 'delete';
166
162
  state: 'queued' | 'running' | 'succeeded' | 'failed';
167
163
  phase?: string;
168
164
  error: ApiError | null;
@@ -232,7 +228,7 @@ interface ConnectionOptions {
232
228
  apiUrl?: string;
233
229
  /** Timeout of a single HTTP request in ms. Default 60 000; exec defaults to its command timeout plus 30 000. */
234
230
  requestTimeoutMs?: number;
235
- /** Max time to wait for a lifecycle operation (create, pause, resume, fork, kill) in ms. Default 600 000. */
231
+ /** Max time to wait for a lifecycle operation (create, pause, resume, kill) in ms. Default 600 000. */
236
232
  operationTimeoutMs?: number;
237
233
  /** Custom fetch implementation (tests, proxies). Default: global `fetch`. */
238
234
  fetch?: typeof fetch;
@@ -339,7 +335,8 @@ declare class Files {
339
335
  format?: 'text';
340
336
  }): Promise<string>;
341
337
  read(path: string, opts: {
342
- format: 'bytes';
338
+ format: 'bytes'; /** @internal */
339
+ maxBytes?: number;
343
340
  }): Promise<Uint8Array>;
344
341
  /**
345
342
  * Writes a file, creating parent directories. Replaces the file atomically (temp file + rename).
@@ -354,6 +351,92 @@ declare class Files {
354
351
  exists(path: string): Promise<boolean>;
355
352
  }
356
353
 
354
+ type MouseButton = 'left' | 'right' | 'middle';
355
+ type ScrollDirection = 'up' | 'down' | 'left' | 'right';
356
+ interface DesktopStatus {
357
+ /** The desktop's packages are installed (templates other than `agent-browser` install them on first `start`). */
358
+ installed: boolean;
359
+ /** Its VNC server runs: the desktop can be seen, screenshotted and controlled. */
360
+ running: boolean;
361
+ /** Screen size in pixels while running. */
362
+ width?: number;
363
+ height?: number;
364
+ }
365
+ interface DesktopStream {
366
+ /** A page that shows the desktop full-screen; open it or embed it in an iframe. No sign-in needed. */
367
+ url: string;
368
+ expiresAt: Date;
369
+ }
370
+ /** X display the sandbox's desktop runs on. */
371
+ declare const DESKTOP_DISPLAY = ":1";
372
+ declare class Desktop {
373
+ private readonly http;
374
+ private readonly sandboxId;
375
+ private readonly commands;
376
+ private readonly files;
377
+ /** @internal */
378
+ constructor(http: HttpClient, sandboxId: string, commands: Commands, files: Files);
379
+ /**
380
+ * Starts the desktop and resolves once it runs; a running desktop is left as it is (its size too).
381
+ * On a template without the desktop it is installed first (about half a minute, once). `width` and
382
+ * `height` size the screen: 800-2560 x 600-1600, default 1280 x 800.
383
+ */
384
+ start(opts?: {
385
+ width?: number;
386
+ height?: number;
387
+ }): Promise<DesktopStatus>;
388
+ /** Whether the desktop runs, and its screen size. */
389
+ status(): Promise<DesktopStatus>;
390
+ /** A PNG of the whole screen. */
391
+ screenshot(): Promise<Uint8Array>;
392
+ /** Clicks at (x, y): the left button by default; `double` clicks twice. */
393
+ click(x: number, y: number, opts?: {
394
+ button?: MouseButton;
395
+ double?: boolean;
396
+ }): Promise<void>;
397
+ /** Moves the pointer to (x, y). */
398
+ move(x: number, y: number): Promise<void>;
399
+ /** Drags with the left button from `from` to `to`, each `[x, y]`. */
400
+ drag(from: [number, number], to: [number, number]): Promise<void>;
401
+ /** Scrolls the wheel at the pointer, `amount` notches (default 3). */
402
+ scroll(opts: {
403
+ direction: ScrollDirection;
404
+ amount?: number;
405
+ }): Promise<void>;
406
+ /** Types `text` as is (quotes, newlines and Unicode included) into the focused window. */
407
+ type(text: string, opts?: {
408
+ delayMs?: number;
409
+ }): Promise<void>;
410
+ /** Presses a key (`'Enter'`, `'a'`, `'F5'`) or a chord (`['ctrl', 'l']`). */
411
+ press(keys: string | string[]): Promise<void>;
412
+ /** Opens `url` (http or https) in the desktop's browser. */
413
+ open(url: string): Promise<void>;
414
+ /** Where the pointer is. */
415
+ cursorPosition(): Promise<{
416
+ x: number;
417
+ y: number;
418
+ }>;
419
+ /**
420
+ * A link that shows the desktop full-screen in a browser, for people without an instabox account:
421
+ * open it or embed it in an iframe. View-only by default (the server drops the viewer's input).
422
+ * `ttlSeconds`: 60 to 86 400, default 3 600. The expiry stops new connections only; a viewer already
423
+ * watching stays until they leave or `revokeStreamUrls()` is called.
424
+ */
425
+ streamUrl(opts?: {
426
+ viewOnly?: boolean;
427
+ ttlSeconds?: number;
428
+ }): Promise<DesktopStream>;
429
+ /**
430
+ * Revokes every link `streamUrl()` made for this sandbox: they stop working and open viewers are
431
+ * disconnected within a few seconds. Links made afterwards work.
432
+ */
433
+ revokeStreamUrls(): Promise<void>;
434
+ private call;
435
+ /** Runs `xdotool <args>` on the desktop's display. */
436
+ private xdo;
437
+ private run;
438
+ }
439
+
357
440
  declare const DEFAULT_TEMPLATE = "agent-browser";
358
441
  /** The default when a server does not offer `DEFAULT_TEMPLATE` (an older or self-hosted one). */
359
442
  declare const FALLBACK_TEMPLATE = "universal";
@@ -428,31 +511,6 @@ interface SandboxInfo {
428
511
  /** The raw machine object from the API. */
429
512
  machine: Machine;
430
513
  }
431
- interface ForkOpts {
432
- /** Name of the new sandbox. Default `<name>-fork-<random>`. */
433
- name?: string;
434
- vcpus?: number;
435
- memMiB?: number;
436
- /** May only grow. */
437
- diskGiB?: number;
438
- /** Root disk size in GiB; may only grow. */
439
- rootDiskGiB?: number;
440
- /** Timeout of the copy, as in `SandboxOpts.timeoutMs`. Default: none (the source's is not copied). */
441
- timeoutMs?: number;
442
- onTimeout?: OnTimeout;
443
- /** Idle pause of the copy, as in `SandboxOpts.autoSuspendMs`. Default: 30 minutes (the source's is not copied); `0`: never. */
444
- autoSuspendMs?: number;
445
- /** Metadata of the copy. Default: the source's; `{}` for none. */
446
- metadata?: Record<string, string>;
447
- /** `false`: the copy never gets the account's Vault items (a copy of a sandbox without the Vault never does). */
448
- vault?: boolean;
449
- /**
450
- * A fork needs a stopped source. When true (default), `fork()` stops the source first if needed
451
- * (running processes end, `/data` is kept) and leaves it stopped; call `resume()` to start it again.
452
- * When false, a source that is not stopped makes the call fail.
453
- */
454
- stopSource?: boolean;
455
- }
456
514
  interface CreateSnapshotOpts {
457
515
  name: string;
458
516
  description?: string;
@@ -480,6 +538,8 @@ declare class Sandbox {
480
538
  readonly commands: Commands;
481
539
  /** Read and write files. Needs a instabox server with the exec endpoint. */
482
540
  readonly files: Files;
541
+ /** See and control the sandbox's graphical desktop (screenshots, mouse, keyboard, a link to watch it). */
542
+ readonly desktop: Desktop;
483
543
  private machine;
484
544
  private constructor();
485
545
  /**
@@ -552,8 +612,6 @@ declare class Sandbox {
552
612
  private wake;
553
613
  /** Stops the sandbox (guest shutdown; processes end, `/data` is kept). */
554
614
  stop(): Promise<void>;
555
- /** Copies this sandbox (root disk and `/data`) into a new sandbox and waits until it runs. */
556
- fork(opts?: ForkOpts): Promise<Sandbox>;
557
615
  /** Deletes the sandbox and its disks. Returns false if it was already gone. */
558
616
  kill(): Promise<boolean>;
559
617
  /**
@@ -573,7 +631,7 @@ declare class Sandbox {
573
631
  private settle;
574
632
  /**
575
633
  * Waits until a stopped sandbox's disks are in object storage (`storage.synced`). A stop returns
576
- * once the host has the snapshot and uploads it after, so a fork or snapshot right after a stop
634
+ * once the host has the snapshot and uploads it after, so a snapshot right after a stop
577
635
  * was refused ("not uploaded to object storage"), which took long enough after a pause and resume
578
636
  * to fail every time. Only a stopped sandbox is waited for; the server says what else is wrong.
579
637
  */
@@ -581,4 +639,4 @@ declare class Sandbox {
581
639
  private mutate;
582
640
  }
583
641
 
584
- export { type ApiError, CommandExitError, type CommandHandle, type CommandOptions, type CommandResult, Commands, type Connection, type ConnectionOptions, type CreateSnapshotOpts, DEFAULT_API_URL, DEFAULT_TEMPLATE, type EntryInfo, type ExecResponse, FALLBACK_TEMPLATE, Files, type ForkOpts, type HostTrust, InstaboxAuthError, InstaboxError, type InstaboxErrorInit, InstaboxQuotaError, InstaboxTimeoutError, MAX_FILE_BYTES, MAX_STDIN_BYTES, type Machine, type MachineList, type MachineSpec, type MachineState, type MachineVault, type MachineVaultItem, type OnTimeout, type Operation, Sandbox, type SandboxConnectOpts, type SandboxInfo, type SandboxListOpts, type SandboxOpts, type Snapshot, type SnapshotList, type SshCredentials, type Template, type TemplateRef, type VaultApplied, type VaultFile, type VaultKept, type WriteInfo };
642
+ export { type ApiError, CommandExitError, type CommandHandle, type CommandOptions, type CommandResult, Commands, type Connection, type ConnectionOptions, type CreateSnapshotOpts, DEFAULT_API_URL, DEFAULT_TEMPLATE, DESKTOP_DISPLAY, Desktop, type DesktopStatus, type DesktopStream, type EntryInfo, type ExecResponse, FALLBACK_TEMPLATE, Files, type HostTrust, InstaboxAuthError, InstaboxError, type InstaboxErrorInit, InstaboxQuotaError, InstaboxTimeoutError, MAX_FILE_BYTES, MAX_STDIN_BYTES, type Machine, type MachineList, type MachineSpec, type MachineState, type MachineVault, type MachineVaultItem, type MouseButton, type OnTimeout, type Operation, Sandbox, type SandboxConnectOpts, type SandboxInfo, type SandboxListOpts, type SandboxOpts, type ScrollDirection, type Snapshot, type SnapshotList, type SshCredentials, type Template, type TemplateRef, type VaultApplied, type VaultFile, type VaultKept, type WriteInfo };
package/dist/index.js CHANGED
@@ -173,6 +173,261 @@ var Commands = class {
173
173
  }
174
174
  };
175
175
 
176
+ // src/desktop.ts
177
+ var DESKTOP_DISPLAY = ":1";
178
+ var BUTTONS = { left: 1, middle: 2, right: 3 };
179
+ var WHEEL = { up: 4, down: 5, left: 6, right: 7 };
180
+ var KEYS = {
181
+ enter: "Return",
182
+ return: "Return",
183
+ esc: "Escape",
184
+ escape: "Escape",
185
+ tab: "Tab",
186
+ space: "space",
187
+ backspace: "BackSpace",
188
+ delete: "Delete",
189
+ del: "Delete",
190
+ insert: "Insert",
191
+ home: "Home",
192
+ end: "End",
193
+ pageup: "Prior",
194
+ pagedown: "Next",
195
+ up: "Up",
196
+ down: "Down",
197
+ left: "Left",
198
+ right: "Right",
199
+ ctrl: "ctrl",
200
+ control: "ctrl",
201
+ alt: "alt",
202
+ shift: "shift",
203
+ meta: "super",
204
+ cmd: "super",
205
+ command: "super",
206
+ super: "super",
207
+ win: "super",
208
+ "+": "plus"
209
+ };
210
+ var enc = encodeURIComponent;
211
+ function keysym(key) {
212
+ if (typeof key !== "string" || !key || /\s/.test(key)) {
213
+ throw new InstaboxError(`invalid key ${JSON.stringify(key)}`, { code: "bad_request" });
214
+ }
215
+ const lower = key.toLowerCase();
216
+ if (KEYS[lower]) return KEYS[lower];
217
+ if (/^f([1-9]|1[0-9]|2[0-4])$/.test(lower)) return lower.toUpperCase();
218
+ return key;
219
+ }
220
+ function coord(name, v) {
221
+ if (!Number.isInteger(v) || v < 0 || v > 16384) {
222
+ throw new InstaboxError(`${name} must be a whole number of pixels from 0; got ${v}`, { code: "bad_request" });
223
+ }
224
+ return v;
225
+ }
226
+ var SCREENSHOT_MAX_BYTES = 32 * 1024 * 1024;
227
+ var Desktop = class {
228
+ /** @internal */
229
+ constructor(http, sandboxId, commands, files) {
230
+ this.http = http;
231
+ this.sandboxId = sandboxId;
232
+ this.commands = commands;
233
+ this.files = files;
234
+ }
235
+ http;
236
+ sandboxId;
237
+ commands;
238
+ files;
239
+ /**
240
+ * Starts the desktop and resolves once it runs; a running desktop is left as it is (its size too).
241
+ * On a template without the desktop it is installed first (about half a minute, once). `width` and
242
+ * `height` size the screen: 800-2560 x 600-1600, default 1280 x 800.
243
+ */
244
+ async start(opts = {}) {
245
+ const size = {};
246
+ for (const [k, lo, hi] of [
247
+ ["width", 800, 2560],
248
+ ["height", 600, 1600]
249
+ ]) {
250
+ const v = opts[k];
251
+ if (v === void 0) continue;
252
+ if (!Number.isInteger(v) || v < lo || v > hi) {
253
+ throw new InstaboxError(`${k} must be a whole number from ${lo} to ${hi}; got ${v}`, { code: "bad_request" });
254
+ }
255
+ size[k] = v;
256
+ }
257
+ let s = await this.call({ action: "start", ...size });
258
+ if (!s.installed) {
259
+ if (!s.installing) s = await this.call({ action: "install" });
260
+ const deadline = Date.now() + this.http.operationTimeoutMs;
261
+ while (!s.installed) {
262
+ if (s.failed) {
263
+ throw new InstaboxError(
264
+ `the desktop could not be installed: ${s.log ?? "see /tmp/instabox-desktop-install.log"}`,
265
+ {
266
+ code: "desktop_install_failed"
267
+ }
268
+ );
269
+ }
270
+ if (Date.now() > deadline) {
271
+ throw new InstaboxTimeoutError(`the desktop was not installed within ${this.http.operationTimeoutMs} ms`, {
272
+ code: "operation_timeout"
273
+ });
274
+ }
275
+ await sleep(this.http.pollIntervalMs * 8);
276
+ s = await this.call({ action: "status" });
277
+ }
278
+ s = await this.call({ action: "start", ...size });
279
+ }
280
+ if (!s.running) throw new InstaboxError("the desktop did not start", { code: "desktop_not_running" });
281
+ return this.status();
282
+ }
283
+ /** Whether the desktop runs, and its screen size. */
284
+ async status() {
285
+ const s = await this.call({ action: "status" });
286
+ const out = { installed: s.installed, running: s.running };
287
+ if (s.running) {
288
+ const [w, h] = (await this.xdo("getdisplaygeometry")).stdout.trim().split(/\s+/).map(Number);
289
+ if (Number.isInteger(w) && Number.isInteger(h)) Object.assign(out, { width: w, height: h });
290
+ }
291
+ return out;
292
+ }
293
+ /** A PNG of the whole screen. */
294
+ async screenshot() {
295
+ const path = `/tmp/instabox-screenshot-${randomSuffix()}.png`;
296
+ const p = shellQuote(path);
297
+ try {
298
+ await this.run(
299
+ `if command -v scrot >/dev/null; then scrot -o ${p}; elif command -v import >/dev/null; then import -window root png:${p}; else echo 'no screenshot tool in the sandbox (scrot or ImageMagick import)' >&2; exit 127; fi`
300
+ );
301
+ return await this.files.read(path, { format: "bytes", maxBytes: SCREENSHOT_MAX_BYTES });
302
+ } finally {
303
+ await this.commands.exec(`rm -f ${p}`).catch(() => {
304
+ });
305
+ }
306
+ }
307
+ /** Clicks at (x, y): the left button by default; `double` clicks twice. */
308
+ async click(x, y, opts = {}) {
309
+ const button = BUTTONS[opts.button ?? "left"];
310
+ if (!button)
311
+ throw new InstaboxError(`button must be left, right or middle; got ${opts.button}`, { code: "bad_request" });
312
+ const repeat = opts.double ? " --repeat 2 --delay 80" : "";
313
+ await this.xdo(`mousemove ${coord("x", x)} ${coord("y", y)} click${repeat} ${button}`);
314
+ }
315
+ /** Moves the pointer to (x, y). */
316
+ async move(x, y) {
317
+ await this.xdo(`mousemove ${coord("x", x)} ${coord("y", y)}`);
318
+ }
319
+ /** Drags with the left button from `from` to `to`, each `[x, y]`. */
320
+ async drag(from, to) {
321
+ await this.xdo(
322
+ `mousemove ${coord("x", from[0])} ${coord("y", from[1])} mousedown 1 sleep 0.1 mousemove ${coord("x", to[0])} ${coord("y", to[1])} sleep 0.1 mouseup 1`
323
+ );
324
+ }
325
+ /** Scrolls the wheel at the pointer, `amount` notches (default 3). */
326
+ async scroll(opts) {
327
+ const wheel = WHEEL[opts.direction];
328
+ const n = opts.amount ?? 3;
329
+ if (!wheel)
330
+ throw new InstaboxError(`direction must be up, down, left or right; got ${opts.direction}`, {
331
+ code: "bad_request"
332
+ });
333
+ if (!Number.isInteger(n) || n < 1 || n > 100) {
334
+ throw new InstaboxError(`amount must be a whole number from 1 to 100; got ${n}`, { code: "bad_request" });
335
+ }
336
+ await this.xdo(`click --repeat ${n} --delay 30 ${wheel}`);
337
+ }
338
+ /** Types `text` as is (quotes, newlines and Unicode included) into the focused window. */
339
+ async type(text, opts = {}) {
340
+ if (typeof text !== "string") throw new InstaboxError("text must be a string", { code: "bad_request" });
341
+ if (!text) return;
342
+ const delay = opts.delayMs ?? 12;
343
+ if (!Number.isInteger(delay) || delay < 0 || delay > 1e3) {
344
+ throw new InstaboxError(`delayMs must be a whole number from 0 to 1000; got ${delay}`, { code: "bad_request" });
345
+ }
346
+ await this.xdo(`type --delay ${delay} --file -`, text);
347
+ }
348
+ /** Presses a key (`'Enter'`, `'a'`, `'F5'`) or a chord (`['ctrl', 'l']`). */
349
+ async press(keys) {
350
+ const list = Array.isArray(keys) ? keys : [keys];
351
+ if (!list.length) throw new InstaboxError("press needs a key", { code: "bad_request" });
352
+ await this.xdo(`key -- ${shellQuote(list.map(keysym).join("+"))}`);
353
+ }
354
+ /** Opens `url` (http or https) in the desktop's browser. */
355
+ async open(url) {
356
+ let u;
357
+ try {
358
+ u = new URL(url);
359
+ } catch {
360
+ throw new InstaboxError(`invalid URL: ${url}`, { code: "bad_request" });
361
+ }
362
+ if (u.protocol !== "http:" && u.protocol !== "https:") {
363
+ throw new InstaboxError(`only http and https URLs open in the browser; got ${u.protocol}`, {
364
+ code: "bad_request"
365
+ });
366
+ }
367
+ await this.run(
368
+ `b=$(command -v chromium || command -v chromium-browser || command -v google-chrome) || { echo 'no browser in the sandbox' >&2; exit 127; }; setsid nohup "$b" --no-first-run --no-default-browser-check --password-store=basic ${shellQuote(u.href)} >/dev/null 2>&1 </dev/null &`
369
+ );
370
+ }
371
+ /** Where the pointer is. */
372
+ async cursorPosition() {
373
+ const out = (await this.xdo("getmouselocation --shell")).stdout;
374
+ const x = Number(/^X=(\d+)/m.exec(out)?.[1]);
375
+ const y = Number(/^Y=(\d+)/m.exec(out)?.[1]);
376
+ if (!Number.isInteger(x) || !Number.isInteger(y)) {
377
+ throw new InstaboxError("could not read the pointer position", { code: "invalid_response" });
378
+ }
379
+ return { x, y };
380
+ }
381
+ /**
382
+ * A link that shows the desktop full-screen in a browser, for people without an instabox account:
383
+ * open it or embed it in an iframe. View-only by default (the server drops the viewer's input).
384
+ * `ttlSeconds`: 60 to 86 400, default 3 600. The expiry stops new connections only; a viewer already
385
+ * watching stays until they leave or `revokeStreamUrls()` is called.
386
+ */
387
+ async streamUrl(opts = {}) {
388
+ const body = { viewOnly: opts.viewOnly ?? true };
389
+ if (opts.ttlSeconds !== void 0) {
390
+ if (!Number.isInteger(opts.ttlSeconds) || opts.ttlSeconds < 60 || opts.ttlSeconds > 86400) {
391
+ throw new InstaboxError(`ttlSeconds must be a whole number from 60 to 86 400; got ${opts.ttlSeconds}`, {
392
+ code: "bad_request"
393
+ });
394
+ }
395
+ body.ttlSeconds = opts.ttlSeconds;
396
+ }
397
+ const r = await this.http.request(
398
+ "POST",
399
+ `/v1/machines/${enc(this.sandboxId)}/desktop/stream`,
400
+ { body }
401
+ );
402
+ return { url: r.url, expiresAt: new Date(r.expiresAt) };
403
+ }
404
+ /**
405
+ * Revokes every link `streamUrl()` made for this sandbox: they stop working and open viewers are
406
+ * disconnected within a few seconds. Links made afterwards work.
407
+ */
408
+ async revokeStreamUrls() {
409
+ await this.http.request("DELETE", `/v1/machines/${enc(this.sandboxId)}/desktop/stream`);
410
+ }
411
+ call(body) {
412
+ return this.http.request("POST", `/v1/machines/${enc(this.sandboxId)}/desktop`, {
413
+ body,
414
+ timeoutMs: 9e4
415
+ });
416
+ }
417
+ /** Runs `xdotool <args>` on the desktop's display. */
418
+ xdo(args, stdin) {
419
+ return this.run(`xdotool ${args}`, stdin);
420
+ }
421
+ async run(cmd, stdin) {
422
+ const r = await this.commands.exec(
423
+ `export DISPLAY=${DESKTOP_DISPLAY}; ${cmd}`,
424
+ stdin === void 0 ? {} : { stdin }
425
+ );
426
+ if (r.exitCode !== 0) throw new CommandExitError(r);
427
+ return r;
428
+ }
429
+ };
430
+
176
431
  // src/files.ts
177
432
  var MAX_FILE_BYTES = 10 * 1024 * 1024;
178
433
  var WRITE_CHUNK_B64 = 48 * 1024;
@@ -185,18 +440,19 @@ var Files = class {
185
440
  commands;
186
441
  async read(path, opts = {}) {
187
442
  const p = arg(path);
443
+ const limit = opts.maxBytes ?? MAX_FILE_BYTES;
188
444
  const r = await this.commands.exec(
189
- `[ -f ${p} ] || { echo "no such file: "${p} >&2; exit 3; }; s=$(wc -c < ${p}) || exit 1; [ "$s" -le ${MAX_FILE_BYTES} ] || { echo "file too large: $s bytes" >&2; exit 4; }; printf '%s' "$s"`
445
+ `[ -f ${p} ] || { echo "no such file: "${p} >&2; exit 3; }; s=$(wc -c < ${p}) || exit 1; [ "$s" -le ${limit} ] || { echo "file too large: $s bytes" >&2; exit 4; }; printf '%s' "$s"`
190
446
  );
191
447
  if (r.exitCode === 3) throw new InstaboxError(`file not found: ${path}`, { status: 404, code: "not_found" });
192
448
  if (r.exitCode === 4) {
193
- throw new InstaboxError(`${path} is larger than the ${MAX_FILE_BYTES}-byte limit of files.read`, {
449
+ throw new InstaboxError(`${path} is larger than the ${limit}-byte limit of files.read`, {
194
450
  code: "file_too_large"
195
451
  });
196
452
  }
197
453
  ensureComplete(r);
198
454
  const size = Number(r.stdout.trim());
199
- if (!Number.isSafeInteger(size) || size < 0 || size > MAX_FILE_BYTES) {
455
+ if (!Number.isSafeInteger(size) || size < 0 || size > limit) {
200
456
  throw new InstaboxError("invalid file size returned by exec", { code: "invalid_response" });
201
457
  }
202
458
  const bytes = new Uint8Array(size);
@@ -465,7 +721,7 @@ function toSeconds(ms, field = "timeoutMs") {
465
721
  return s;
466
722
  }
467
723
  var METADATA_KEY = /^[A-Za-z0-9_.-]{1,64}$/;
468
- var enc = encodeURIComponent;
724
+ var enc2 = encodeURIComponent;
469
725
  var Sandbox = class _Sandbox {
470
726
  constructor(http, machine, opts = {}) {
471
727
  this.http = http;
@@ -473,6 +729,7 @@ var Sandbox = class _Sandbox {
473
729
  this.machine = machine;
474
730
  this.commands = new Commands(http, machine.id, { ...opts.envs });
475
731
  this.files = new Files(this.commands);
732
+ this.desktop = new Desktop(http, machine.id, this.commands, this.files);
476
733
  }
477
734
  http;
478
735
  /** The machine ID (`m_...`). */
@@ -481,6 +738,8 @@ var Sandbox = class _Sandbox {
481
738
  commands;
482
739
  /** Read and write files. Needs a instabox server with the exec endpoint. */
483
740
  files;
741
+ /** See and control the sandbox's graphical desktop (screenshots, mouse, keyboard, a link to watch it). */
742
+ desktop;
484
743
  machine;
485
744
  static async create(a, b) {
486
745
  const opts = (typeof a === "string" ? b : a) ?? {};
@@ -541,12 +800,12 @@ var Sandbox = class _Sandbox {
541
800
  }
542
801
  /** Fetches a snapshot by ID. Requires images:read. */
543
802
  static async getSnapshot(snapshotId, opts = {}) {
544
- return new HttpClient(opts).request("GET", `/v1/snapshots/${enc(snapshotId)}`);
803
+ return new HttpClient(opts).request("GET", `/v1/snapshots/${enc2(snapshotId)}`);
545
804
  }
546
805
  /** Deletes a snapshot. Returns false if absent. Requires images:delete. */
547
806
  static async deleteSnapshot(snapshotId, opts = {}) {
548
807
  try {
549
- await new HttpClient(opts).request("DELETE", `/v1/snapshots/${enc(snapshotId)}`);
808
+ await new HttpClient(opts).request("DELETE", `/v1/snapshots/${enc2(snapshotId)}`);
550
809
  return true;
551
810
  } catch (err) {
552
811
  if (err instanceof InstaboxError && err.status === 404 && err.code === "not_found") return false;
@@ -561,7 +820,7 @@ var Sandbox = class _Sandbox {
561
820
  async createSnapshot(opts) {
562
821
  await this.settle();
563
822
  await this.untilSynced();
564
- return this.http.request("POST", `/v1/machines/${enc(this.sandboxId)}/snapshots`, { body: opts });
823
+ return this.http.request("POST", `/v1/machines/${enc2(this.sandboxId)}/snapshots`, { body: opts });
565
824
  }
566
825
  /** Fetches the current state of the sandbox. */
567
826
  async getInfo() {
@@ -575,20 +834,20 @@ var Sandbox = class _Sandbox {
575
834
  async setTimeout(timeoutMs, opts = {}) {
576
835
  const body = { timeoutSeconds: timeoutMs === 0 ? 0 : toSeconds(timeoutMs) };
577
836
  if (opts.onTimeout) body.onTimeout = opts.onTimeout;
578
- this.machine = await this.http.request("PATCH", `/v1/machines/${enc(this.sandboxId)}`, { body });
837
+ this.machine = await this.http.request("PATCH", `/v1/machines/${enc2(this.sandboxId)}`, { body });
579
838
  }
580
839
  /**
581
840
  * Pauses the sandbox once it has been idle `idleMs` (whole seconds, 2 min to 24 h); 0 turns the idle
582
841
  * pause off. Unlike a timeout the setting stays across pause and resume.
583
842
  */
584
843
  async setAutoSuspend(idleMs) {
585
- this.machine = await this.http.request("PATCH", `/v1/machines/${enc(this.sandboxId)}`, {
844
+ this.machine = await this.http.request("PATCH", `/v1/machines/${enc2(this.sandboxId)}`, {
586
845
  body: { autoSuspendAfterSeconds: toIdleSeconds(idleMs) }
587
846
  });
588
847
  }
589
848
  /** Replaces the sandbox's metadata (`{}` clears it). */
590
849
  async setMetadata(metadata) {
591
- this.machine = await this.http.request("PATCH", `/v1/machines/${enc(this.sandboxId)}`, {
850
+ this.machine = await this.http.request("PATCH", `/v1/machines/${enc2(this.sandboxId)}`, {
592
851
  body: { metadata }
593
852
  });
594
853
  }
@@ -598,21 +857,21 @@ var Sandbox = class _Sandbox {
598
857
  * Throws `not_found` on a server without the Vault.
599
858
  */
600
859
  async vault() {
601
- return this.http.request("GET", `/v1/machines/${enc(this.sandboxId)}/vault`);
860
+ return this.http.request("GET", `/v1/machines/${enc2(this.sandboxId)}/vault`);
602
861
  }
603
862
  /**
604
863
  * Writes the account's current Vault items into the running sandbox now, the same write as after a boot,
605
864
  * and returns its record (`error` set when the guest refused it). Requires machines:write.
606
865
  */
607
866
  async pushVault() {
608
- return this.http.request("POST", `/v1/machines/${enc(this.sandboxId)}/vault`);
867
+ return this.http.request("POST", `/v1/machines/${enc2(this.sandboxId)}/vault`);
609
868
  }
610
869
  /**
611
870
  * Turns the Vault off for this sandbox, for good, in any state: its next boot, resume or push removes
612
871
  * what the Vault wrote and nothing is written again. Requires machines:write.
613
872
  */
614
873
  async disableVault() {
615
- this.machine = await this.http.request("PATCH", `/v1/machines/${enc(this.sandboxId)}`, {
874
+ this.machine = await this.http.request("PATCH", `/v1/machines/${enc2(this.sandboxId)}`, {
616
875
  body: { vault: false }
617
876
  });
618
877
  }
@@ -640,34 +899,6 @@ var Sandbox = class _Sandbox {
640
899
  if (this.machine.state === "suspended") await this.mutate("POST", "start");
641
900
  await this.mutate("POST", "stop");
642
901
  }
643
- /** Copies this sandbox (root disk and `/data`) into a new sandbox and waits until it runs. */
644
- async fork(opts = {}) {
645
- if (opts.timeoutMs !== void 0) toSeconds(opts.timeoutMs);
646
- if (opts.autoSuspendMs !== void 0) toIdleSeconds(opts.autoSuspendMs);
647
- await this.settle();
648
- if (this.machine.state !== "stopped") {
649
- if (opts.stopSource === false) {
650
- throw new InstaboxError(`fork needs a stopped sandbox; ${this.sandboxId} is ${this.machine.state}`, {
651
- code: "operation_conflict"
652
- });
653
- }
654
- await this.stop();
655
- }
656
- await this.untilSynced();
657
- const body = { name: opts.name ?? `${this.machine.name}-fork-${randomSuffix(4)}` };
658
- if (opts.vcpus !== void 0) body.vcpus = opts.vcpus;
659
- if (opts.memMiB !== void 0) body.memMiB = opts.memMiB;
660
- if (opts.diskGiB !== void 0) body.persistentDiskGiB = opts.diskGiB;
661
- if (opts.rootDiskGiB !== void 0) body.rootDiskGiB = opts.rootDiskGiB;
662
- if (opts.timeoutMs !== void 0) body.timeoutSeconds = toSeconds(opts.timeoutMs);
663
- if (opts.onTimeout) body.onTimeout = opts.onTimeout;
664
- if (opts.autoSuspendMs !== void 0) body.autoSuspendAfterSeconds = toIdleSeconds(opts.autoSuspendMs);
665
- if (opts.metadata) body.metadata = opts.metadata;
666
- if (opts.vault === false) body.vault = false;
667
- const op = await this.http.request("POST", `/v1/machines/${enc(this.sandboxId)}/fork`, { body });
668
- const done = await this.http.waitForOperation(op);
669
- return new _Sandbox(this.http, await getMachine(this.http, done.machineId));
670
- }
671
902
  /** Deletes the sandbox and its disks. Returns false if it was already gone. */
672
903
  async kill() {
673
904
  return killMachine(this.http, this.sandboxId);
@@ -687,7 +918,7 @@ var Sandbox = class _Sandbox {
687
918
  }
688
919
  body.ttlSeconds = opts.ttlSeconds;
689
920
  }
690
- const c = await this.http.request("POST", `/v1/machines/${enc(this.sandboxId)}/connections`, { body });
921
+ const c = await this.http.request("POST", `/v1/machines/${enc2(this.sandboxId)}/connections`, { body });
691
922
  return {
692
923
  host: c.host,
693
924
  port: c.port,
@@ -706,7 +937,7 @@ var Sandbox = class _Sandbox {
706
937
  async settle(refresh = true) {
707
938
  if (refresh) this.machine = await getMachine(this.http, this.sandboxId);
708
939
  if (this.machine.operationId) {
709
- const op = await this.http.request("GET", `/v1/operations/${enc(this.machine.operationId)}`);
940
+ const op = await this.http.request("GET", `/v1/operations/${enc2(this.machine.operationId)}`);
710
941
  await this.http.waitForOperation(op).catch(() => {
711
942
  });
712
943
  this.machine = await getMachine(this.http, this.sandboxId);
@@ -714,7 +945,7 @@ var Sandbox = class _Sandbox {
714
945
  }
715
946
  /**
716
947
  * Waits until a stopped sandbox's disks are in object storage (`storage.synced`). A stop returns
717
- * once the host has the snapshot and uploads it after, so a fork or snapshot right after a stop
948
+ * once the host has the snapshot and uploads it after, so a snapshot right after a stop
718
949
  * was refused ("not uploaded to object storage"), which took long enough after a pause and resume
719
950
  * to fail every time. Only a stopped sandbox is waited for; the server says what else is wrong.
720
951
  */
@@ -734,17 +965,17 @@ var Sandbox = class _Sandbox {
734
965
  }
735
966
  }
736
967
  async mutate(method, action) {
737
- const op = await this.http.request(method, `/v1/machines/${enc(this.sandboxId)}/${action}`);
968
+ const op = await this.http.request(method, `/v1/machines/${enc2(this.sandboxId)}/${action}`);
738
969
  await this.http.waitForOperation(op);
739
970
  this.machine = await getMachine(this.http, this.sandboxId);
740
971
  }
741
972
  };
742
973
  async function getMachine(http, id) {
743
- return http.request("GET", `/v1/machines/${enc(id)}`);
974
+ return http.request("GET", `/v1/machines/${enc2(id)}`);
744
975
  }
745
976
  async function killMachine(http, id) {
746
977
  try {
747
- const op = await http.request("DELETE", `/v1/machines/${enc(id)}`);
978
+ const op = await http.request("DELETE", `/v1/machines/${enc2(id)}`);
748
979
  await http.waitForOperation(op);
749
980
  return true;
750
981
  } catch (err) {
@@ -793,6 +1024,8 @@ export {
793
1024
  Commands,
794
1025
  DEFAULT_API_URL,
795
1026
  DEFAULT_TEMPLATE,
1027
+ DESKTOP_DISPLAY,
1028
+ Desktop,
796
1029
  FALLBACK_TEMPLATE,
797
1030
  Files,
798
1031
  InstaboxAuthError,