@insforge/instabox-sdk 0.5.3 → 0.7.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
@@ -19,15 +19,36 @@ declare class InstaboxError extends Error {
19
19
  readonly operationId?: string | null;
20
20
  constructor(message: string, init?: InstaboxErrorInit);
21
21
  }
22
- /** 401 / 403: invalid or revoked API key, or not allowed. Also no API key at all (`missing_api_key`, status 0). */
22
+ /**
23
+ * 401 / 403 that is not a plan limit: invalid, expired or revoked API key, a missing scope, or no
24
+ * access (`permission_denied`). Also no API key at all (`missing_api_key`, status 0).
25
+ */
23
26
  declare class InstaboxAuthError extends InstaboxError {
24
27
  }
25
- /** 429 `quota_exceeded`: an account limit was reached (for example the machine limit). */
28
+ /**
29
+ * A quota, plan or billing limit, the CLI's exit code 5: any code in `LIMIT_CODES` whatever the
30
+ * status (for example 403 `template_not_allowed`, 400 `spec_not_allowed`, 402 `credit_exhausted`,
31
+ * 429 `quota_exceeded`), and any other 402 or 429. A new key will not help; the plan, the account's
32
+ * usage or (for `rate_limited` and `concurrency_limit`) waiting will.
33
+ */
26
34
  declare class InstaboxQuotaError extends InstaboxError {
27
35
  }
36
+ /**
37
+ * API error codes of a quota, plan or billing limit, as the instabox CLI classes them (exit code 5).
38
+ * They throw `InstaboxQuotaError` whatever the HTTP status.
39
+ */
40
+ declare const LIMIT_CODES: readonly string[];
41
+ /** True for a quota, plan or billing limit code (`LIMIT_CODES`). */
42
+ declare function isLimitCode(code: string | undefined): boolean;
28
43
  /** A request or an operation did not finish in time. */
29
44
  declare class InstaboxTimeoutError extends InstaboxError {
30
45
  }
46
+ /**
47
+ * `files.read` in the default text format met bytes that are not valid UTF-8 (`not_utf8`, status 0).
48
+ * Read the file with `{ format: 'bytes' }` instead; text reads never return U+FFFD for bad bytes.
49
+ */
50
+ declare class InstaboxNotUtf8Error extends InstaboxError {
51
+ }
31
52
  /** Result of a finished command. */
32
53
  interface CommandResult {
33
54
  stdout: string;
@@ -92,10 +113,7 @@ interface Machine {
92
113
  processesPreserved?: boolean;
93
114
  };
94
115
  lastError?: ApiError;
95
- /** When the server pauses or deletes the machine (see `onTimeout`); null for no timeout. */
96
- timeoutAt?: string | null;
97
116
  archiveAt?: string | null;
98
- onTimeout?: OnTimeout;
99
117
  /** Idle seconds after which the server pauses the running machine; null when it never does. */
100
118
  autoSuspendAfterSeconds?: number | null;
101
119
  /** When the server paused it for idleness; cleared by the next explicit operation. */
@@ -149,8 +167,6 @@ interface MachineVault {
149
167
  /** The last write into the machine; null before one. */
150
168
  applied: VaultApplied | null;
151
169
  }
152
- /** What happens at `timeoutAt`: `pause` suspends the machine, `kill` deletes it. */
153
- type OnTimeout = 'pause' | 'kill';
154
170
  interface MachineList {
155
171
  machines: Machine[];
156
172
  nextCursor: string | null;
@@ -232,6 +248,7 @@ interface MachineUsage {
232
248
  vcpuSeconds: number;
233
249
  memGiBSeconds: number;
234
250
  diskGiBSeconds: number;
251
+ egressBytes?: number;
235
252
  }
236
253
  /** One sandbox's share of `Usage.storedBytes`. */
237
254
  interface UsageMachineStorage {
@@ -263,6 +280,63 @@ interface UsageLimits {
263
280
  maxBytes: number;
264
281
  };
265
282
  }
283
+ /**
284
+ * `Usage.cost`: the workspace's usage this calendar month (UTC) in USD, as the hourly rating priced
285
+ * it, with its allowance and credit balance. The same figures as `GET /v1/orgs/{id}` `usage`.
286
+ */
287
+ interface UsageCost {
288
+ periodStart: string;
289
+ periodEnd: string;
290
+ /** Live sandboxes; `freeMachines` of them are free (never billed). */
291
+ machines: number;
292
+ freeMachines: number;
293
+ /** Wall-clock running hours of the free sandboxes this month (not vCPU-weighted). */
294
+ freeSandboxHours: number;
295
+ snapshots: number;
296
+ vcpuHours: number;
297
+ memGiBHours: number;
298
+ /** Allocated /data of paid sandboxes beyond the free amount each, summed over the hours. */
299
+ storageGiBHours: number;
300
+ /** Egress beyond the free amount. */
301
+ egressGiB: number;
302
+ /** Compute: `vcpuUSD` plus `memUSD`. */
303
+ runtimeUSD: number;
304
+ /** The vCPU part of compute. Absent from older servers. */
305
+ vcpuUSD?: number;
306
+ /** The memory part of compute. Absent from older servers. */
307
+ memUSD?: number;
308
+ storageUSD: number;
309
+ egressUSD: number;
310
+ /** The month's usage so far. */
311
+ costUSD: number;
312
+ /** What the month includes: the free credit, or what the subscription paid for. */
313
+ allowanceUSD: number;
314
+ /** The allowance left. */
315
+ creditRemainingUSD: number;
316
+ /** Usage beyond the allowance (billed at month end on a paid plan). */
317
+ overageUSD: number;
318
+ /** What may still be used before the workspace's sandboxes are stopped. */
319
+ remainingUSD: number;
320
+ /** The rating covers usage up to this time. */
321
+ ratedUntil: string;
322
+ /** The /data being billed now: paid sandboxes' disk beyond `freeDiskGiBPerSandbox`. */
323
+ billableDiskGiB: number;
324
+ /** Absent from servers before per-sandbox disk billing. */
325
+ freeDiskGiBPerSandbox?: number;
326
+ /** The /data of all live sandboxes, free ones included. */
327
+ allocatedDiskGiB: number;
328
+ /** @deprecated always null; read `billableDiskGiB`. */
329
+ storedBytes: number | null;
330
+ /** @deprecated always null. */
331
+ storageComputedAt: string | null;
332
+ /** What the unexpired credits have left; `creditsExpireAt` is when the earliest expires. */
333
+ creditsUSD: number;
334
+ creditsExpireAt?: string;
335
+ /** What credits paid this month. */
336
+ creditsUsedUSD: number;
337
+ /** Usage beyond the allowance already charged this month (threshold billing). */
338
+ chargedUSD?: number;
339
+ }
266
340
  /** Response of `GET /v1/usage`: your counts, stored bytes (measured about hourly) and limits. */
267
341
  interface Usage {
268
342
  /** When the byte figures were measured; null before your first measurement. */
@@ -277,6 +351,8 @@ interface Usage {
277
351
  limits: UsageLimits;
278
352
  /** `storedBytes` by sandbox. Absent before your first measurement. */
279
353
  storage?: UsageStorage;
354
+ /** This month's cost, allowance and credits. Absent from older servers. */
355
+ cost?: UsageCost;
280
356
  }
281
357
  /** Response of `POST /v1/machines/{id}/exec`. */
282
358
  interface ExecResponse {
@@ -309,24 +385,60 @@ interface ConnectionOptions {
309
385
  interface RequestOptions {
310
386
  timeoutMs?: number;
311
387
  body?: unknown;
388
+ /** A raw request body, sent as `application/octet-stream` instead of JSON. */
389
+ rawBody?: Uint8Array;
390
+ /**
391
+ * A streamed request body, sent as `application/octet-stream` with `duplex: 'half'` (chunked when no
392
+ * length is known). A stream can be read once, so such a request is never retried.
393
+ */
394
+ streamBody?: ReadableStream<Uint8Array>;
312
395
  query?: Record<string, string | number | string[] | undefined>;
313
396
  /** Retry on 502/503/504 and network errors. Default: true for GET and for requests carrying an Idempotency-Key. */
314
397
  retry?: boolean;
315
398
  /** Send an Idempotency-Key. Default: true for every method other than GET/HEAD. */
316
399
  idempotent?: boolean;
400
+ /** Extra request headers (for example X-Confirm-Delete). */
401
+ headers?: Record<string, string>;
402
+ /** Value of the Accept header. Default `application/json`. */
403
+ accept?: string;
404
+ /**
405
+ * Aborts the request, and the reading of its response body after `send` returned. An abort before
406
+ * the response arrived throws `InstaboxError` with code `aborted`.
407
+ */
408
+ signal?: AbortSignal;
317
409
  }
318
410
  declare class HttpClient {
411
+ #private;
319
412
  readonly apiUrl: string;
320
413
  readonly operationTimeoutMs: number;
321
- private readonly apiKey;
322
414
  private readonly requestTimeoutMs?;
323
415
  private readonly fetchImpl;
324
416
  readonly pollIntervalMs: number;
325
417
  private readonly retryDelayMs;
418
+ /** Removes the caller's abort listener of a response `send` returned; see `release`. */
419
+ private readonly releases;
326
420
  constructor(opts?: ConnectionOptions);
327
421
  request<T>(method: string, path: string, opts?: RequestOptions): Promise<T>;
422
+ /**
423
+ * Unwires the caller's `signal` from a response `send` returned, once its body is read or dropped.
424
+ * Until then an abort still ends the body; after it the signal holds no listener of this request,
425
+ * so a signal shared by many requests (a long `wait()`) does not collect one per request.
426
+ */
427
+ release(res: Response): void;
328
428
  /** Performs the request with retries; returns a 2xx response or throws an InstaboxError. */
329
429
  send(method: string, path: string, opts?: RequestOptions): Promise<Response>;
430
+ /** The deadline of one request: `requestTimeoutMs` when set, else `defaultMs`. */
431
+ requestTimeout(defaultMs: number): number;
432
+ /**
433
+ * The error for an API error envelope found in a 2xx response body (a streamed exec's `error`
434
+ * event), with the API key redacted as for an error response.
435
+ */
436
+ errorFromBody(status: number, text: string, fallbackMessage: string): InstaboxError;
437
+ /** JSON form, without the API key. */
438
+ toJSON(): {
439
+ apiUrl: string;
440
+ apiKey: string;
441
+ };
330
442
  private backoff;
331
443
  /** Polls an operation until it is `succeeded` (returns it) or `failed` (throws). */
332
444
  waitForOperation(op: Operation, timeoutMs?: number): Promise<Operation>;
@@ -339,35 +451,93 @@ interface CommandOptions {
339
451
  cwd?: string;
340
452
  /** Extra environment variables, merged over the sandbox-level `envs` from `Sandbox.create`. */
341
453
  envs?: Record<string, string>;
342
- /** Command timeout in ms (sent as whole seconds). Default: the server's default. */
454
+ /**
455
+ * Command timeout in ms (sent as whole seconds), at most 600 000. Default: the server's default (60 s).
456
+ * For a longer command use `background: true` and `wait()` on the handle.
457
+ */
343
458
  timeoutMs?: number;
344
- /** Text sent to the command's standard input, at most 1 MiB (UTF-8). */
345
- stdin?: string;
346
459
  /**
347
- * Called with stdout once the command finished. Output is not streamed yet:
348
- * the callback receives the whole stdout in one call.
460
+ * The command's standard input: text, or bytes that reach the command exactly as given. Up to 1 MiB
461
+ * of UTF-8 text goes in the exec request itself; anything else (bytes that are not UTF-8, or more than
462
+ * 1 MiB) is first uploaded to a temporary file in the sandbox, as `instabox exec --stdin` does, and the
463
+ * command reads it from there (up to the server's 5 GiB file limit). Not with `background: true`.
464
+ */
465
+ stdin?: string | Uint8Array;
466
+ /**
467
+ * Called with each chunk of stdout as the command writes it. With `onStdout` or `onStderr` set, the
468
+ * output is streamed and not capped: the result still carries the whole stdout and stderr.
469
+ * A returned promise is awaited before the next chunk is delivered. Not allowed with `background: true`
470
+ * (throws `bad_request`): pass `onStdout` to `wait()` on the handle instead.
349
471
  */
350
472
  onStdout?: (data: string) => unknown;
351
473
  /** Like `onStdout`, for stderr. */
352
474
  onStderr?: (data: string) => unknown;
353
- /** Start the command detached (nohup, in its own session) and return right away with its PID. */
475
+ /**
476
+ * Start the command detached, as a job in its own session, and return right away with a handle.
477
+ * Its output is kept in the sandbox; `wait()` on the handle follows it. Not limited to 10 minutes.
478
+ * Needs bash, util-linux `setsid` and GNU coreutils in the sandbox; without them it throws
479
+ * `InstaboxError` with code `background_unsupported`, naming what is missing.
480
+ */
354
481
  background?: boolean;
482
+ /**
483
+ * Stops the command: the request is closed, which kills the command in the sandbox, and `run` throws
484
+ * `InstaboxError` with code `aborted`. With `background: true` it only aborts the start.
485
+ */
486
+ signal?: AbortSignal;
487
+ }
488
+ /** Options of `CommandHandle.wait`. */
489
+ interface CommandWaitOptions {
490
+ /**
491
+ * Called with each chunk of the job's output as it is written, from the start. A background command's
492
+ * stdout and stderr go to one log, so both arrive here.
493
+ */
494
+ onStdout?: (data: string) => unknown;
495
+ /** Give up after this long: throws `InstaboxTimeoutError` with code `job_wait_timeout`; the job keeps running. */
496
+ timeoutMs?: number;
497
+ /** Stops waiting: throws `InstaboxError` with code `aborted`; the job keeps running. */
498
+ signal?: AbortSignal;
355
499
  }
356
500
  /** A command started with `background: true`. */
357
501
  interface CommandHandle {
358
502
  /** PID of the command's shell, which leads the process group of everything it started. */
359
503
  pid: number;
504
+ /**
505
+ * The job's ID. The CLI sees the same job: `instabox jobs logs <sandbox> <jobId> -f`,
506
+ * `instabox jobs wait`, `instabox jobs ls`.
507
+ */
508
+ jobId: string;
360
509
  /** Sends SIGTERM to the command and every process it started. Returns false if they had all exited. */
361
510
  kill(): Promise<boolean>;
511
+ /**
512
+ * Waits for the command to end, calling `onStdout` with its output as it is written. Resolves with
513
+ * `{ stdout, stderr: '', exitCode, timedOut: false, truncated: false }`, `stdout` holding the whole
514
+ * log (stdout and stderr together); throws `CommandExitError` on a non-zero exit, and `InstaboxError`
515
+ * with code `job_lost` when the job ended without an exit code (the sandbox restarted).
516
+ */
517
+ wait(opts?: CommandWaitOptions): Promise<CommandResult>;
362
518
  }
519
+ type ExecOptions = Pick<CommandOptions, 'cwd' | 'envs' | 'timeoutMs' | 'signal'> & {
520
+ /** Text for the request's `stdin` (at most 1 MiB). */
521
+ stdin?: string;
522
+ /** Leave the command out of the sandbox's history (job polls). */
523
+ noHistory?: boolean;
524
+ /** How the command appears in the sandbox's history. */
525
+ historyCommand?: string;
526
+ };
363
527
  declare class Commands {
364
528
  private readonly http;
365
529
  private readonly sandboxId;
366
530
  private readonly defaultEnvs;
531
+ /**
532
+ * @internal Uploads stdin the exec request cannot carry to a temporary file and returns its path
533
+ * (set by `Sandbox`, which owns the file routes).
534
+ */
535
+ stageStdin?: (bytes: Uint8Array, signal?: AbortSignal) => Promise<string>;
367
536
  /** @internal */
368
537
  constructor(http: HttpClient, sandboxId: string, defaultEnvs: Record<string, string>);
369
538
  /**
370
- * Runs a shell command in the sandbox and waits for it to finish.
539
+ * Runs a shell command in the sandbox and waits for it to finish. With `onStdout` or `onStderr` the
540
+ * output is streamed to them as the command writes it.
371
541
  * Throws `CommandExitError` (carrying stdout, stderr and exitCode) when it exits non-zero.
372
542
  */
373
543
  run(cmd: string, opts: CommandOptions & {
@@ -377,12 +547,40 @@ declare class Commands {
377
547
  background?: false;
378
548
  }): Promise<CommandResult>;
379
549
  run(cmd: string, opts?: CommandOptions): Promise<CommandResult | CommandHandle>;
550
+ private get execPath();
551
+ private execBody;
552
+ /** The request deadline of an exec: its command timeout plus 30 s, unless `requestTimeoutMs` is set. */
553
+ private execDeadline;
380
554
  /** @internal Raw exec: never throws on a non-zero exit code. */
381
- exec(cmd: string, opts?: Pick<CommandOptions, 'cwd' | 'envs' | 'timeoutMs' | 'stdin'>): Promise<CommandResult>;
555
+ exec(cmd: string, opts?: ExecOptions): Promise<CommandResult>;
556
+ /**
557
+ * Exec with the output streamed (`Accept: text/event-stream`): each `stdout`/`stderr` event goes to its
558
+ * callback as it arrives, and the result carries all of it. A server that does not stream answers with
559
+ * the whole result, whose output is passed to the callbacks then.
560
+ */
561
+ private execStream;
562
+ /** Reads a streamed exec's server-sent events until its `exit` or `error` event. */
563
+ private readEvents;
564
+ /** Handles one event: output goes to its callback, `exit` is the result, `error` is thrown. */
565
+ private dispatch;
566
+ /** Starts a background job the CLI's way and returns its handle. */
567
+ private startJob;
568
+ /** One read of a job: its status and up to `max` bytes of output from `off`, waiting up to `w` seconds. */
569
+ private readJob;
570
+ /** `readJob` for the wait loop. Reads change nothing, so a transient error is retried for up to 2 minutes. */
571
+ private pollJob;
572
+ /** Follows a job's output until it ends. */
573
+ private waitJob;
382
574
  }
383
575
 
384
- /** Largest file `files.read` / `files.write` move (files go through exec as base64). */
576
+ /**
577
+ * Default cap of a buffered `files.read` (raise it with `maxBytes`, or use `readStream`), and the most
578
+ * `files.write` moves on a server without the file routes (over exec). Over the file routes `write`
579
+ * and `readStream` have no such cap: the server takes a file of up to 5 GiB (`MAX_UPLOAD_BYTES`).
580
+ */
385
581
  declare const MAX_FILE_BYTES: number;
582
+ /** The largest file the server's `PUT /v1/machines/{id}/files` takes: 5 GiB. */
583
+ declare const MAX_UPLOAD_BYTES: number;
386
584
  interface EntryInfo {
387
585
  name: string;
388
586
  path: string;
@@ -392,26 +590,173 @@ interface WriteInfo {
392
590
  path: string;
393
591
  }
394
592
  /**
395
- * File access inside the sandbox. Implemented on top of exec (base64 over the command
396
- * channel), capped at 10 MiB per file.
593
+ * What `files.write` takes: text, bytes, or a stream of bytes. A stream is sent as it is read, never
594
+ * held in memory whole: a Node `Readable` (`fs.createReadStream(...)`), a web `ReadableStream`, or any
595
+ * `AsyncIterable` of `Uint8Array` (or string) chunks, such as an async generator.
596
+ */
597
+ type WriteData = string | Uint8Array | ArrayBuffer | ReadableStream<Uint8Array> | AsyncIterable<Uint8Array | string>;
598
+ interface WriteOptions {
599
+ /** Stops the transfer: `write` throws `InstaboxError` with code `aborted`, and the file is left as it was. */
600
+ signal?: AbortSignal;
601
+ }
602
+ interface ReadStreamOptions {
603
+ /** Stops the transfer: the promise rejects, or the stream errors, with `InstaboxError` code `aborted`. */
604
+ signal?: AbortSignal;
605
+ }
606
+ /** A file's bytes as they arrive: a web `ReadableStream` that is also an `AsyncIterable` (`for await`). */
607
+ type FileStream = ReadableStream<Uint8Array> & AsyncIterable<Uint8Array>;
608
+ interface UploadOptions {
609
+ /**
610
+ * In a git work tree, upload only the files git tracks, as `instabox push` does. Default true;
611
+ * `false` uploads everything under the directory.
612
+ */
613
+ git?: boolean;
614
+ /** With `git`, also upload untracked files that git does not ignore (`instabox push --all`). */
615
+ all?: boolean;
616
+ /** Stops the transfer: throws `InstaboxError` with code `aborted`. */
617
+ signal?: AbortSignal;
618
+ }
619
+ interface UploadInfo {
620
+ /** The sandbox directory the files went into (absolute, symlinks resolved). */
621
+ path: string;
622
+ /** Regular files uploaded (directories and symlinks are not counted). */
623
+ files: number;
624
+ /** Size of the gzipped tar that was sent. */
625
+ bytes: number;
626
+ }
627
+ interface DownloadOptions {
628
+ /** Stops the transfer: throws `InstaboxError` with code `aborted`. */
629
+ signal?: AbortSignal;
630
+ }
631
+ interface DownloadInfo {
632
+ /** The local directory the files went into. */
633
+ path: string;
634
+ /** The sandbox directory (absolute, symlinks resolved). */
635
+ remotePath: string;
636
+ /** Regular files written. */
637
+ files: number;
638
+ /** Size of the gzipped tar that was received. */
639
+ bytes: number;
640
+ }
641
+ /**
642
+ * File access inside the sandbox. `read`, `readStream` and `write` move the bytes over the file routes
643
+ * (`GET /v1/machines/{id}/files/content`, `PUT /v1/machines/{id}/files`), as the CLI's `cp` does; a
644
+ * server without them gets base64 chunks over exec (up to 10 MiB). `upload` and `download` move a
645
+ * directory as one gzipped tar over the same routes, as `instabox push` and `instabox pull` do.
646
+ * `list`, `exists` and `remove` run over exec.
397
647
  */
398
648
  declare class Files {
399
649
  private readonly commands;
650
+ private readonly http?;
651
+ private readonly sandboxId?;
652
+ private home?;
653
+ /** False once a server answered that it has no file routes. */
654
+ private routes;
655
+ /** True once a server answered on a file route, so a stream need not probe for it. */
656
+ private routesSeen;
400
657
  /** @internal */
401
- constructor(commands: Commands);
402
- /** Reads a file. Returns text (UTF-8) by default, or bytes with `{ format: 'bytes' }`. */
658
+ constructor(commands: Commands, http?: HttpClient | undefined, sandboxId?: string | undefined);
659
+ private get filesPath();
660
+ /**
661
+ * Reads a file into memory. Returns text (UTF-8) by default, or bytes with `{ format: 'bytes' }`. A
662
+ * text read of a file that is not valid UTF-8 throws `InstaboxNotUtf8Error` (code `not_utf8`) rather
663
+ * than returning U+FFFD in place of the bad bytes. A file over `maxBytes` (default 10 MiB) throws
664
+ * `file_too_large`: pass a larger `maxBytes`, or use `readStream`, for bigger files.
665
+ */
403
666
  read(path: string, opts?: {
404
667
  format?: 'text';
668
+ maxBytes?: number;
405
669
  }): Promise<string>;
406
670
  read(path: string, opts: {
407
- format: 'bytes'; /** @internal */
671
+ format: 'bytes';
408
672
  maxBytes?: number;
409
673
  }): Promise<Uint8Array>;
410
674
  /**
411
- * Writes a file, creating parent directories. Replaces the file atomically (temp file + rename).
412
- * Throws `is_a_directory` when `path` is a directory.
675
+ * Opens a file for reading as a stream, with no size cap: the bytes arrive as the server sends them,
676
+ * so a file of any size reads in bounded memory. Errors before the first byte (`not_found`, a
677
+ * directory) reject the promise; a stream cut short errors with `file_changed`. Read it with
678
+ * `for await`, `getReader()`, or in Node `Readable.fromWeb(stream)` and `pipeline`. On a server
679
+ * without the file routes the file is read over exec first (at most 10 MiB).
680
+ */
681
+ readStream(path: string, opts?: ReadStreamOptions): Promise<FileStream>;
682
+ /**
683
+ * `GET .../files/content` of `path` (or of `abs`, already absolute); undefined when the server has
684
+ * no such route. `not_found` and `not_a_file` become `not_found`: a directory is not a file either.
685
+ */
686
+ private openRoute;
687
+ /** Reads a whole response body of `path`, at most `limit` bytes. */
688
+ private readRoute;
689
+ /** A response body as a stream that errors with `file_changed` when it ends short of Content-Length. */
690
+ private countedBody;
691
+ private readExec;
692
+ /**
693
+ * Writes a file, creating parent directories. Replaces the file atomically (temp file + rename), so
694
+ * a failed or aborted write leaves the old file. Throws `is_a_directory` when `path` is a directory.
695
+ *
696
+ * `data` is a string, bytes, or a stream (a Node `Readable`, a web `ReadableStream`, an
697
+ * `AsyncIterable` of chunks): a stream is sent as it is read, in bounded memory, up to the server's
698
+ * 5 GiB. The size and SHA-256 the server reports are checked against what was sent
699
+ * (`transfer_mismatch` when they differ). On a server without the file routes, writes go over exec
700
+ * and are capped at 10 MiB (`file_too_large`).
701
+ */
702
+ write(path: string, data: WriteData, opts?: WriteOptions): Promise<WriteInfo>;
703
+ /**
704
+ * Writes over `PUT .../files?parents=true`, which writes a temp file beside the target and renames
705
+ * it into place once every byte arrived. False when the server has no such route.
413
706
  */
414
- write(path: string, data: string | Uint8Array): Promise<WriteInfo>;
707
+ private writeRoute;
708
+ /**
709
+ * True when the server has the file routes. A stream can be sent only once, so before the first one
710
+ * the route is probed with a relative path, which the server refuses (400) before touching the
711
+ * sandbox; a server without the route answers 404 or 405.
712
+ */
713
+ private routesAvailable;
714
+ /**
715
+ * `PUT .../files` of `body` to the absolute path `abs`, checking the size and SHA-256 the server
716
+ * reports. Bytes are retried on 502-504 (the server replaces the file atomically, so a repeat writes
717
+ * the same bytes); a stream is sent once, as it is read, and given up when it moves nothing for
718
+ * 2 minutes. Undefined when the server has no such route.
719
+ */
720
+ private put;
721
+ private putStream;
722
+ private writeExec;
723
+ /**
724
+ * Puts `src` at the absolute temporary path `abs` (mode 0600): over the file route, or in base64
725
+ * chunks over exec (`instabox push`'s fallback) on a server without it.
726
+ */
727
+ private putTemp;
728
+ /**
729
+ * Runs a transfer script and returns its stdout after `mark`. A non-zero exit throws `transfer_failed`
730
+ * (`permission_denied`, status 403, when the sandbox refused access), as the CLI reports it.
731
+ */
732
+ private transferExec;
733
+ /**
734
+ * Uploads a local directory's contents into `remoteDir` in one call, as one gzipped tar, the way
735
+ * `instabox push` does: streamed over `PUT .../files` to a temporary file, then unpacked in the
736
+ * sandbox with `tar`. `remoteDir` and its parents are created; existing files there are replaced,
737
+ * others kept. In a git work tree only what git tracks is uploaded (pass `all: true` to add
738
+ * untracked files git does not ignore, `git: false` to upload everything). Symlinks are uploaded as
739
+ * symlinks, never followed; sockets, FIFOs and devices are skipped. Node.js (or Bun, Deno) only.
740
+ */
741
+ upload(localDir: string, remoteDir: string, opts?: UploadOptions): Promise<UploadInfo>;
742
+ /**
743
+ * Downloads a sandbox directory into `localDir` in one call, as one gzipped tar, the way
744
+ * `instabox pull` packs it: `tar` in the sandbox (as root when sudo allows, as the file routes read),
745
+ * streamed back over `GET .../files/content` and unpacked as it arrives. `localDir` and its parents
746
+ * are created; existing files are replaced, others kept. Everything under `remoteDir` comes, dot
747
+ * files and empty directories included; symlinks arrive as symlinks. No entry can write outside
748
+ * `localDir`. Node.js (or Bun, Deno) only.
749
+ */
750
+ download(remoteDir: string, localDir: string, opts?: DownloadOptions): Promise<DownloadInfo>;
751
+ /** The temporary archive's bytes: over the file route, or in base64 chunks over exec without it. */
752
+ private fetchTemp;
753
+ /**
754
+ * @internal Stages bytes as a temporary file for a command's stdin (`instabox exec --stdin`'s way) and
755
+ * returns its path. The command removes it as it starts.
756
+ */
757
+ stageStdin(bytes: Uint8Array, signal?: AbortSignal): Promise<string>;
758
+ /** The file routes take absolute paths; a relative one is relative to exec's working directory (HOME). */
759
+ private absolute;
415
760
  /** Lists the entries of a directory (not recursive). */
416
761
  list(path: string): Promise<EntryInfo[]>;
417
762
  /** Removes a file or a directory (recursively). Missing paths are fine. */
@@ -516,14 +861,7 @@ interface SandboxOpts extends ConnectionOptions {
516
861
  metadata?: Record<string, string>;
517
862
  /** Environment variables applied to every `commands.run` of this Sandbox object (client-side). */
518
863
  envs?: Record<string, string>;
519
- /**
520
- * The server pauses (or with `onTimeout: 'kill'` deletes) the sandbox this long after creation.
521
- * Sent as whole seconds, 60 s to 24 h. Default: no timeout. Change it with `setTimeout()`.
522
- */
523
- timeoutMs?: number;
524
- /** What happens at the timeout: `pause` (default) or `kill`. */
525
- onTimeout?: OnTimeout;
526
- /** Stop and archive after this many milliseconds, independent of the pause/kill timeout. */
864
+ /** Stop and archive after this many milliseconds. */
527
865
  archiveMs?: number;
528
866
  /**
529
867
  * The server pauses the sandbox once it has been idle this long (no agent working, no terminal use,
@@ -547,6 +885,13 @@ interface SandboxOpts extends ConnectionOptions {
547
885
  * Default: the sandbox gets them. Cannot be turned on again later.
548
886
  */
549
887
  vault?: boolean;
888
+ /**
889
+ * @deprecated Removed in 0.6.0: sandboxes have no lifetime timeout since 2026-10-20. Passing it throws
890
+ * `InstaboxError` (`code: 'retired_option'`); use `autoSuspendMs`, `archiveMs` or `kill()` instead.
891
+ */
892
+ timeoutMs?: never;
893
+ /** @deprecated Removed in 0.6.0 with `timeoutMs`; passing it throws. */
894
+ onTimeout?: never;
550
895
  }
551
896
  interface SandboxConnectOpts extends ConnectionOptions {
552
897
  /** Resume the sandbox if it is paused (suspended) or stopped. Default true. */
@@ -570,10 +915,7 @@ interface SandboxInfo {
570
915
  vault: boolean;
571
916
  /** Creation time of the machine. */
572
917
  startedAt: Date;
573
- /** When the server pauses or kills the sandbox (see `onTimeout`); undefined for no timeout. */
574
- endAt?: Date;
575
918
  archiveAt?: Date;
576
- onTimeout: OnTimeout;
577
919
  /** Idle time after which the server pauses the sandbox; undefined when it never does. */
578
920
  autoSuspendMs?: number;
579
921
  state: MachineState;
@@ -616,6 +958,11 @@ interface SandboxUsage {
616
958
  memGiBSeconds: number;
617
959
  /** Disk size (system disk plus /data) times the seconds the sandbox existed in the window. */
618
960
  diskGiBSeconds: number;
961
+ /**
962
+ * Bytes sent to the public internet, by whole hour: every hour from the one `from` falls in up to `to`.
963
+ * Billed or not (the plan's free egress and free sandboxes included). Absent from older servers.
964
+ */
965
+ egressBytes?: number;
619
966
  }
620
967
  interface SandboxUsageOpts {
621
968
  /** Default: the start of the current calendar month (UTC). */
@@ -688,18 +1035,17 @@ declare class Sandbox {
688
1035
  getUsage(opts?: SandboxUsageOpts): Promise<SandboxUsage>;
689
1036
  /** Fetches the current state of the sandbox. */
690
1037
  getInfo(): Promise<SandboxInfo>;
691
- /**
692
- * Sets the timeout to `timeoutMs` from now (whole seconds, 60 s to 24 h); 0 clears it.
693
- * `onTimeout` changes what happens then (`pause` or `kill`).
694
- */
695
- setTimeout(timeoutMs: number, opts?: {
696
- onTimeout?: OnTimeout;
697
- }): Promise<void>;
698
1038
  /**
699
1039
  * Pauses the sandbox once it has been idle `idleMs` (whole seconds, 2 min to 24 h); 0 turns the idle
700
- * pause off. Unlike a timeout the setting stays across pause and resume.
1040
+ * pause off. The setting stays across pause and resume.
701
1041
  */
702
1042
  setAutoSuspend(idleMs: number): Promise<void>;
1043
+ /**
1044
+ * @deprecated Removed in 0.6.0: sandboxes have no lifetime timeout since 2026-10-20. Always rejects with
1045
+ * `InstaboxError` (`code: 'retired_option'`) naming the replacements (`setAutoSuspend()`, `kill()`), and
1046
+ * sends no request.
1047
+ */
1048
+ setTimeout(..._args: unknown[]): Promise<never>;
703
1049
  /** Replaces the sandbox's metadata (`{}` clears it). */
704
1050
  setMetadata(metadata: Record<string, string>): Promise<void>;
705
1051
  /**
@@ -755,4 +1101,4 @@ declare class Sandbox {
755
1101
  private mutate;
756
1102
  }
757
1103
 
758
- 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 MachineMetric, type MachineMetrics, type MachineSpec, type MachineState, type MachineUsage, type MachineVault, type MachineVaultItem, type MouseButton, type OnTimeout, type Operation, 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 Usage, type UsageLimits, type UsageMachineStorage, type UsageStorage, type VaultApplied, type VaultFile, type VaultKept, type WriteInfo };
1104
+ 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 ReadStreamOptions, 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 };