@keska/sandbox 0.42.0 → 0.44.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.
Files changed (3) hide show
  1. package/dist/index.d.ts +266 -72
  2. package/dist/index.js +300 -58
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -365,6 +365,31 @@ function writeTar(files) {
365
365
  return Buffer.concat(chunks);
366
366
  }
367
367
 
368
+ // ../sdk-shared-ts/src/heartbeat.ts
369
+ var IMAGE_BUILD_HEARTBEAT_MS = 15e3;
370
+ function startImageBuildHeartbeat(opts) {
371
+ const intervalMs = opts?.intervalMs ?? IMAGE_BUILD_HEARTBEAT_MS;
372
+ const write2 = opts?.write ?? ((line) => process.stderr.write(`${line}
373
+ `));
374
+ const schedule = opts?.schedule ?? ((tick, ms) => {
375
+ const id = setInterval(tick, ms);
376
+ return { cancel: () => clearInterval(id) };
377
+ });
378
+ write2("building image...");
379
+ let ticks = 0;
380
+ let stopped = false;
381
+ const step = Math.round(intervalMs / 1e3);
382
+ const handle = schedule(() => {
383
+ if (stopped) return;
384
+ ticks += 1;
385
+ write2(`building image... ${ticks * step}s`);
386
+ }, intervalMs);
387
+ return () => {
388
+ stopped = true;
389
+ handle.cancel();
390
+ };
391
+ }
392
+
368
393
  // ../sdk-shared-ts/src/errors.ts
369
394
  var SandboxError = class extends Error {
370
395
  code;
@@ -426,7 +451,11 @@ var ConflictError = class extends SandboxError {
426
451
  };
427
452
  var PermissionDeniedError = class extends SandboxError {
428
453
  };
429
- var SandboxTimeoutError = class extends SandboxError {
454
+ var TimeoutError = class extends SandboxError {
455
+ };
456
+ var ImageTimeoutError = class extends TimeoutError {
457
+ };
458
+ var SandboxTimeoutError = class extends TimeoutError {
430
459
  };
431
460
  var PageExhaustedError = class extends SandboxError {
432
461
  constructor(message = "no more pages") {
@@ -440,8 +469,6 @@ var CommandFailedError = class extends SandboxError {
440
469
  };
441
470
  var PathNotFoundError = class extends NotFoundError {
442
471
  };
443
- var FileNotFoundError = class extends PathNotFoundError {
444
- };
445
472
  var DirectoryNotEmptyError = class extends ConflictError {
446
473
  };
447
474
  var FileExistsError = class extends SandboxError {
@@ -488,7 +515,7 @@ var ProcessWaitTimeoutError = class extends SandboxTimeoutError {
488
515
  var SandboxWaitTimeoutError = class extends SandboxTimeoutError {
489
516
  };
490
517
  var BY_REASON = {
491
- FILE_NOT_FOUND: FileNotFoundError,
518
+ FILE_NOT_FOUND: PathNotFoundError,
492
519
  DIR_NOT_EMPTY: DirectoryNotEmptyError,
493
520
  FILE_EXISTS: FileExistsError,
494
521
  FILE_TOO_LARGE: FileTooLargeError,
@@ -500,7 +527,13 @@ var BY_REASON = {
500
527
  SANDBOX_SLEEPING: SandboxSleepingError,
501
528
  PATH_INVALID: InvalidPathError,
502
529
  SANDBOX_NOT_FOUND: SandboxNotFoundError,
503
- NAME_NOT_FOUND: SandboxNotFoundError,
530
+ NAME_NOT_FOUND: NotFoundError,
531
+ IMAGE_NOT_FOUND: NotFoundError,
532
+ VOLUME_NOT_FOUND: NotFoundError,
533
+ SECRET_NOT_FOUND: NotFoundError,
534
+ SNAPSHOT_NOT_FOUND: NotFoundError,
535
+ TAG_NOT_FOUND: NotFoundError,
536
+ AGENT_NOT_FOUND: NotFoundError,
504
537
  SANDBOX_NOT_READY: SandboxNotReadyError,
505
538
  SIZE_NOT_PARKED: SandboxNotReadyError,
506
539
  SIZE_NOT_SLEEPING: SandboxNotReadyError,
@@ -512,7 +545,6 @@ var BY_REASON = {
512
545
  GUEST_RUNTIME_DEAD: GuestRuntimeDeadError,
513
546
  CAPACITY: CapacityError,
514
547
  UNAUTHENTICATED: AuthenticationError,
515
- DEADLINE: SandboxTimeoutError,
516
548
  CANCELED: SandboxError,
517
549
  UNAVAILABLE: UnavailableError,
518
550
  INTERNAL: SandboxError
@@ -566,9 +598,61 @@ var INVALID_ARGUMENT_REASONS = /* @__PURE__ */ new Set([
566
598
  "FILE_OP",
567
599
  "CLONE",
568
600
  "SOURCE_CLASS",
569
- "SANDBOX_STATE"
601
+ "STATE_ENUM"
602
+ ]);
603
+ var IMAGE_DEADLINE = /* @__PURE__ */ new Set(["BuildImage", "RegisterImage"]);
604
+ var CATALOG_DEADLINE = /* @__PURE__ */ new Set([
605
+ "CreateSnapshot",
606
+ "GetSnapshot",
607
+ "ListSnapshots",
608
+ "SetSnapshotLabels",
609
+ "DeleteSnapshot",
610
+ "CreateVolume",
611
+ "GetVolume",
612
+ "ListVolumes",
613
+ "SetVolumeLabels",
614
+ "DeleteVolume",
615
+ "SetSecret",
616
+ "GetSecret",
617
+ "ListSecrets",
618
+ "DeleteSecret",
619
+ "CreateAgent",
620
+ "GetAgent",
621
+ "ListAgents",
622
+ "DeleteAgent",
623
+ "SetAgentSecret",
624
+ "DeleteAgentSecret",
625
+ "CreateToken",
626
+ "GetToken",
627
+ "RevokeToken",
628
+ "CreateTag",
629
+ "GetTag",
630
+ "ListTags",
631
+ "UpdateTag",
632
+ "DeleteTag",
633
+ "CreatePolicy",
634
+ "GetPolicy",
635
+ "ListPolicies",
636
+ "UpdatePolicy",
637
+ "DeletePolicy",
638
+ "GetImage",
639
+ "ListImages",
640
+ "DeleteImage"
570
641
  ]);
571
- function errorClass(reason) {
642
+ function deadlineClass(procedure) {
643
+ const name = procedure.split("/").pop() ?? procedure;
644
+ if (IMAGE_DEADLINE.has(name)) {
645
+ return ImageTimeoutError;
646
+ }
647
+ if (CATALOG_DEADLINE.has(name)) {
648
+ return TimeoutError;
649
+ }
650
+ return SandboxTimeoutError;
651
+ }
652
+ function errorClass(reason, procedure = "") {
653
+ if (reason === "DEADLINE") {
654
+ return deadlineClass(procedure);
655
+ }
572
656
  if (BY_REASON[reason]) {
573
657
  return BY_REASON[reason];
574
658
  }
@@ -577,9 +661,27 @@ function errorClass(reason) {
577
661
  }
578
662
  return SandboxError;
579
663
  }
580
- function sandboxError(message, fields) {
581
- const Ctor = errorClass(fields.reason ?? "");
582
- return new Ctor(message, fields);
664
+ var ACTION = {
665
+ DIR_NOT_EMPTY: "A directory remove needs `recursive` because the directory is not empty.",
666
+ COMMAND_TIMEOUT: "The command was killed because `timeout` elapsed. Pass a larger timeout.",
667
+ PORT_NOT_OPEN: "Nothing is listening on the forwarded port.",
668
+ SANDBOX_SLEEPING: "The sandbox is sleeping. Wake it before an HTTP request.",
669
+ FILE_NOT_FOUND: "The guest path does not exist.",
670
+ EXECUTABLE_NOT_FOUND: "The command executable is not on the guest.",
671
+ SANDBOX_NOT_READY: "The sandbox is not in the state this call requires.",
672
+ CAPACITY: "The project has no room for another sandbox of this size."
673
+ };
674
+ function explained(message, reason) {
675
+ const text = message.trim();
676
+ if (text !== "" && !/^(unknown|internal|not found|canceled|cancelled)$/i.test(text)) {
677
+ return message;
678
+ }
679
+ return ACTION[reason] ?? message;
680
+ }
681
+ function sandboxError(message, fields, procedure = "") {
682
+ const reason = fields.reason ?? "";
683
+ const Ctor = errorClass(reason, procedure);
684
+ return new Ctor(explained(message, reason), fields);
583
685
  }
584
686
 
585
687
  // ../sdk-shared-ts/src/resource_defaults.ts
@@ -772,28 +874,60 @@ function logRpc(err, procedure = "") {
772
874
  err.requestId ?? ""
773
875
  );
774
876
  }
775
- function rewrite(error, timeoutMs) {
776
- const wrapped = deadlineOr(error, timeoutMs);
877
+ function rewrite(error, timeoutMs, procedure = "") {
878
+ const wrapped = deadlineOr(error, timeoutMs, procedure);
777
879
  return wrapped instanceof SandboxError ? wrapped : error;
778
880
  }
881
+ function deadlineMessage(procedure, timeoutMs) {
882
+ const name = procedure.split("/").pop() ?? procedure;
883
+ const after = timeoutMs != null && timeoutMs > 0 ? ` after ${Math.trunc(timeoutMs / 1e3)}s` : "";
884
+ if (name === "CreateSandbox") {
885
+ return `Create timed out${after}. Pass a larger timeout on sandboxes.create.`;
886
+ }
887
+ if (name === "BuildImage") {
888
+ return `Image build timed out${after}. Pass a larger timeout or waitSec on images.build.`;
889
+ }
890
+ if (name === "RegisterImage") {
891
+ return `Image register timed out${after}. Pass a larger timeout or waitSec on images.register.`;
892
+ }
893
+ return `Deadline exceeded${after}. Pass a larger timeout on this call.`;
894
+ }
895
+ function bareDeadline(message) {
896
+ const text = message.trim().toLowerCase();
897
+ return text === "" || text === "deadline exceeded" || text === "context deadline exceeded";
898
+ }
899
+ function deadlineFields(fields, message, procedure, timeoutMs) {
900
+ const reason = fields.reason ?? "";
901
+ if (fields.code !== "deadline_exceeded" || reason !== "" && reason !== "DEADLINE") {
902
+ return { message, fields };
903
+ }
904
+ const next = { ...fields, code: "deadline_exceeded", reason: "DEADLINE" };
905
+ if (!bareDeadline(message)) {
906
+ return { message, fields: next };
907
+ }
908
+ return { message: deadlineMessage(procedure, timeoutMs), fields: next };
909
+ }
779
910
  function mapConnectError(error, timeoutMs, procedure = "") {
780
911
  if (error instanceof SandboxError) {
781
- const wrapped2 = rewrite(error, timeoutMs);
912
+ const wrapped2 = rewrite(error, timeoutMs, procedure);
782
913
  logRpc(wrapped2, procedure);
783
914
  return wrapped2;
784
915
  }
785
916
  if (error instanceof ConnectError) {
786
917
  const code = codeName(error.code);
787
918
  const fields = fieldsFromHeaders(error.metadata, code);
788
- const mapped = sandboxError(
919
+ const prepared = deadlineFields(
920
+ fields,
789
921
  withCapacitySentence(code, error.rawMessage || error.message, fields.resource),
790
- fields
922
+ procedure,
923
+ timeoutMs
791
924
  );
792
- const wrapped2 = rewrite(mapped, timeoutMs);
925
+ const mapped = sandboxError(prepared.message, prepared.fields, procedure);
926
+ const wrapped2 = rewrite(mapped, timeoutMs, procedure);
793
927
  logRpc(wrapped2, procedure);
794
928
  return wrapped2;
795
929
  }
796
- const wrapped = deadlineOr(error, timeoutMs);
930
+ const wrapped = deadlineOr(error, timeoutMs, procedure);
797
931
  if (wrapped instanceof SandboxError) {
798
932
  logRpc(wrapped);
799
933
  return wrapped;
@@ -986,8 +1120,9 @@ var BidiQueue = class {
986
1120
  }
987
1121
  }
988
1122
  };
989
- function asDeadline(error) {
990
- return new SandboxError("deadline exceeded", {
1123
+ function asDeadline(error, timeoutMs, procedure = "") {
1124
+ const Ctor = deadlineClass(procedure);
1125
+ return new Ctor(deadlineMessage(procedure, timeoutMs), {
991
1126
  code: "deadline_exceeded",
992
1127
  reason: "DEADLINE",
993
1128
  sandboxId: error.sandboxId,
@@ -1001,29 +1136,34 @@ function asDeadline(error) {
1001
1136
  retryAfterSec: error.retryAfterSec
1002
1137
  });
1003
1138
  }
1004
- function deadlineOr(error, timeoutMs) {
1005
- if (timeoutMs === void 0) {
1006
- return error instanceof Error ? error : new Error(String(error));
1007
- }
1139
+ function deadlineOr(error, timeoutMs, procedure = "") {
1008
1140
  if (error instanceof SandboxError) {
1009
- if (error.code === "canceled") {
1010
- return asDeadline(error);
1141
+ if (timeoutMs !== void 0 && (error.code === "canceled" || error.code === "internal" && /without exit/i.test(error.message))) {
1142
+ return asDeadline(error, timeoutMs, procedure);
1011
1143
  }
1012
- if (error.code === "internal" && /without exit/i.test(error.message)) {
1013
- return asDeadline(error);
1144
+ if (error.code === "deadline_exceeded" && bareDeadline(error.message)) {
1145
+ return asDeadline(error, timeoutMs, procedure);
1014
1146
  }
1015
1147
  return error;
1016
1148
  }
1149
+ if (timeoutMs === void 0) {
1150
+ return error instanceof Error ? error : new Error(String(error));
1151
+ }
1017
1152
  if (error instanceof ConnectError && error.code === Code.Canceled) {
1018
- return asDeadline(sandboxError(error.rawMessage || error.message, fieldsFromHeaders(error.metadata, "canceled")));
1153
+ return asDeadline(
1154
+ sandboxError(error.rawMessage || error.message, fieldsFromHeaders(error.metadata, "canceled")),
1155
+ timeoutMs,
1156
+ procedure
1157
+ );
1019
1158
  }
1020
1159
  const name = error instanceof Error ? error.name : "";
1021
- if (name === "TimeoutError" || name === "AbortError" || name === "DOMException") {
1022
- return new SandboxError("deadline exceeded", { code: "deadline_exceeded", reason: "DEADLINE" });
1023
- }
1024
1160
  const msg = error instanceof Error ? error.message : String(error);
1025
- if (/NGHTTP2_CANCEL|ERR_HTTP2_STREAM|stream closed|session closed/i.test(msg)) {
1026
- return new SandboxError("deadline exceeded", { code: "deadline_exceeded", reason: "DEADLINE" });
1161
+ if (name === "TimeoutError" || name === "AbortError" || name === "DOMException" || /NGHTTP2_CANCEL|ERR_HTTP2_STREAM|stream closed|session closed/i.test(msg)) {
1162
+ const Ctor = deadlineClass(procedure);
1163
+ return new Ctor(deadlineMessage(procedure, timeoutMs), {
1164
+ code: "deadline_exceeded",
1165
+ reason: "DEADLINE"
1166
+ });
1027
1167
  }
1028
1168
  return error instanceof Error ? error : new Error(msg);
1029
1169
  }
@@ -1292,7 +1432,7 @@ var ForwardSession = class {
1292
1432
  reject(this.err);
1293
1433
  return;
1294
1434
  }
1295
- reject(new SandboxError("forward recv timed out", { code: "deadline_exceeded", reason: "DEADLINE" }));
1435
+ reject(new SandboxTimeoutError("forward recv timed out", { code: "deadline_exceeded", reason: "DEADLINE" }));
1296
1436
  }, timeoutMs);
1297
1437
  const onValue = (value) => {
1298
1438
  clearTimeout(timer);
@@ -1719,9 +1859,10 @@ function bytesToB64(value) {
1719
1859
  return Buffer.from(value, "utf8").toString("base64");
1720
1860
  }
1721
1861
  function imageRpcTimeout(timeoutMs, wait, waitSec) {
1722
- if (!wait) return timeoutMs;
1723
- const waitMs = Math.max(waitSec ?? 600, 0) * 1e3;
1724
- return Math.max(timeoutMs, waitMs);
1862
+ if (timeoutMs === 0) return void 0;
1863
+ if (timeoutMs != null) return timeoutMs;
1864
+ if (!wait) return 18e4;
1865
+ return Math.max(waitSec ?? 600, 0) * 1e3;
1725
1866
  }
1726
1867
  function modeField(mode) {
1727
1868
  return typeof mode === "number" && mode > 0 ? { mode } : {};
@@ -1905,7 +2046,7 @@ var Session = class {
1905
2046
  labels: params.labels ?? {},
1906
2047
  ...fillCreateResourceDefaults(params)
1907
2048
  },
1908
- params.timeoutMs ?? 18e4,
2049
+ params.timeoutMs === void 0 ? 1e4 : params.timeoutMs === 0 ? void 0 : params.timeoutMs,
1909
2050
  params.signal
1910
2051
  );
1911
2052
  return parseSandbox(body);
@@ -2689,7 +2830,7 @@ var Session = class {
2689
2830
  const registered = await this.call(
2690
2831
  "RegisterImage",
2691
2832
  body,
2692
- imageRpcTimeout(opts.timeoutMs ?? 6e5, wait, opts.waitSec),
2833
+ imageRpcTimeout(opts.timeoutMs, wait, opts.waitSec),
2693
2834
  opts.signal
2694
2835
  );
2695
2836
  return parseImage(registered);
@@ -2713,10 +2854,11 @@ var Session = class {
2713
2854
  };
2714
2855
  }
2715
2856
  }
2857
+ const stopHeartbeat = startImageBuildHeartbeat();
2716
2858
  try {
2717
2859
  const res = await this.svc.buildImage(chunks(), {
2718
2860
  signal: opts.signal,
2719
- timeoutMs: imageRpcTimeout(opts.timeoutMs ?? 6e5, wait, opts.waitSec),
2861
+ timeoutMs: imageRpcTimeout(opts.timeoutMs, wait, opts.waitSec),
2720
2862
  headers: this.extraHeaders()
2721
2863
  });
2722
2864
  return parseImage({
@@ -2726,7 +2868,9 @@ var Session = class {
2726
2868
  updatedAt: res.updatedAt
2727
2869
  });
2728
2870
  } catch (error) {
2729
- throw mapConnectError(error, opts.timeoutMs ?? 6e5);
2871
+ throw mapConnectError(error, imageRpcTimeout(opts.timeoutMs, wait, opts.waitSec), "BuildImage");
2872
+ } finally {
2873
+ stopHeartbeat();
2730
2874
  }
2731
2875
  }
2732
2876
  async getImage(name, opts) {
@@ -4239,6 +4383,7 @@ var Sandbox = class _Sandbox {
4239
4383
  fromSnapshotId: params.fromSnapshotId ?? "",
4240
4384
  volumeId: params.volumeId ?? "",
4241
4385
  labels: params.labels ?? {},
4386
+ timeoutMs: params.timeoutMs,
4242
4387
  ...fillCreateResourceDefaults(params)
4243
4388
  };
4244
4389
  const info = await wire.createSandbox(create);
@@ -4636,7 +4781,7 @@ var Sandbox = class _Sandbox {
4636
4781
  signal: opts?.signal
4637
4782
  });
4638
4783
  } catch (error) {
4639
- if ((opts?.missingOk ?? true) && error instanceof FileNotFoundError) {
4784
+ if ((opts?.missingOk ?? true) && error instanceof PathNotFoundError) {
4640
4785
  return;
4641
4786
  }
4642
4787
  throw error;
@@ -4708,7 +4853,7 @@ var Sandbox = class _Sandbox {
4708
4853
  try {
4709
4854
  await this.wire.deleteSnapshot(snap.id);
4710
4855
  } catch (error) {
4711
- if (!(error instanceof SandboxNotFoundError)) {
4856
+ if (!(error instanceof NotFoundError)) {
4712
4857
  throw error;
4713
4858
  }
4714
4859
  }
@@ -4746,15 +4891,23 @@ var Sandbox = class _Sandbox {
4746
4891
  // src/surface.ts
4747
4892
  var UNLIMITED = Number.POSITIVE_INFINITY;
4748
4893
  var SandboxStatus = {
4894
+ /** The sandbox is being created. */
4749
4895
  PENDING: "Pending",
4896
+ /** The guest is up and accepts calls. */
4750
4897
  READY: "Ready",
4898
+ /** The VM is stopped and the disk is kept. */
4751
4899
  SLEEPING: "Sleeping",
4900
+ /** The sandbox has exited and will be deleted. */
4752
4901
  FINISHED: "Finished",
4902
+ /** A delete is in progress. */
4753
4903
  DELETING: "Deleting"
4754
4904
  };
4755
4905
  var LogStream = {
4906
+ /** Guest stdout. */
4756
4907
  STDOUT: "stdout",
4908
+ /** Guest stderr. */
4757
4909
  STDERR: "stderr",
4910
+ /** A platform event, not guest output. */
4758
4911
  EVENT: "event"
4759
4912
  };
4760
4913
  var Page = class {
@@ -4766,15 +4919,18 @@ var Page = class {
4766
4919
  items;
4767
4920
  nextPageToken;
4768
4921
  fetchPage;
4922
+ /** True when `next` will fetch another page. */
4769
4923
  get hasMore() {
4770
4924
  return this.nextPageToken != null;
4771
4925
  }
4926
+ /** Fetch the following page. Throws `PageExhaustedError` on the last page. */
4772
4927
  async next() {
4773
4928
  if (this.nextPageToken == null) {
4774
4929
  throw new PageExhaustedError();
4775
4930
  }
4776
4931
  return this.fetchPage(this.nextPageToken);
4777
4932
  }
4933
+ /** Iterate the rows on this page. */
4778
4934
  [Symbol.iterator]() {
4779
4935
  return this.items[Symbol.iterator]();
4780
4936
  }
@@ -4903,6 +5059,8 @@ var SIGNALS = {
4903
5059
  SIGINT: 2,
4904
5060
  SIGQUIT: 3,
4905
5061
  SIGKILL: 9,
5062
+ SIGUSR1: 10,
5063
+ SIGUSR2: 12,
4906
5064
  SIGTERM: 15,
4907
5065
  SIGSTOP: 19
4908
5066
  };
@@ -4921,7 +5079,7 @@ async function missingOk(fn, ok) {
4921
5079
  try {
4922
5080
  await fn();
4923
5081
  } catch (error) {
4924
- if (ok && error instanceof SandboxNotFoundError) {
5082
+ if (ok && error instanceof NotFoundError) {
4925
5083
  return;
4926
5084
  }
4927
5085
  throw error;
@@ -4937,7 +5095,7 @@ async function retry(client, fn, opts) {
4937
5095
  try {
4938
5096
  return await fn();
4939
5097
  } catch (error) {
4940
- if (opts?.delete && attempt > 0 && error instanceof SandboxNotFoundError) {
5098
+ if (opts?.delete && attempt > 0 && error instanceof NotFoundError) {
4941
5099
  return void 0;
4942
5100
  }
4943
5101
  if (!(error instanceof SandboxError) || !error.retryable || attempt + 1 === attempts) {
@@ -4958,12 +5116,15 @@ var Agent = class {
4958
5116
  this.createdAt = info.createdAt;
4959
5117
  }
4960
5118
  client;
5119
+ /** Agent id. */
4961
5120
  id;
5121
+ /** Agent name. */
4962
5122
  name;
4963
5123
  /** Matrix user id to invite from your Matrix client. */
4964
5124
  matrixUserId;
4965
5125
  /** Env name to secret name. Values are not included. */
4966
5126
  secretEnv;
5127
+ /** When the agent was created. */
4967
5128
  createdAt;
4968
5129
  take(info) {
4969
5130
  this.name = info.name;
@@ -5044,15 +5205,23 @@ var Agents2 = class {
5044
5205
  }
5045
5206
  };
5046
5207
  var Client2 = class {
5208
+ /** Retries after the first try. Default 3. `0` is one attempt. */
5047
5209
  maxRetries;
5048
5210
  /** @internal */
5049
5211
  wire;
5212
+ /** Named disks. */
5050
5213
  volumes;
5214
+ /** Project secrets. Values cannot be read back. */
5051
5215
  secrets;
5216
+ /** Matrix agents. */
5052
5217
  agents;
5218
+ /** Platform and project images. */
5053
5219
  images;
5220
+ /** Filesystem snapshots. */
5054
5221
  snapshots;
5222
+ /** Names bound to a policy set. */
5055
5223
  tags;
5224
+ /** Create, list, and open sandboxes. */
5056
5225
  sandboxes;
5057
5226
  constructor(opts = {}) {
5058
5227
  this.maxRetries = opts.maxRetries ?? 3;
@@ -5083,14 +5252,12 @@ var Client2 = class {
5083
5252
  token = void 0;
5084
5253
  }
5085
5254
  }
5086
- const timeout = timeoutSeconds(opts.timeout);
5087
5255
  this.wire = new Client(opts.baseUrl ?? process.env.NUMEN_BASE_URL ?? "", {
5088
5256
  credentialsFile: credentialsFile ? expandHome(credentialsFile) : void 0,
5089
5257
  clientId,
5090
5258
  clientSecret,
5091
5259
  token,
5092
- tokenUrl,
5093
- timeoutMs: timeout == null ? void 0 : timeout === 0 ? void 0 : timeout * 1e3
5260
+ tokenUrl
5094
5261
  });
5095
5262
  this.volumes = new Volumes2(this);
5096
5263
  this.secrets = new Secrets2(this);
@@ -5100,12 +5267,15 @@ var Client2 = class {
5100
5267
  this.tags = new Tags2(this);
5101
5268
  this.sandboxes = new Sandboxes(this);
5102
5269
  }
5270
+ /** Close the connection. */
5103
5271
  close() {
5104
5272
  this.wire.close();
5105
5273
  }
5274
+ /** `using` calls this. */
5106
5275
  [Symbol.dispose]() {
5107
5276
  this.close();
5108
5277
  }
5278
+ /** `await using` calls this. */
5109
5279
  async [Symbol.asyncDispose]() {
5110
5280
  this.close();
5111
5281
  }
@@ -5199,16 +5369,24 @@ var Images2 = class {
5199
5369
  this.client = client;
5200
5370
  }
5201
5371
  client;
5372
+ /** Copy a public image into the project. Omit `timeout` to wait up to 600 seconds. */
5202
5373
  register(name, opts) {
5203
5374
  return this.client.wire.images.register(name, {
5204
5375
  from: opts.source,
5205
- timeout: timeoutSeconds(opts.timeout),
5376
+ ...opts.timeout == null ? {} : { timeout: timeoutSeconds(opts.timeout) },
5206
5377
  waitUntilReady: opts.waitUntilReady,
5207
5378
  waitSec: opts.waitSec
5208
5379
  });
5209
5380
  }
5381
+ /** Build a Dockerfile. Omit `timeout` to wait up to 600 seconds. Pass `timeout` or `waitSec` to replace that. */
5210
5382
  build(name, opts) {
5211
- return this.client.wire.images.build(name, { ...opts, timeout: timeoutSeconds(opts?.timeout) });
5383
+ return this.client.wire.images.build(name, {
5384
+ dockerfile: opts?.dockerfile,
5385
+ context: opts?.context,
5386
+ waitUntilReady: opts?.waitUntilReady,
5387
+ waitSec: opts?.waitSec,
5388
+ ...opts?.timeout == null ? {} : { timeout: timeoutSeconds(opts.timeout) }
5389
+ });
5212
5390
  }
5213
5391
  get(name, opts) {
5214
5392
  return retry(this.client, () => this.client.wire.images.get(name, { timeout: timeoutSeconds(opts?.timeout) }));
@@ -5304,7 +5482,7 @@ var Tags2 = class {
5304
5482
  return tag;
5305
5483
  }
5306
5484
  }
5307
- throw new SandboxNotFoundError(`no tag named ${name}`, { reason: "NAME_NOT_FOUND" });
5485
+ throw new NotFoundError(`no tag named ${name}`, { reason: "NAME_NOT_FOUND" });
5308
5486
  }
5309
5487
  async list(opts) {
5310
5488
  const load = async (token) => {
@@ -5361,8 +5539,10 @@ var Sandboxes = class {
5361
5539
  this.client = client;
5362
5540
  }
5363
5541
  client;
5542
+ /** Create a sandbox. Omit `timeout` for a 10 second deadline. */
5364
5543
  async create(opts) {
5365
5544
  const resources = opts.resources ?? {};
5545
+ const seconds = timeoutSeconds(opts.timeout, 10);
5366
5546
  const inner = await Sandbox.create(this.client.wire, {
5367
5547
  image: opts.image,
5368
5548
  name: opts.name,
@@ -5378,7 +5558,8 @@ var Sandboxes = class {
5378
5558
  tags: opts.tags,
5379
5559
  cpuMillicores: resources.cpu == null ? void 0 : cpuMillicores(resources.cpu),
5380
5560
  memoryBytes: resources.memory == null ? void 0 : parseBytes(resources.memory),
5381
- diskBytes: resources.disk == null ? void 0 : parseBytes(resources.disk)
5561
+ diskBytes: resources.disk == null ? void 0 : parseBytes(resources.disk),
5562
+ timeoutMs: seconds === 0 ? 0 : seconds * 1e3
5382
5563
  });
5383
5564
  return new Sandbox2(this.client, inner, opts.deleteOnExit !== false);
5384
5565
  }
@@ -5438,20 +5619,29 @@ var Sandbox2 = class _Sandbox {
5438
5619
  }
5439
5620
  client;
5440
5621
  inner;
5622
+ /** Files on the guest. */
5441
5623
  fs;
5624
+ /** Logs from this sandbox. */
5442
5625
  logs;
5626
+ /** Processes started with `start`. */
5443
5627
  processes;
5628
+ /** Credentials that let a caller reach one guest port. */
5444
5629
  httpGrants;
5630
+ /** When true, disposing the sandbox deletes it. */
5445
5631
  deleteOnExit;
5632
+ /** Last record from create, get, wake, or sleep. */
5446
5633
  get info() {
5447
5634
  return this.inner.info;
5448
5635
  }
5636
+ /** Sandbox id. */
5449
5637
  get id() {
5450
5638
  return this.inner.id;
5451
5639
  }
5640
+ /** Refresh `info`. Does not wake a sleeping sandbox. */
5452
5641
  get() {
5453
5642
  return this.inner.get();
5454
5643
  }
5644
+ /** Wake a sleeping sandbox. Omit `timeout` for no RPC deadline. */
5455
5645
  async wake(opts) {
5456
5646
  const info = await this.inner.open();
5457
5647
  if (opts?.wait === false) {
@@ -5459,6 +5649,7 @@ var Sandbox2 = class _Sandbox {
5459
5649
  }
5460
5650
  return this.inner.wait({ until: [SandboxStatus.READY], timeout: timeoutSeconds(opts?.timeout, UNLIMITED) });
5461
5651
  }
5652
+ /** Stop the VM and keep the disk. Omit `timeout` for no RPC deadline. */
5462
5653
  async sleep(opts) {
5463
5654
  const info = await this.inner.park();
5464
5655
  if (opts?.wait === false) {
@@ -5466,13 +5657,16 @@ var Sandbox2 = class _Sandbox {
5466
5657
  }
5467
5658
  return this.inner.wait({ until: [SandboxStatus.SLEEPING], timeout: timeoutSeconds(opts?.timeout, UNLIMITED) });
5468
5659
  }
5660
+ /** Block until the sandbox is in one of `until`. Omit `timeout` for no RPC deadline. */
5469
5661
  wait(opts) {
5470
5662
  const until = typeof opts.until === "string" ? [opts.until] : [...opts.until];
5471
5663
  return this.inner.wait({ until, timeout: timeoutSeconds(opts.timeout, UNLIMITED) });
5472
5664
  }
5665
+ /** Block until the sandbox is gone. Omit `timeout` for no RPC deadline. */
5473
5666
  waitDeleted(opts) {
5474
5667
  return this.inner.wait({ untilDeleted: true, timeout: timeoutSeconds(opts?.timeout, UNLIMITED) });
5475
5668
  }
5669
+ /** Change size. The sandbox must be sleeping. */
5476
5670
  resize(opts) {
5477
5671
  return this.inner.setSize({
5478
5672
  cpuMillicores: opts.cpu == null ? 0 : cpuMillicores(opts.cpu),
@@ -5480,6 +5674,7 @@ var Sandbox2 = class _Sandbox {
5480
5674
  diskBytes: opts.disk == null ? 0 : parseBytes(opts.disk)
5481
5675
  });
5482
5676
  }
5677
+ /** Replace labels, tags, or both. */
5483
5678
  async update(opts) {
5484
5679
  if (opts.labels) {
5485
5680
  await this.inner.setLabels(opts.labels);
@@ -5489,9 +5684,11 @@ var Sandbox2 = class _Sandbox {
5489
5684
  }
5490
5685
  return this.info;
5491
5686
  }
5687
+ /** Run a command and wait for it. Omit `timeout` for no RPC deadline. */
5492
5688
  run(argv, opts) {
5493
5689
  return this.exec(argv, true, opts);
5494
5690
  }
5691
+ /** `run` with binary stdout and stderr. */
5495
5692
  runBytes(argv, opts) {
5496
5693
  return this.exec(argv, false, opts);
5497
5694
  }
@@ -5519,9 +5716,11 @@ var Sandbox2 = class _Sandbox {
5519
5716
  }
5520
5717
  return result;
5521
5718
  }
5719
+ /** Run one shell string with `/bin/sh -c`. */
5522
5720
  sh(command, opts) {
5523
5721
  return this.run(["/bin/sh", "-c", command], opts);
5524
5722
  }
5723
+ /** Start a command and return its handle. Omit `timeout` for no RPC deadline. */
5525
5724
  async start(argv, opts) {
5526
5725
  const inner = await this.inner.start(argv, {
5527
5726
  env: opts?.env,
@@ -5533,19 +5732,24 @@ var Sandbox2 = class _Sandbox {
5533
5732
  });
5534
5733
  return new ProcessHandle2(this, inner);
5535
5734
  }
5735
+ /** Copy this sandbox's writable layer into new sandboxes. */
5536
5736
  async clone(opts) {
5537
5737
  const children = await this.inner.clone(opts?.count ?? 1, { concurrency: opts?.concurrency ?? 8 });
5538
5738
  return children.map((child) => new _Sandbox(this.client, child, false));
5539
5739
  }
5740
+ /** Freeze the writable layer. Start later sandboxes from the snapshot. */
5540
5741
  snapshot(opts) {
5541
5742
  return this.inner.snapshot(opts);
5542
5743
  }
5744
+ /** Client for a server listening inside the sandbox. */
5543
5745
  http(port, opts) {
5544
5746
  return this.inner.http(port, opts);
5545
5747
  }
5748
+ /** Delete the sandbox. */
5546
5749
  delete() {
5547
5750
  return this.inner.delete();
5548
5751
  }
5752
+ /** Delete when `deleteOnExit` is true. */
5549
5753
  async [Symbol.asyncDispose]() {
5550
5754
  if (this.deleteOnExit) {
5551
5755
  await this.delete();
@@ -5568,15 +5772,25 @@ var Files = class {
5568
5772
  this.sandbox = sandbox;
5569
5773
  }
5570
5774
  sandbox;
5775
+ /** Read a guest file as bytes. Omit `timeout` for 60 seconds. */
5571
5776
  read(path, opts) {
5572
5777
  return this.sandbox.inner.read(path, { timeout: timeoutSeconds(opts?.timeout, 60) });
5573
5778
  }
5779
+ /** Read a guest file as a UTF-8 string. Omit `timeout` for 60 seconds. */
5574
5780
  async readText(path, opts) {
5575
5781
  return (await this.read(path, opts)).toString("utf8");
5576
5782
  }
5783
+ /**
5784
+ * Write one file from memory. Replaces it if it exists.
5785
+ * @param timeout Omit for 60 seconds.
5786
+ */
5577
5787
  write(path, data, opts) {
5578
5788
  return this.sandbox.inner.upload(path, data, { mode: opts?.mode, timeout: timeoutSeconds(opts?.timeout, 60) });
5579
5789
  }
5790
+ /**
5791
+ * Upload a local file or directory. An existing target raises unless `overwrite` is set.
5792
+ * @param timeout Omit for 60 seconds.
5793
+ */
5580
5794
  upload(local, remote, opts) {
5581
5795
  return this.sandbox.inner.upload(remote, {
5582
5796
  local,
@@ -5585,27 +5799,34 @@ var Files = class {
5585
5799
  timeout: timeoutSeconds(opts?.timeout, 60)
5586
5800
  });
5587
5801
  }
5802
+ /** Download a guest path to a local path. Omit `timeout` for 60 seconds. */
5588
5803
  download(remote, local, opts) {
5589
5804
  return this.sandbox.inner.download(remote, local, { timeout: timeoutSeconds(opts?.timeout, 60) });
5590
5805
  }
5806
+ /** List a guest directory. Depth defaults to 1. Omit `timeout` for 60 seconds. */
5591
5807
  list(path, opts) {
5592
5808
  return this.sandbox.inner.ls(path, {
5593
5809
  maxDepth: fileDepth(opts?.depth),
5594
5810
  timeout: timeoutSeconds(opts?.timeout, 60)
5595
5811
  });
5596
5812
  }
5813
+ /** One guest path's type and size. */
5597
5814
  stat(path) {
5598
5815
  return this.sandbox.inner.stat(path);
5599
5816
  }
5817
+ /** Create a guest directory, including missing parents. */
5600
5818
  mkdir(path) {
5601
5819
  return this.sandbox.inner.mkdir(path);
5602
5820
  }
5821
+ /** Remove a guest path. A missing path succeeds unless `missingOk` is false. A non-empty directory needs `recursive`. */
5603
5822
  remove(path, opts) {
5604
- return this.sandbox.inner.rm(path, { recursive: opts?.recursive, missingOk: opts?.missingOk });
5823
+ return this.sandbox.inner.rm(path, { recursive: opts?.recursive, missingOk: opts?.missingOk !== false });
5605
5824
  }
5825
+ /** Download a guest directory as a tar file. Omit `timeout` for 60 seconds. */
5606
5826
  export(path, dest, opts) {
5607
5827
  return this.sandbox.inner.exportPath(path, { dest, gzip: opts?.gzip, timeout: timeoutSeconds(opts?.timeout, 60) });
5608
5828
  }
5829
+ /** Apply several file changes in one call. Omit `timeout` for 60 seconds. */
5609
5830
  batch(ops, opts) {
5610
5831
  return this.sandbox.inner.write(
5611
5832
  ops.map((op) => {
@@ -5628,6 +5849,7 @@ var Logs = class {
5628
5849
  }
5629
5850
  sandbox;
5630
5851
  processId;
5852
+ /** One page of logs. Pass `pageToken` from the previous page to continue. */
5631
5853
  async list(opts) {
5632
5854
  const processId = opts?.processId ?? this.processId;
5633
5855
  const load = async (token) => {
@@ -5642,6 +5864,7 @@ var Logs = class {
5642
5864
  };
5643
5865
  return load(opts?.pageToken);
5644
5866
  }
5867
+ /** Yield log entries, following pages until `limit`. */
5645
5868
  iter(opts) {
5646
5869
  return iterate((token) => this.list({ ...opts, pageToken: token }), opts?.limit);
5647
5870
  }
@@ -5651,9 +5874,11 @@ var Processes = class {
5651
5874
  this.sandbox = sandbox;
5652
5875
  }
5653
5876
  sandbox;
5877
+ /** Look up one guest process by id. */
5654
5878
  async get(id) {
5655
5879
  return new ProcessHandle2(this.sandbox, await this.sandbox.inner.process(id));
5656
5880
  }
5881
+ /** Guest processes for this sandbox. */
5657
5882
  async list() {
5658
5883
  const rows = await this.sandbox.inner.processes();
5659
5884
  return rows.map((row) => new ProcessHandle2(this.sandbox, row));
@@ -5664,14 +5889,17 @@ var HTTPGrants = class {
5664
5889
  this.sandbox = sandbox;
5665
5890
  }
5666
5891
  sandbox;
5892
+ /** Mint a grant for a guest port. The token is set only on this call. */
5667
5893
  create(port, opts) {
5668
5894
  return this.sandbox.inner.createHttpGrant(port, { ttlSec: opts?.ttl });
5669
5895
  }
5896
+ /** Grants for this sandbox. Tokens are not included. */
5670
5897
  list() {
5671
5898
  return this.sandbox.inner.listHttpGrants();
5672
5899
  }
5673
- delete(id) {
5674
- return this.sandbox.inner.deleteHttpGrant(id);
5900
+ /** Delete a grant. A missing grant raises unless `missingOk` is set. */
5901
+ delete(id, opts) {
5902
+ return missingOk(() => this.sandbox.inner.deleteHttpGrant(id), opts?.missingOk === true);
5675
5903
  }
5676
5904
  };
5677
5905
  var ProcessHandle2 = class {
@@ -5680,34 +5908,45 @@ var ProcessHandle2 = class {
5680
5908
  this.logs = new Logs(sandbox, inner.id);
5681
5909
  }
5682
5910
  inner;
5911
+ /** Logs for this process. */
5683
5912
  logs;
5913
+ /** Process id. */
5684
5914
  get id() {
5685
5915
  return this.inner.id;
5686
5916
  }
5917
+ /** Last known status. */
5687
5918
  get status() {
5688
5919
  return this.inner.status;
5689
5920
  }
5921
+ /** Name passed to `start`, or empty. */
5690
5922
  get name() {
5691
5923
  return this.inner.serviceName;
5692
5924
  }
5925
+ /** Exit code once the process has finished. */
5693
5926
  get exitCode() {
5694
5927
  return this.inner.exitCode;
5695
5928
  }
5929
+ /** Refresh status without waiting. */
5696
5930
  poll() {
5697
5931
  return this.inner.poll();
5698
5932
  }
5933
+ /** Block until the process exits. Omit `timeout` for no RPC deadline. */
5699
5934
  wait(opts) {
5700
5935
  return this.inner.wait({ timeout: timeoutSeconds(opts?.timeout, UNLIMITED) });
5701
5936
  }
5937
+ /** Send a signal. The default is `SIGTERM`. */
5702
5938
  kill(signal = "SIGTERM") {
5703
5939
  return this.inner.kill(signalNumber(signal));
5704
5940
  }
5941
+ /** Write to the process stdin. */
5705
5942
  writeStdin(data = Buffer.alloc(0), opts) {
5706
5943
  return this.inner.writeStdin(data, opts);
5707
5944
  }
5945
+ /** Close stdin. */
5708
5946
  closeStdin() {
5709
5947
  return this.inner.writeStdin(Buffer.alloc(0), { eof: true });
5710
5948
  }
5949
+ /** Stream stdout and stderr as text. Omit `timeout` for no RPC deadline. */
5711
5950
  follow(opts) {
5712
5951
  return this.inner.follow({
5713
5952
  timeout: timeoutSeconds(opts?.timeout, UNLIMITED),
@@ -5716,6 +5955,7 @@ var ProcessHandle2 = class {
5716
5955
  signal: opts?.signal
5717
5956
  });
5718
5957
  }
5958
+ /** Stream stdout and stderr as bytes. */
5719
5959
  followBytes(opts) {
5720
5960
  return this.inner.follow({
5721
5961
  timeout: timeoutSeconds(opts?.timeout, UNLIMITED),
@@ -5739,9 +5979,9 @@ var publicExports = [
5739
5979
  "DirectoryNotEmptyError",
5740
5980
  "ExecutableNotFoundError",
5741
5981
  "FileExistsError",
5742
- "FileNotFoundError",
5743
5982
  "FileTooLargeError",
5744
5983
  "GuestRuntimeDeadError",
5984
+ "ImageTimeoutError",
5745
5985
  "InvalidArgumentError",
5746
5986
  "InvalidPathError",
5747
5987
  "Mkdir",
@@ -5768,6 +6008,7 @@ var publicExports = [
5768
6008
  "SandboxStatus",
5769
6009
  "SandboxWaitTimeoutError",
5770
6010
  "SandboxTimeoutError",
6011
+ "TimeoutError",
5771
6012
  "UnavailableError",
5772
6013
  "Write",
5773
6014
  "mkdir",
@@ -5787,9 +6028,9 @@ export {
5787
6028
  DirectoryNotEmptyError,
5788
6029
  ExecutableNotFoundError,
5789
6030
  FileExistsError,
5790
- FileNotFoundError,
5791
6031
  FileTooLargeError,
5792
6032
  GuestRuntimeDeadError,
6033
+ ImageTimeoutError,
5793
6034
  InvalidArgumentError,
5794
6035
  InvalidPathError,
5795
6036
  LogStream,
@@ -5815,6 +6056,7 @@ export {
5815
6056
  SandboxStatus,
5816
6057
  SandboxTimeoutError,
5817
6058
  SandboxWaitTimeoutError,
6059
+ TimeoutError,
5818
6060
  UNLIMITED,
5819
6061
  UnavailableError,
5820
6062
  Write,