@keska/sandbox 0.43.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 +272 -58
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -451,7 +451,11 @@ var ConflictError = class extends SandboxError {
451
451
  };
452
452
  var PermissionDeniedError = class extends SandboxError {
453
453
  };
454
- 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 {
455
459
  };
456
460
  var PageExhaustedError = class extends SandboxError {
457
461
  constructor(message = "no more pages") {
@@ -465,8 +469,6 @@ var CommandFailedError = class extends SandboxError {
465
469
  };
466
470
  var PathNotFoundError = class extends NotFoundError {
467
471
  };
468
- var FileNotFoundError = class extends PathNotFoundError {
469
- };
470
472
  var DirectoryNotEmptyError = class extends ConflictError {
471
473
  };
472
474
  var FileExistsError = class extends SandboxError {
@@ -513,7 +515,7 @@ var ProcessWaitTimeoutError = class extends SandboxTimeoutError {
513
515
  var SandboxWaitTimeoutError = class extends SandboxTimeoutError {
514
516
  };
515
517
  var BY_REASON = {
516
- FILE_NOT_FOUND: FileNotFoundError,
518
+ FILE_NOT_FOUND: PathNotFoundError,
517
519
  DIR_NOT_EMPTY: DirectoryNotEmptyError,
518
520
  FILE_EXISTS: FileExistsError,
519
521
  FILE_TOO_LARGE: FileTooLargeError,
@@ -525,7 +527,13 @@ var BY_REASON = {
525
527
  SANDBOX_SLEEPING: SandboxSleepingError,
526
528
  PATH_INVALID: InvalidPathError,
527
529
  SANDBOX_NOT_FOUND: SandboxNotFoundError,
528
- 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,
529
537
  SANDBOX_NOT_READY: SandboxNotReadyError,
530
538
  SIZE_NOT_PARKED: SandboxNotReadyError,
531
539
  SIZE_NOT_SLEEPING: SandboxNotReadyError,
@@ -537,7 +545,6 @@ var BY_REASON = {
537
545
  GUEST_RUNTIME_DEAD: GuestRuntimeDeadError,
538
546
  CAPACITY: CapacityError,
539
547
  UNAUTHENTICATED: AuthenticationError,
540
- DEADLINE: SandboxTimeoutError,
541
548
  CANCELED: SandboxError,
542
549
  UNAVAILABLE: UnavailableError,
543
550
  INTERNAL: SandboxError
@@ -591,9 +598,61 @@ var INVALID_ARGUMENT_REASONS = /* @__PURE__ */ new Set([
591
598
  "FILE_OP",
592
599
  "CLONE",
593
600
  "SOURCE_CLASS",
594
- "SANDBOX_STATE"
601
+ "STATE_ENUM"
595
602
  ]);
596
- function errorClass(reason) {
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"
641
+ ]);
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
+ }
597
656
  if (BY_REASON[reason]) {
598
657
  return BY_REASON[reason];
599
658
  }
@@ -602,9 +661,27 @@ function errorClass(reason) {
602
661
  }
603
662
  return SandboxError;
604
663
  }
605
- function sandboxError(message, fields) {
606
- const Ctor = errorClass(fields.reason ?? "");
607
- 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);
608
685
  }
609
686
 
610
687
  // ../sdk-shared-ts/src/resource_defaults.ts
@@ -797,28 +874,60 @@ function logRpc(err, procedure = "") {
797
874
  err.requestId ?? ""
798
875
  );
799
876
  }
800
- function rewrite(error, timeoutMs) {
801
- const wrapped = deadlineOr(error, timeoutMs);
877
+ function rewrite(error, timeoutMs, procedure = "") {
878
+ const wrapped = deadlineOr(error, timeoutMs, procedure);
802
879
  return wrapped instanceof SandboxError ? wrapped : error;
803
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
+ }
804
910
  function mapConnectError(error, timeoutMs, procedure = "") {
805
911
  if (error instanceof SandboxError) {
806
- const wrapped2 = rewrite(error, timeoutMs);
912
+ const wrapped2 = rewrite(error, timeoutMs, procedure);
807
913
  logRpc(wrapped2, procedure);
808
914
  return wrapped2;
809
915
  }
810
916
  if (error instanceof ConnectError) {
811
917
  const code = codeName(error.code);
812
918
  const fields = fieldsFromHeaders(error.metadata, code);
813
- const mapped = sandboxError(
919
+ const prepared = deadlineFields(
920
+ fields,
814
921
  withCapacitySentence(code, error.rawMessage || error.message, fields.resource),
815
- fields
922
+ procedure,
923
+ timeoutMs
816
924
  );
817
- const wrapped2 = rewrite(mapped, timeoutMs);
925
+ const mapped = sandboxError(prepared.message, prepared.fields, procedure);
926
+ const wrapped2 = rewrite(mapped, timeoutMs, procedure);
818
927
  logRpc(wrapped2, procedure);
819
928
  return wrapped2;
820
929
  }
821
- const wrapped = deadlineOr(error, timeoutMs);
930
+ const wrapped = deadlineOr(error, timeoutMs, procedure);
822
931
  if (wrapped instanceof SandboxError) {
823
932
  logRpc(wrapped);
824
933
  return wrapped;
@@ -1011,8 +1120,9 @@ var BidiQueue = class {
1011
1120
  }
1012
1121
  }
1013
1122
  };
1014
- function asDeadline(error) {
1015
- return new SandboxError("deadline exceeded", {
1123
+ function asDeadline(error, timeoutMs, procedure = "") {
1124
+ const Ctor = deadlineClass(procedure);
1125
+ return new Ctor(deadlineMessage(procedure, timeoutMs), {
1016
1126
  code: "deadline_exceeded",
1017
1127
  reason: "DEADLINE",
1018
1128
  sandboxId: error.sandboxId,
@@ -1026,29 +1136,34 @@ function asDeadline(error) {
1026
1136
  retryAfterSec: error.retryAfterSec
1027
1137
  });
1028
1138
  }
1029
- function deadlineOr(error, timeoutMs) {
1030
- if (timeoutMs === void 0) {
1031
- return error instanceof Error ? error : new Error(String(error));
1032
- }
1139
+ function deadlineOr(error, timeoutMs, procedure = "") {
1033
1140
  if (error instanceof SandboxError) {
1034
- if (error.code === "canceled") {
1035
- 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);
1036
1143
  }
1037
- if (error.code === "internal" && /without exit/i.test(error.message)) {
1038
- return asDeadline(error);
1144
+ if (error.code === "deadline_exceeded" && bareDeadline(error.message)) {
1145
+ return asDeadline(error, timeoutMs, procedure);
1039
1146
  }
1040
1147
  return error;
1041
1148
  }
1149
+ if (timeoutMs === void 0) {
1150
+ return error instanceof Error ? error : new Error(String(error));
1151
+ }
1042
1152
  if (error instanceof ConnectError && error.code === Code.Canceled) {
1043
- 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
+ );
1044
1158
  }
1045
1159
  const name = error instanceof Error ? error.name : "";
1046
- if (name === "TimeoutError" || name === "AbortError" || name === "DOMException") {
1047
- return new SandboxError("deadline exceeded", { code: "deadline_exceeded", reason: "DEADLINE" });
1048
- }
1049
1160
  const msg = error instanceof Error ? error.message : String(error);
1050
- if (/NGHTTP2_CANCEL|ERR_HTTP2_STREAM|stream closed|session closed/i.test(msg)) {
1051
- 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
+ });
1052
1167
  }
1053
1168
  return error instanceof Error ? error : new Error(msg);
1054
1169
  }
@@ -1317,7 +1432,7 @@ var ForwardSession = class {
1317
1432
  reject(this.err);
1318
1433
  return;
1319
1434
  }
1320
- 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" }));
1321
1436
  }, timeoutMs);
1322
1437
  const onValue = (value) => {
1323
1438
  clearTimeout(timer);
@@ -1744,9 +1859,10 @@ function bytesToB64(value) {
1744
1859
  return Buffer.from(value, "utf8").toString("base64");
1745
1860
  }
1746
1861
  function imageRpcTimeout(timeoutMs, wait, waitSec) {
1747
- if (!wait) return timeoutMs;
1748
- const waitMs = Math.max(waitSec ?? 600, 0) * 1e3;
1749
- 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;
1750
1866
  }
1751
1867
  function modeField(mode) {
1752
1868
  return typeof mode === "number" && mode > 0 ? { mode } : {};
@@ -1930,7 +2046,7 @@ var Session = class {
1930
2046
  labels: params.labels ?? {},
1931
2047
  ...fillCreateResourceDefaults(params)
1932
2048
  },
1933
- params.timeoutMs ?? 18e4,
2049
+ params.timeoutMs === void 0 ? 1e4 : params.timeoutMs === 0 ? void 0 : params.timeoutMs,
1934
2050
  params.signal
1935
2051
  );
1936
2052
  return parseSandbox(body);
@@ -2714,7 +2830,7 @@ var Session = class {
2714
2830
  const registered = await this.call(
2715
2831
  "RegisterImage",
2716
2832
  body,
2717
- imageRpcTimeout(opts.timeoutMs ?? 6e5, wait, opts.waitSec),
2833
+ imageRpcTimeout(opts.timeoutMs, wait, opts.waitSec),
2718
2834
  opts.signal
2719
2835
  );
2720
2836
  return parseImage(registered);
@@ -2742,7 +2858,7 @@ var Session = class {
2742
2858
  try {
2743
2859
  const res = await this.svc.buildImage(chunks(), {
2744
2860
  signal: opts.signal,
2745
- timeoutMs: imageRpcTimeout(opts.timeoutMs ?? 6e5, wait, opts.waitSec),
2861
+ timeoutMs: imageRpcTimeout(opts.timeoutMs, wait, opts.waitSec),
2746
2862
  headers: this.extraHeaders()
2747
2863
  });
2748
2864
  return parseImage({
@@ -2752,7 +2868,7 @@ var Session = class {
2752
2868
  updatedAt: res.updatedAt
2753
2869
  });
2754
2870
  } catch (error) {
2755
- throw mapConnectError(error, opts.timeoutMs ?? 6e5);
2871
+ throw mapConnectError(error, imageRpcTimeout(opts.timeoutMs, wait, opts.waitSec), "BuildImage");
2756
2872
  } finally {
2757
2873
  stopHeartbeat();
2758
2874
  }
@@ -4267,6 +4383,7 @@ var Sandbox = class _Sandbox {
4267
4383
  fromSnapshotId: params.fromSnapshotId ?? "",
4268
4384
  volumeId: params.volumeId ?? "",
4269
4385
  labels: params.labels ?? {},
4386
+ timeoutMs: params.timeoutMs,
4270
4387
  ...fillCreateResourceDefaults(params)
4271
4388
  };
4272
4389
  const info = await wire.createSandbox(create);
@@ -4664,7 +4781,7 @@ var Sandbox = class _Sandbox {
4664
4781
  signal: opts?.signal
4665
4782
  });
4666
4783
  } catch (error) {
4667
- if ((opts?.missingOk ?? true) && error instanceof FileNotFoundError) {
4784
+ if ((opts?.missingOk ?? true) && error instanceof PathNotFoundError) {
4668
4785
  return;
4669
4786
  }
4670
4787
  throw error;
@@ -4736,7 +4853,7 @@ var Sandbox = class _Sandbox {
4736
4853
  try {
4737
4854
  await this.wire.deleteSnapshot(snap.id);
4738
4855
  } catch (error) {
4739
- if (!(error instanceof SandboxNotFoundError)) {
4856
+ if (!(error instanceof NotFoundError)) {
4740
4857
  throw error;
4741
4858
  }
4742
4859
  }
@@ -4774,15 +4891,23 @@ var Sandbox = class _Sandbox {
4774
4891
  // src/surface.ts
4775
4892
  var UNLIMITED = Number.POSITIVE_INFINITY;
4776
4893
  var SandboxStatus = {
4894
+ /** The sandbox is being created. */
4777
4895
  PENDING: "Pending",
4896
+ /** The guest is up and accepts calls. */
4778
4897
  READY: "Ready",
4898
+ /** The VM is stopped and the disk is kept. */
4779
4899
  SLEEPING: "Sleeping",
4900
+ /** The sandbox has exited and will be deleted. */
4780
4901
  FINISHED: "Finished",
4902
+ /** A delete is in progress. */
4781
4903
  DELETING: "Deleting"
4782
4904
  };
4783
4905
  var LogStream = {
4906
+ /** Guest stdout. */
4784
4907
  STDOUT: "stdout",
4908
+ /** Guest stderr. */
4785
4909
  STDERR: "stderr",
4910
+ /** A platform event, not guest output. */
4786
4911
  EVENT: "event"
4787
4912
  };
4788
4913
  var Page = class {
@@ -4794,15 +4919,18 @@ var Page = class {
4794
4919
  items;
4795
4920
  nextPageToken;
4796
4921
  fetchPage;
4922
+ /** True when `next` will fetch another page. */
4797
4923
  get hasMore() {
4798
4924
  return this.nextPageToken != null;
4799
4925
  }
4926
+ /** Fetch the following page. Throws `PageExhaustedError` on the last page. */
4800
4927
  async next() {
4801
4928
  if (this.nextPageToken == null) {
4802
4929
  throw new PageExhaustedError();
4803
4930
  }
4804
4931
  return this.fetchPage(this.nextPageToken);
4805
4932
  }
4933
+ /** Iterate the rows on this page. */
4806
4934
  [Symbol.iterator]() {
4807
4935
  return this.items[Symbol.iterator]();
4808
4936
  }
@@ -4931,6 +5059,8 @@ var SIGNALS = {
4931
5059
  SIGINT: 2,
4932
5060
  SIGQUIT: 3,
4933
5061
  SIGKILL: 9,
5062
+ SIGUSR1: 10,
5063
+ SIGUSR2: 12,
4934
5064
  SIGTERM: 15,
4935
5065
  SIGSTOP: 19
4936
5066
  };
@@ -4949,7 +5079,7 @@ async function missingOk(fn, ok) {
4949
5079
  try {
4950
5080
  await fn();
4951
5081
  } catch (error) {
4952
- if (ok && error instanceof SandboxNotFoundError) {
5082
+ if (ok && error instanceof NotFoundError) {
4953
5083
  return;
4954
5084
  }
4955
5085
  throw error;
@@ -4965,7 +5095,7 @@ async function retry(client, fn, opts) {
4965
5095
  try {
4966
5096
  return await fn();
4967
5097
  } catch (error) {
4968
- if (opts?.delete && attempt > 0 && error instanceof SandboxNotFoundError) {
5098
+ if (opts?.delete && attempt > 0 && error instanceof NotFoundError) {
4969
5099
  return void 0;
4970
5100
  }
4971
5101
  if (!(error instanceof SandboxError) || !error.retryable || attempt + 1 === attempts) {
@@ -4986,12 +5116,15 @@ var Agent = class {
4986
5116
  this.createdAt = info.createdAt;
4987
5117
  }
4988
5118
  client;
5119
+ /** Agent id. */
4989
5120
  id;
5121
+ /** Agent name. */
4990
5122
  name;
4991
5123
  /** Matrix user id to invite from your Matrix client. */
4992
5124
  matrixUserId;
4993
5125
  /** Env name to secret name. Values are not included. */
4994
5126
  secretEnv;
5127
+ /** When the agent was created. */
4995
5128
  createdAt;
4996
5129
  take(info) {
4997
5130
  this.name = info.name;
@@ -5072,15 +5205,23 @@ var Agents2 = class {
5072
5205
  }
5073
5206
  };
5074
5207
  var Client2 = class {
5208
+ /** Retries after the first try. Default 3. `0` is one attempt. */
5075
5209
  maxRetries;
5076
5210
  /** @internal */
5077
5211
  wire;
5212
+ /** Named disks. */
5078
5213
  volumes;
5214
+ /** Project secrets. Values cannot be read back. */
5079
5215
  secrets;
5216
+ /** Matrix agents. */
5080
5217
  agents;
5218
+ /** Platform and project images. */
5081
5219
  images;
5220
+ /** Filesystem snapshots. */
5082
5221
  snapshots;
5222
+ /** Names bound to a policy set. */
5083
5223
  tags;
5224
+ /** Create, list, and open sandboxes. */
5084
5225
  sandboxes;
5085
5226
  constructor(opts = {}) {
5086
5227
  this.maxRetries = opts.maxRetries ?? 3;
@@ -5111,14 +5252,12 @@ var Client2 = class {
5111
5252
  token = void 0;
5112
5253
  }
5113
5254
  }
5114
- const timeout = timeoutSeconds(opts.timeout);
5115
5255
  this.wire = new Client(opts.baseUrl ?? process.env.NUMEN_BASE_URL ?? "", {
5116
5256
  credentialsFile: credentialsFile ? expandHome(credentialsFile) : void 0,
5117
5257
  clientId,
5118
5258
  clientSecret,
5119
5259
  token,
5120
- tokenUrl,
5121
- timeoutMs: timeout == null ? void 0 : timeout === 0 ? void 0 : timeout * 1e3
5260
+ tokenUrl
5122
5261
  });
5123
5262
  this.volumes = new Volumes2(this);
5124
5263
  this.secrets = new Secrets2(this);
@@ -5128,12 +5267,15 @@ var Client2 = class {
5128
5267
  this.tags = new Tags2(this);
5129
5268
  this.sandboxes = new Sandboxes(this);
5130
5269
  }
5270
+ /** Close the connection. */
5131
5271
  close() {
5132
5272
  this.wire.close();
5133
5273
  }
5274
+ /** `using` calls this. */
5134
5275
  [Symbol.dispose]() {
5135
5276
  this.close();
5136
5277
  }
5278
+ /** `await using` calls this. */
5137
5279
  async [Symbol.asyncDispose]() {
5138
5280
  this.close();
5139
5281
  }
@@ -5227,16 +5369,24 @@ var Images2 = class {
5227
5369
  this.client = client;
5228
5370
  }
5229
5371
  client;
5372
+ /** Copy a public image into the project. Omit `timeout` to wait up to 600 seconds. */
5230
5373
  register(name, opts) {
5231
5374
  return this.client.wire.images.register(name, {
5232
5375
  from: opts.source,
5233
- timeout: timeoutSeconds(opts.timeout),
5376
+ ...opts.timeout == null ? {} : { timeout: timeoutSeconds(opts.timeout) },
5234
5377
  waitUntilReady: opts.waitUntilReady,
5235
5378
  waitSec: opts.waitSec
5236
5379
  });
5237
5380
  }
5381
+ /** Build a Dockerfile. Omit `timeout` to wait up to 600 seconds. Pass `timeout` or `waitSec` to replace that. */
5238
5382
  build(name, opts) {
5239
- 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
+ });
5240
5390
  }
5241
5391
  get(name, opts) {
5242
5392
  return retry(this.client, () => this.client.wire.images.get(name, { timeout: timeoutSeconds(opts?.timeout) }));
@@ -5332,7 +5482,7 @@ var Tags2 = class {
5332
5482
  return tag;
5333
5483
  }
5334
5484
  }
5335
- throw new SandboxNotFoundError(`no tag named ${name}`, { reason: "NAME_NOT_FOUND" });
5485
+ throw new NotFoundError(`no tag named ${name}`, { reason: "NAME_NOT_FOUND" });
5336
5486
  }
5337
5487
  async list(opts) {
5338
5488
  const load = async (token) => {
@@ -5389,8 +5539,10 @@ var Sandboxes = class {
5389
5539
  this.client = client;
5390
5540
  }
5391
5541
  client;
5542
+ /** Create a sandbox. Omit `timeout` for a 10 second deadline. */
5392
5543
  async create(opts) {
5393
5544
  const resources = opts.resources ?? {};
5545
+ const seconds = timeoutSeconds(opts.timeout, 10);
5394
5546
  const inner = await Sandbox.create(this.client.wire, {
5395
5547
  image: opts.image,
5396
5548
  name: opts.name,
@@ -5406,7 +5558,8 @@ var Sandboxes = class {
5406
5558
  tags: opts.tags,
5407
5559
  cpuMillicores: resources.cpu == null ? void 0 : cpuMillicores(resources.cpu),
5408
5560
  memoryBytes: resources.memory == null ? void 0 : parseBytes(resources.memory),
5409
- 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
5410
5563
  });
5411
5564
  return new Sandbox2(this.client, inner, opts.deleteOnExit !== false);
5412
5565
  }
@@ -5466,20 +5619,29 @@ var Sandbox2 = class _Sandbox {
5466
5619
  }
5467
5620
  client;
5468
5621
  inner;
5622
+ /** Files on the guest. */
5469
5623
  fs;
5624
+ /** Logs from this sandbox. */
5470
5625
  logs;
5626
+ /** Processes started with `start`. */
5471
5627
  processes;
5628
+ /** Credentials that let a caller reach one guest port. */
5472
5629
  httpGrants;
5630
+ /** When true, disposing the sandbox deletes it. */
5473
5631
  deleteOnExit;
5632
+ /** Last record from create, get, wake, or sleep. */
5474
5633
  get info() {
5475
5634
  return this.inner.info;
5476
5635
  }
5636
+ /** Sandbox id. */
5477
5637
  get id() {
5478
5638
  return this.inner.id;
5479
5639
  }
5640
+ /** Refresh `info`. Does not wake a sleeping sandbox. */
5480
5641
  get() {
5481
5642
  return this.inner.get();
5482
5643
  }
5644
+ /** Wake a sleeping sandbox. Omit `timeout` for no RPC deadline. */
5483
5645
  async wake(opts) {
5484
5646
  const info = await this.inner.open();
5485
5647
  if (opts?.wait === false) {
@@ -5487,6 +5649,7 @@ var Sandbox2 = class _Sandbox {
5487
5649
  }
5488
5650
  return this.inner.wait({ until: [SandboxStatus.READY], timeout: timeoutSeconds(opts?.timeout, UNLIMITED) });
5489
5651
  }
5652
+ /** Stop the VM and keep the disk. Omit `timeout` for no RPC deadline. */
5490
5653
  async sleep(opts) {
5491
5654
  const info = await this.inner.park();
5492
5655
  if (opts?.wait === false) {
@@ -5494,13 +5657,16 @@ var Sandbox2 = class _Sandbox {
5494
5657
  }
5495
5658
  return this.inner.wait({ until: [SandboxStatus.SLEEPING], timeout: timeoutSeconds(opts?.timeout, UNLIMITED) });
5496
5659
  }
5660
+ /** Block until the sandbox is in one of `until`. Omit `timeout` for no RPC deadline. */
5497
5661
  wait(opts) {
5498
5662
  const until = typeof opts.until === "string" ? [opts.until] : [...opts.until];
5499
5663
  return this.inner.wait({ until, timeout: timeoutSeconds(opts.timeout, UNLIMITED) });
5500
5664
  }
5665
+ /** Block until the sandbox is gone. Omit `timeout` for no RPC deadline. */
5501
5666
  waitDeleted(opts) {
5502
5667
  return this.inner.wait({ untilDeleted: true, timeout: timeoutSeconds(opts?.timeout, UNLIMITED) });
5503
5668
  }
5669
+ /** Change size. The sandbox must be sleeping. */
5504
5670
  resize(opts) {
5505
5671
  return this.inner.setSize({
5506
5672
  cpuMillicores: opts.cpu == null ? 0 : cpuMillicores(opts.cpu),
@@ -5508,6 +5674,7 @@ var Sandbox2 = class _Sandbox {
5508
5674
  diskBytes: opts.disk == null ? 0 : parseBytes(opts.disk)
5509
5675
  });
5510
5676
  }
5677
+ /** Replace labels, tags, or both. */
5511
5678
  async update(opts) {
5512
5679
  if (opts.labels) {
5513
5680
  await this.inner.setLabels(opts.labels);
@@ -5517,9 +5684,11 @@ var Sandbox2 = class _Sandbox {
5517
5684
  }
5518
5685
  return this.info;
5519
5686
  }
5687
+ /** Run a command and wait for it. Omit `timeout` for no RPC deadline. */
5520
5688
  run(argv, opts) {
5521
5689
  return this.exec(argv, true, opts);
5522
5690
  }
5691
+ /** `run` with binary stdout and stderr. */
5523
5692
  runBytes(argv, opts) {
5524
5693
  return this.exec(argv, false, opts);
5525
5694
  }
@@ -5547,9 +5716,11 @@ var Sandbox2 = class _Sandbox {
5547
5716
  }
5548
5717
  return result;
5549
5718
  }
5719
+ /** Run one shell string with `/bin/sh -c`. */
5550
5720
  sh(command, opts) {
5551
5721
  return this.run(["/bin/sh", "-c", command], opts);
5552
5722
  }
5723
+ /** Start a command and return its handle. Omit `timeout` for no RPC deadline. */
5553
5724
  async start(argv, opts) {
5554
5725
  const inner = await this.inner.start(argv, {
5555
5726
  env: opts?.env,
@@ -5561,19 +5732,24 @@ var Sandbox2 = class _Sandbox {
5561
5732
  });
5562
5733
  return new ProcessHandle2(this, inner);
5563
5734
  }
5735
+ /** Copy this sandbox's writable layer into new sandboxes. */
5564
5736
  async clone(opts) {
5565
5737
  const children = await this.inner.clone(opts?.count ?? 1, { concurrency: opts?.concurrency ?? 8 });
5566
5738
  return children.map((child) => new _Sandbox(this.client, child, false));
5567
5739
  }
5740
+ /** Freeze the writable layer. Start later sandboxes from the snapshot. */
5568
5741
  snapshot(opts) {
5569
5742
  return this.inner.snapshot(opts);
5570
5743
  }
5744
+ /** Client for a server listening inside the sandbox. */
5571
5745
  http(port, opts) {
5572
5746
  return this.inner.http(port, opts);
5573
5747
  }
5748
+ /** Delete the sandbox. */
5574
5749
  delete() {
5575
5750
  return this.inner.delete();
5576
5751
  }
5752
+ /** Delete when `deleteOnExit` is true. */
5577
5753
  async [Symbol.asyncDispose]() {
5578
5754
  if (this.deleteOnExit) {
5579
5755
  await this.delete();
@@ -5596,15 +5772,25 @@ var Files = class {
5596
5772
  this.sandbox = sandbox;
5597
5773
  }
5598
5774
  sandbox;
5775
+ /** Read a guest file as bytes. Omit `timeout` for 60 seconds. */
5599
5776
  read(path, opts) {
5600
5777
  return this.sandbox.inner.read(path, { timeout: timeoutSeconds(opts?.timeout, 60) });
5601
5778
  }
5779
+ /** Read a guest file as a UTF-8 string. Omit `timeout` for 60 seconds. */
5602
5780
  async readText(path, opts) {
5603
5781
  return (await this.read(path, opts)).toString("utf8");
5604
5782
  }
5783
+ /**
5784
+ * Write one file from memory. Replaces it if it exists.
5785
+ * @param timeout Omit for 60 seconds.
5786
+ */
5605
5787
  write(path, data, opts) {
5606
5788
  return this.sandbox.inner.upload(path, data, { mode: opts?.mode, timeout: timeoutSeconds(opts?.timeout, 60) });
5607
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
+ */
5608
5794
  upload(local, remote, opts) {
5609
5795
  return this.sandbox.inner.upload(remote, {
5610
5796
  local,
@@ -5613,27 +5799,34 @@ var Files = class {
5613
5799
  timeout: timeoutSeconds(opts?.timeout, 60)
5614
5800
  });
5615
5801
  }
5802
+ /** Download a guest path to a local path. Omit `timeout` for 60 seconds. */
5616
5803
  download(remote, local, opts) {
5617
5804
  return this.sandbox.inner.download(remote, local, { timeout: timeoutSeconds(opts?.timeout, 60) });
5618
5805
  }
5806
+ /** List a guest directory. Depth defaults to 1. Omit `timeout` for 60 seconds. */
5619
5807
  list(path, opts) {
5620
5808
  return this.sandbox.inner.ls(path, {
5621
5809
  maxDepth: fileDepth(opts?.depth),
5622
5810
  timeout: timeoutSeconds(opts?.timeout, 60)
5623
5811
  });
5624
5812
  }
5813
+ /** One guest path's type and size. */
5625
5814
  stat(path) {
5626
5815
  return this.sandbox.inner.stat(path);
5627
5816
  }
5817
+ /** Create a guest directory, including missing parents. */
5628
5818
  mkdir(path) {
5629
5819
  return this.sandbox.inner.mkdir(path);
5630
5820
  }
5821
+ /** Remove a guest path. A missing path succeeds unless `missingOk` is false. A non-empty directory needs `recursive`. */
5631
5822
  remove(path, opts) {
5632
- 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 });
5633
5824
  }
5825
+ /** Download a guest directory as a tar file. Omit `timeout` for 60 seconds. */
5634
5826
  export(path, dest, opts) {
5635
5827
  return this.sandbox.inner.exportPath(path, { dest, gzip: opts?.gzip, timeout: timeoutSeconds(opts?.timeout, 60) });
5636
5828
  }
5829
+ /** Apply several file changes in one call. Omit `timeout` for 60 seconds. */
5637
5830
  batch(ops, opts) {
5638
5831
  return this.sandbox.inner.write(
5639
5832
  ops.map((op) => {
@@ -5656,6 +5849,7 @@ var Logs = class {
5656
5849
  }
5657
5850
  sandbox;
5658
5851
  processId;
5852
+ /** One page of logs. Pass `pageToken` from the previous page to continue. */
5659
5853
  async list(opts) {
5660
5854
  const processId = opts?.processId ?? this.processId;
5661
5855
  const load = async (token) => {
@@ -5670,6 +5864,7 @@ var Logs = class {
5670
5864
  };
5671
5865
  return load(opts?.pageToken);
5672
5866
  }
5867
+ /** Yield log entries, following pages until `limit`. */
5673
5868
  iter(opts) {
5674
5869
  return iterate((token) => this.list({ ...opts, pageToken: token }), opts?.limit);
5675
5870
  }
@@ -5679,9 +5874,11 @@ var Processes = class {
5679
5874
  this.sandbox = sandbox;
5680
5875
  }
5681
5876
  sandbox;
5877
+ /** Look up one guest process by id. */
5682
5878
  async get(id) {
5683
5879
  return new ProcessHandle2(this.sandbox, await this.sandbox.inner.process(id));
5684
5880
  }
5881
+ /** Guest processes for this sandbox. */
5685
5882
  async list() {
5686
5883
  const rows = await this.sandbox.inner.processes();
5687
5884
  return rows.map((row) => new ProcessHandle2(this.sandbox, row));
@@ -5692,14 +5889,17 @@ var HTTPGrants = class {
5692
5889
  this.sandbox = sandbox;
5693
5890
  }
5694
5891
  sandbox;
5892
+ /** Mint a grant for a guest port. The token is set only on this call. */
5695
5893
  create(port, opts) {
5696
5894
  return this.sandbox.inner.createHttpGrant(port, { ttlSec: opts?.ttl });
5697
5895
  }
5896
+ /** Grants for this sandbox. Tokens are not included. */
5698
5897
  list() {
5699
5898
  return this.sandbox.inner.listHttpGrants();
5700
5899
  }
5701
- delete(id) {
5702
- 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);
5703
5903
  }
5704
5904
  };
5705
5905
  var ProcessHandle2 = class {
@@ -5708,34 +5908,45 @@ var ProcessHandle2 = class {
5708
5908
  this.logs = new Logs(sandbox, inner.id);
5709
5909
  }
5710
5910
  inner;
5911
+ /** Logs for this process. */
5711
5912
  logs;
5913
+ /** Process id. */
5712
5914
  get id() {
5713
5915
  return this.inner.id;
5714
5916
  }
5917
+ /** Last known status. */
5715
5918
  get status() {
5716
5919
  return this.inner.status;
5717
5920
  }
5921
+ /** Name passed to `start`, or empty. */
5718
5922
  get name() {
5719
5923
  return this.inner.serviceName;
5720
5924
  }
5925
+ /** Exit code once the process has finished. */
5721
5926
  get exitCode() {
5722
5927
  return this.inner.exitCode;
5723
5928
  }
5929
+ /** Refresh status without waiting. */
5724
5930
  poll() {
5725
5931
  return this.inner.poll();
5726
5932
  }
5933
+ /** Block until the process exits. Omit `timeout` for no RPC deadline. */
5727
5934
  wait(opts) {
5728
5935
  return this.inner.wait({ timeout: timeoutSeconds(opts?.timeout, UNLIMITED) });
5729
5936
  }
5937
+ /** Send a signal. The default is `SIGTERM`. */
5730
5938
  kill(signal = "SIGTERM") {
5731
5939
  return this.inner.kill(signalNumber(signal));
5732
5940
  }
5941
+ /** Write to the process stdin. */
5733
5942
  writeStdin(data = Buffer.alloc(0), opts) {
5734
5943
  return this.inner.writeStdin(data, opts);
5735
5944
  }
5945
+ /** Close stdin. */
5736
5946
  closeStdin() {
5737
5947
  return this.inner.writeStdin(Buffer.alloc(0), { eof: true });
5738
5948
  }
5949
+ /** Stream stdout and stderr as text. Omit `timeout` for no RPC deadline. */
5739
5950
  follow(opts) {
5740
5951
  return this.inner.follow({
5741
5952
  timeout: timeoutSeconds(opts?.timeout, UNLIMITED),
@@ -5744,6 +5955,7 @@ var ProcessHandle2 = class {
5744
5955
  signal: opts?.signal
5745
5956
  });
5746
5957
  }
5958
+ /** Stream stdout and stderr as bytes. */
5747
5959
  followBytes(opts) {
5748
5960
  return this.inner.follow({
5749
5961
  timeout: timeoutSeconds(opts?.timeout, UNLIMITED),
@@ -5767,9 +5979,9 @@ var publicExports = [
5767
5979
  "DirectoryNotEmptyError",
5768
5980
  "ExecutableNotFoundError",
5769
5981
  "FileExistsError",
5770
- "FileNotFoundError",
5771
5982
  "FileTooLargeError",
5772
5983
  "GuestRuntimeDeadError",
5984
+ "ImageTimeoutError",
5773
5985
  "InvalidArgumentError",
5774
5986
  "InvalidPathError",
5775
5987
  "Mkdir",
@@ -5796,6 +6008,7 @@ var publicExports = [
5796
6008
  "SandboxStatus",
5797
6009
  "SandboxWaitTimeoutError",
5798
6010
  "SandboxTimeoutError",
6011
+ "TimeoutError",
5799
6012
  "UnavailableError",
5800
6013
  "Write",
5801
6014
  "mkdir",
@@ -5815,9 +6028,9 @@ export {
5815
6028
  DirectoryNotEmptyError,
5816
6029
  ExecutableNotFoundError,
5817
6030
  FileExistsError,
5818
- FileNotFoundError,
5819
6031
  FileTooLargeError,
5820
6032
  GuestRuntimeDeadError,
6033
+ ImageTimeoutError,
5821
6034
  InvalidArgumentError,
5822
6035
  InvalidPathError,
5823
6036
  LogStream,
@@ -5843,6 +6056,7 @@ export {
5843
6056
  SandboxStatus,
5844
6057
  SandboxTimeoutError,
5845
6058
  SandboxWaitTimeoutError,
6059
+ TimeoutError,
5846
6060
  UNLIMITED,
5847
6061
  UnavailableError,
5848
6062
  Write,