disk 1.1.0 → 1.1.2

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/README.md CHANGED
@@ -158,7 +158,17 @@ const restricted = await client.sandboxes.create({
158
158
  network: {
159
159
  egress: {
160
160
  default: "deny",
161
- allow: ["github.com", "*.github.com", "140.82.112.0/20"],
161
+ allow: [
162
+ "github.com",
163
+ "*.github.com",
164
+ "140.82.112.0/20",
165
+ {
166
+ target: "api.openai.com",
167
+ transform: {
168
+ headers: { Authorization: `Bearer ${process.env.OPENAI_API_KEY}` },
169
+ },
170
+ },
171
+ ],
162
172
  },
163
173
  },
164
174
  });
@@ -167,8 +177,11 @@ const restricted = await client.sandboxes.create({
167
177
  An egress policy accepts IPv4 addresses, CIDR ranges, exact domains, and `*.`
168
178
  wildcard domains. The `default` action applies when no target matches. `allow`
169
179
  and `deny` can both be specified; deny matches take precedence. Domain matching
170
- applies to HTTPS traffic and a wildcard such as `*.github.com` matches
171
- subdomains, not `github.com` itself. Omit `network` for unrestricted egress. A
180
+ applies to plaintext HTTP and HTTPS traffic, and a wildcard such as
181
+ `*.github.com` matches subdomains, not `github.com` itself. An object-form allow
182
+ rule can transform outbound HTTPS requests to its exact lowercase domain.
183
+ Header transformations overwrite values supplied by the sandbox; matching
184
+ plaintext HTTP requests are rejected. Omit `network` for unrestricted egress. A
172
185
  running sandbox's complete policy can be replaced without restarting it;
173
186
  existing connections are not terminated:
174
187
 
package/dist/cli.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { O as ArchilApiError, a as deleteApiKey, l as listApiKeys, n as createApiKey, r as createDisk, s as getDisk, t as configure, u as listDisks } from "./src-B_Vucedi.mjs";
3
- import { a as renderTable, i as resolveProgramCredentials, n as addProfileCommands, r as isProfileCommand, t as addGlobalOptions } from "./common-CIf8wLtI.mjs";
2
+ import { O as ArchilApiError, a as deleteApiKey, l as listApiKeys, n as createApiKey, r as createDisk, s as getDisk, t as configure, u as listDisks } from "./src-DXNLDPID.mjs";
3
+ import { a as renderTable, i as resolveProgramCredentials, n as addProfileCommands, r as isProfileCommand, t as addGlobalOptions } from "./common-DUyyWu2M.mjs";
4
4
  import { createRequire } from "node:module";
5
5
  import { Command } from "commander";
6
6
  //#region bin/cli.ts
@@ -1,4 +1,4 @@
1
- import { D as REGION_URLS, p as Archil } from "./src-B_Vucedi.mjs";
1
+ import { D as REGION_URLS, p as Archil } from "./src-DXNLDPID.mjs";
2
2
  import { Option } from "commander";
3
3
  import { isCancel, password, spinner } from "@clack/prompts";
4
4
  import { chmod, mkdir, open, readFile, rename, rm, stat } from "node:fs/promises";
package/dist/index.cjs CHANGED
@@ -145,17 +145,54 @@ function deriveS3BaseUrl(controlBaseUrl) {
145
145
  }
146
146
  //#endregion
147
147
  //#region src/version.ts
148
- const VERSION = "1.1.0";
148
+ const VERSION = "1.1.2";
149
149
  const USER_AGENT = `archil-js/${VERSION}`;
150
150
  //#endregion
151
151
  //#region src/client.ts
152
152
  const createClient = typeof openapi_fetch.default === "function" ? openapi_fetch.default : openapi_fetch.default.default;
153
+ function isNodeRuntime() {
154
+ return typeof process !== "undefined" && typeof process.versions?.node === "string";
155
+ }
156
+ const undiciModule = isNodeRuntime() ? import("undici") : void 0;
157
+ const sharedDispatchers = /* @__PURE__ */ new Map();
158
+ function dispatcherKey(baseUrl, apiKey) {
159
+ return `${new URL(baseUrl).origin}\0${apiKey}`;
160
+ }
161
+ function getSharedDispatcher(baseUrl, apiKey) {
162
+ const key = dispatcherKey(baseUrl, apiKey);
163
+ const existing = sharedDispatchers.get(key);
164
+ if (existing) return existing;
165
+ const dispatcher = (async () => {
166
+ if (!undiciModule) throw new Error("The pooled control-plane transport requires Node.js");
167
+ const { Agent } = await undiciModule;
168
+ return new Agent({
169
+ allowH2: true,
170
+ connections: 100,
171
+ keepAliveTimeout: 6e4,
172
+ keepAliveMaxTimeout: 6e5
173
+ });
174
+ })();
175
+ sharedDispatchers.set(key, dispatcher);
176
+ dispatcher.catch(() => {
177
+ if (sharedDispatchers.get(key) === dispatcher) sharedDispatchers.delete(key);
178
+ });
179
+ return dispatcher;
180
+ }
181
+ function createPooledFetch(baseUrl, apiKey) {
182
+ if (!isNodeRuntime()) return void 0;
183
+ return async (request) => {
184
+ const dispatcher = await getSharedDispatcher(baseUrl, apiKey);
185
+ return globalThis.fetch(request, { dispatcher });
186
+ };
187
+ }
153
188
  function createApiClient(opts) {
154
189
  const baseUrl = opts.baseUrl ?? resolveBaseUrl(opts.region);
190
+ const apiKey = `key-${opts.apiKey.replace(/^key-/, "")}`;
155
191
  return createClient({
156
192
  baseUrl,
193
+ fetch: createPooledFetch(baseUrl, apiKey),
157
194
  headers: {
158
- Authorization: `key-${opts.apiKey.replace(/^key-/, "")}`,
195
+ Authorization: apiKey,
159
196
  "User-Agent": USER_AGENT
160
197
  }
161
198
  });
@@ -189,6 +226,68 @@ async function unwrapEmpty(promise) {
189
226
  if (error || !body) throw new ArchilApiError(error?.error ?? `API request failed with status ${response.status}`, response.status);
190
227
  if (!body.success) throw new ArchilApiError(body.error ?? "Unknown API error", response.status);
191
228
  }
229
+ const RETRY_BASE_MS = 100;
230
+ const RETRY_CAP_MS = 2e3;
231
+ const TRANSIENT_STATUSES = /* @__PURE__ */ new Set([
232
+ 429,
233
+ 500,
234
+ 502,
235
+ 503,
236
+ 504
237
+ ]);
238
+ const CONNECT_ERROR_CODES = /* @__PURE__ */ new Set([
239
+ "CERT_HAS_EXPIRED",
240
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
241
+ "EAI_AGAIN",
242
+ "ECONNREFUSED",
243
+ "EHOSTUNREACH",
244
+ "ENETUNREACH",
245
+ "ENOTFOUND",
246
+ "ETIMEDOUT",
247
+ "ERR_TLS_CERT_ALTNAME_INVALID",
248
+ "SELF_SIGNED_CERT_IN_CHAIN",
249
+ "UNABLE_TO_GET_ISSUER_CERT",
250
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
251
+ "UND_ERR_CONNECT_TIMEOUT"
252
+ ]);
253
+ function isTransientStatus(status) {
254
+ return TRANSIENT_STATUSES.has(status);
255
+ }
256
+ function retryDelayMs(attempt) {
257
+ const ceiling = Math.min(RETRY_CAP_MS, RETRY_BASE_MS * 2 ** attempt);
258
+ return Math.random() * ceiling;
259
+ }
260
+ function retrySleep(attempt) {
261
+ return new Promise((resolve) => setTimeout(resolve, retryDelayMs(attempt)));
262
+ }
263
+ function isConnectionEstablishmentError(error) {
264
+ const seen = /* @__PURE__ */ new Set();
265
+ const pending = [error];
266
+ while (pending.length > 0) {
267
+ const current = pending.pop();
268
+ if (!current || seen.has(current)) continue;
269
+ seen.add(current);
270
+ if (typeof current !== "object") continue;
271
+ const value = current;
272
+ const code = typeof value.code === "string" ? value.code : "";
273
+ if (CONNECT_ERROR_CODES.has(code) || code.startsWith("ERR_SSL_") || code.startsWith("ERR_TLS_")) return true;
274
+ if (typeof value.message === "string" && value.message.includes("before secure TLS connection was established")) return true;
275
+ if (value.cause) pending.push(value.cause);
276
+ if (Array.isArray(value.errors)) pending.push(...value.errors);
277
+ }
278
+ return false;
279
+ }
280
+ async function retryApiRequest(request, mode) {
281
+ for (let attempt = 0;; attempt++) {
282
+ try {
283
+ const result = await request();
284
+ if (mode !== "transient" || !isTransientStatus(result.response.status) || attempt >= 3) return result;
285
+ } catch (error) {
286
+ if (!(mode === "transient" || mode === "connect" && isConnectionEstablishmentError(error)) || attempt >= 3) throw error;
287
+ }
288
+ await retrySleep(attempt);
289
+ }
290
+ }
192
291
  //#endregion
193
292
  //#region src/disk.ts
194
293
  var Disk = class {
@@ -717,7 +816,7 @@ var Disk = class {
717
816
  } } : {}
718
817
  };
719
818
  const hasBody = method === "GET" || method === "POST";
720
- const maxRetries = opts.retry === false ? 0 : MAX_S3_RETRIES;
819
+ const maxRetries = opts.retry === false ? 0 : 3;
721
820
  for (let attempt = 0;; attempt++) {
722
821
  let error;
723
822
  let response;
@@ -725,15 +824,15 @@ var Disk = class {
725
824
  ({error, response} = await call(path, init));
726
825
  } catch (transportError) {
727
826
  if (attempt < maxRetries) {
728
- await sleep$1(s3RetryDelayMs(attempt));
827
+ await retrySleep(attempt);
729
828
  continue;
730
829
  }
731
830
  throw transportError;
732
831
  }
733
832
  if (!response.ok) {
734
- if (isTransientS3Status(response.status) && attempt < maxRetries) {
833
+ if (isTransientStatus(response.status) && attempt < maxRetries) {
735
834
  await response.body?.cancel().catch(() => {});
736
- await sleep$1(s3RetryDelayMs(attempt));
835
+ await retrySleep(attempt);
737
836
  continue;
738
837
  }
739
838
  const message = typeof error === "string" ? error : error ? JSON.stringify(error) : "";
@@ -949,28 +1048,6 @@ function posixCreateHeaders(attrs) {
949
1048
  }
950
1049
  /** S3's per-request cap on DeleteObjects keys; larger inputs are batched. */
951
1050
  const MAX_DELETE_OBJECTS_PER_REQUEST = 1e3;
952
- /** Automatic retries for a transient S3 failure (5xx / 429 / network error). */
953
- const MAX_S3_RETRIES = 3;
954
- /** Base backoff for S3 retries (ms); grows exponentially, then full-jittered. */
955
- const S3_RETRY_BASE_MS = 100;
956
- /** Ceiling for a single retry backoff (ms). */
957
- const S3_RETRY_CAP_MS = 2e3;
958
- /**
959
- * Statuses worth retrying: throttling (429) and the gateway's transient 5xx
960
- * (e.g. a journal-commit timeout surfaced as 500). 4xx other than 429 are
961
- * caller errors and never retried.
962
- */
963
- function isTransientS3Status(status) {
964
- return status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
965
- }
966
- /** Full-jittered exponential backoff for retry `attempt` (0-based). */
967
- function s3RetryDelayMs(attempt) {
968
- const ceiling = Math.min(S3_RETRY_CAP_MS, S3_RETRY_BASE_MS * 2 ** attempt);
969
- return Math.random() * ceiling;
970
- }
971
- function sleep$1(ms) {
972
- return new Promise((resolve) => setTimeout(resolve, ms));
973
- }
974
1051
  /** S3's minimum size for every multipart part but the last (5 MiB). */
975
1052
  const MIN_PART_SIZE = 5 * 1024 * 1024;
976
1053
  /** Default part size {@link Disk.putObject} uses on the multipart path (16 MiB). */
@@ -1187,10 +1264,63 @@ var Disks = class {
1187
1264
  authorizedUsers
1188
1265
  };
1189
1266
  }
1267
+ /**
1268
+ * Execute a command on a disk that is already known to exist. Accepts the
1269
+ * disk ID directly so callers that do not need its metadata can execute
1270
+ * without fetching the disk first.
1271
+ */
1272
+ async exec(id, command) {
1273
+ return unwrap(this._client.POST("/api/disks/{id}/exec", {
1274
+ params: { path: { id } },
1275
+ body: { command }
1276
+ }));
1277
+ }
1190
1278
  };
1191
1279
  //#endregion
1192
1280
  //#region src/sandbox-process.ts
1193
1281
  const PROCESS_STDIN_CHUNK_BYTES = 1024 * 1024;
1282
+ async function waitForSocketOpen(socket) {
1283
+ if (socket.readyState === WebSocket.OPEN) return;
1284
+ await new Promise((resolve, reject) => {
1285
+ const cleanup = () => {
1286
+ socket.removeEventListener("open", opened);
1287
+ socket.removeEventListener("error", failed);
1288
+ socket.removeEventListener("close", closed);
1289
+ };
1290
+ const opened = () => {
1291
+ cleanup();
1292
+ resolve();
1293
+ };
1294
+ const failed = () => {
1295
+ cleanup();
1296
+ reject(/* @__PURE__ */ new Error("Process connection failed"));
1297
+ };
1298
+ const closed = () => {
1299
+ cleanup();
1300
+ reject(/* @__PURE__ */ new Error("Process connection closed before opening"));
1301
+ };
1302
+ socket.addEventListener("open", opened, { once: true });
1303
+ socket.addEventListener("error", failed, { once: true });
1304
+ socket.addEventListener("close", closed, { once: true });
1305
+ });
1306
+ }
1307
+ async function openProcessSocket(connectionUrl) {
1308
+ for (let attempt = 0;; attempt++) {
1309
+ const url = await connectionUrl();
1310
+ let socket;
1311
+ try {
1312
+ socket = new WebSocket(url);
1313
+ await waitForSocketOpen(socket);
1314
+ return socket;
1315
+ } catch (error) {
1316
+ try {
1317
+ socket?.close();
1318
+ } catch {}
1319
+ if (attempt >= 3) throw new Error(`Process connection failed after ${attempt + 1} attempts`, { cause: error });
1320
+ }
1321
+ await retrySleep(attempt);
1322
+ }
1323
+ }
1194
1324
  var SandboxProcesses = class {
1195
1325
  _sandboxId;
1196
1326
  _client;
@@ -1225,13 +1355,12 @@ var SandboxProcesses = class {
1225
1355
  return process;
1226
1356
  }
1227
1357
  async _connectionUrl() {
1228
- return (await unwrap(this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this._sandboxId } } }))).url;
1358
+ return (await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this._sandboxId } } }), "transient"))).url;
1229
1359
  }
1230
1360
  async _control(request) {
1231
- const socket = new WebSocket(await this._connectionUrl());
1361
+ const socket = await openProcessSocket(() => this._connectionUrl());
1232
1362
  const expected = request.type === "kill" ? "killed" : "resized";
1233
1363
  await new Promise((resolve, reject) => {
1234
- socket.addEventListener("open", () => socket.send(JSON.stringify(request)), { once: true });
1235
1364
  socket.addEventListener("message", (message) => {
1236
1365
  try {
1237
1366
  const event = JSON.parse(message.data);
@@ -1246,6 +1375,7 @@ var SandboxProcesses = class {
1246
1375
  }, { once: true });
1247
1376
  socket.addEventListener("error", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} request failed`)));
1248
1377
  socket.addEventListener("close", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} connection closed before confirmation`)));
1378
+ socket.send(JSON.stringify(request));
1249
1379
  });
1250
1380
  }
1251
1381
  };
@@ -1335,8 +1465,7 @@ var SandboxProcess = class {
1335
1465
  }
1336
1466
  /** @internal */
1337
1467
  async _connect(request) {
1338
- const url = await this._connectionUrl();
1339
- const socket = new WebSocket(url);
1468
+ const socket = await openProcessSocket(this._connectionUrl);
1340
1469
  socket.binaryType = "arraybuffer";
1341
1470
  this._socket = socket;
1342
1471
  let resolveClosed;
@@ -1373,7 +1502,6 @@ var SandboxProcess = class {
1373
1502
  }
1374
1503
  if (output) this._onOutput?.(output);
1375
1504
  });
1376
- socket.addEventListener("open", () => socket.send(JSON.stringify(request)), { once: true });
1377
1505
  socket.addEventListener("error", () => {
1378
1506
  const error = /* @__PURE__ */ new Error("Process connection failed");
1379
1507
  this._connectionError = error;
@@ -1384,6 +1512,7 @@ var SandboxProcess = class {
1384
1512
  if (!readySettled) rejectReady(/* @__PURE__ */ new Error("Process connection closed before ready"));
1385
1513
  resolveClosed();
1386
1514
  }, { once: true });
1515
+ socket.send(JSON.stringify(request));
1387
1516
  await ready;
1388
1517
  }
1389
1518
  _openSocket() {
@@ -1758,67 +1887,67 @@ var Sandbox = class Sandbox {
1758
1887
  }
1759
1888
  /** Re-fetch this sandbox. */
1760
1889
  async refresh() {
1761
- const data = await unwrap(this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }));
1890
+ const data = await unwrap(retryApiRequest(() => this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }), "transient"));
1762
1891
  return this._apply(data);
1763
1892
  }
1764
1893
  /** Start this sandbox. */
1765
1894
  async start(options = {}) {
1766
- const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/start", { params: {
1895
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/start", { params: {
1767
1896
  path: { sid: this.id },
1768
1897
  query: { wait: options.wait ?? true }
1769
- } }));
1898
+ } }), "transient"));
1770
1899
  this._apply(data);
1771
1900
  return options.wait === false ? this : waitForSandboxStart(this);
1772
1901
  }
1773
1902
  /** Stop this sandbox. */
1774
1903
  async stop(options = {}) {
1775
- const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/stop", { params: { path: { sid: this.id } } }));
1904
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/stop", { params: { path: { sid: this.id } } }), "transient"));
1776
1905
  this._apply(data);
1777
1906
  return options.wait === false ? this : waitWhileSandboxStatus(this, "stopping");
1778
1907
  }
1779
1908
  /** Pause this sandbox, preserving its CPU and memory state. */
1780
1909
  async pause(options = {}) {
1781
- const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/pause", { params: { path: { sid: this.id } } }));
1910
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/pause", { params: { path: { sid: this.id } } }), "transient"));
1782
1911
  this._apply(data);
1783
1912
  return options.wait === false ? this : waitWhileSandboxStatus(this, "pausing");
1784
1913
  }
1785
1914
  /** Resume this sandbox from its preserved CPU and memory state. */
1786
1915
  async resume(options = {}) {
1787
- const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/resume", { params: {
1916
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/resume", { params: {
1788
1917
  path: { sid: this.id },
1789
1918
  query: { wait: options.wait ?? true }
1790
- } }));
1919
+ } }), "transient"));
1791
1920
  this._apply(data);
1792
1921
  return options.wait === false ? this : waitForSandboxStart(this);
1793
1922
  }
1794
1923
  /** Create an isolated writable branch from this sandbox's current state. */
1795
1924
  async fork(options = {}) {
1796
- const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/fork", {
1925
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/fork", {
1797
1926
  params: {
1798
1927
  path: { sid: this.id },
1799
1928
  query: { wait: options.wait ?? true }
1800
1929
  },
1801
1930
  body: options.name === void 0 ? void 0 : { name: options.name }
1802
- }));
1931
+ }), "connect"));
1803
1932
  const fork = new Sandbox(data, this._client);
1804
1933
  return options.wait === false ? fork : waitForSandboxStart(fork);
1805
1934
  }
1806
1935
  /** Get this running sandbox's effective network policy. */
1807
1936
  async getNetwork() {
1808
1937
  const client = this._client;
1809
- return unwrap(client.GET("/api/sandboxes/{sid}/network", { params: { path: { sid: this.id } } }));
1938
+ return unwrap(retryApiRequest(() => client.GET("/api/sandboxes/{sid}/network", { params: { path: { sid: this.id } } }), "transient"));
1810
1939
  }
1811
1940
  /** Replace this running sandbox's complete network policy and return the effective policy. */
1812
1941
  async updateNetwork(network) {
1813
1942
  const client = this._client;
1814
- return unwrap(client.PUT("/api/sandboxes/{sid}/network", {
1943
+ return unwrap(retryApiRequest(() => client.PUT("/api/sandboxes/{sid}/network", {
1815
1944
  params: { path: { sid: this.id } },
1816
1945
  body: network
1817
- }));
1946
+ }), "transient"));
1818
1947
  }
1819
1948
  /** Delete this sandbox and its backing disk. */
1820
1949
  async delete() {
1821
- await unwrapEmpty(this._client.DELETE("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }));
1950
+ await unwrapEmpty(retryApiRequest(() => this._client.DELETE("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }), "transient"));
1822
1951
  }
1823
1952
  };
1824
1953
  /** @internal Continue waiting if the server returned before startup completed. */
@@ -1844,10 +1973,10 @@ var Sandboxes = class {
1844
1973
  /** List the account's sandboxes, oldest first. */
1845
1974
  async list(options = {}) {
1846
1975
  const filesystem = typeof options.disk === "string" ? options.disk : options.disk?.id;
1847
- return ((await unwrap(this._client.GET("/api/sandboxes", { params: { query: { filesystem } } })))?.sandboxes ?? []).map((sandbox) => new Sandbox(sandbox, this._client));
1976
+ return ((await unwrap(retryApiRequest(() => this._client.GET("/api/sandboxes", { params: { query: { filesystem } } }), "transient")))?.sandboxes ?? []).map((sandbox) => new Sandbox(sandbox, this._client));
1848
1977
  }
1849
1978
  async get(id) {
1850
- return new Sandbox(await unwrap(this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: id } } })), this._client);
1979
+ return new Sandbox(await unwrap(retryApiRequest(() => this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: id } } }), "transient")), this._client);
1851
1980
  }
1852
1981
  async create(request = {}, options = {}) {
1853
1982
  const body = {
@@ -1860,10 +1989,10 @@ var Sandboxes = class {
1860
1989
  max_concurrent_execs: request.maxConcurrentExecs,
1861
1990
  network: request.network
1862
1991
  };
1863
- const sandbox = new Sandbox(await unwrap(this._client.POST("/api/sandboxes", {
1992
+ const sandbox = new Sandbox(await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes", {
1864
1993
  params: { query: { wait: options.wait ?? true } },
1865
1994
  body
1866
- })), this._client);
1995
+ }), "connect")), this._client);
1867
1996
  return options.wait === false ? sandbox : waitForSandboxStart(sandbox);
1868
1997
  }
1869
1998
  };
package/dist/index.d.cts CHANGED
@@ -57,6 +57,12 @@ declare class Disks {
57
57
  * Creation-time only.
58
58
  */
59
59
  create(req: CreateDiskRequest): Promise<CreateDiskResult>;
60
+ /**
61
+ * Execute a command on a disk that is already known to exist. Accepts the
62
+ * disk ID directly so callers that do not need its metadata can execute
63
+ * without fetching the disk first.
64
+ */
65
+ exec(id: string, command: string): Promise<ExecResult>;
60
66
  }
61
67
  //#endregion
62
68
  //#region src/sandbox-process.d.ts
@@ -191,6 +197,8 @@ declare class SandboxFiles {
191
197
  //#region src/sandbox.d.ts
192
198
  type SandboxNetworkAction = components["schemas"]["SandboxNetworkAction"];
193
199
  type SandboxEgressPolicy = components["schemas"]["SandboxEgressPolicy"];
200
+ type SandboxEgressRule = components["schemas"]["SandboxEgressRule"];
201
+ type SandboxEgressTransform = components["schemas"]["SandboxEgressTransform"];
194
202
  type SandboxNetwork = components["schemas"]["SandboxNetwork"];
195
203
  /** @internal */
196
204
  type SandboxWire = components["schemas"]["Sandbox"];
@@ -557,4 +565,4 @@ declare function exec(opts: ExecOptions): Promise<ExecDiskResult>;
557
565
  */
558
566
  declare function workspace(mounts: Record<string, ExecMount>): Workspace;
559
567
  //#endregion
560
- export { type ApiTokenResponse, type AppendObjectOptions, Archil, ArchilApiError, ArchilError, type ArchilOptions, ArchilS3Error, type AuthorizedUser, type AwsStsUser, type AzureBlobMount, type CompletedMultipartUpload, type ConnectedClient, type CreateApiTokenRequest, type CreateDiskRequest, type CreateDiskResult, type CreateSandboxRequest, type Delegation, type DeleteObjectsError, type DeleteObjectsOptions, type DeleteObjectsResult, Disk, type DiskListPage, type DiskMetrics, DiskMultipart, type DiskResponse, type DiskStatus, type DiskUser, Disks, type ExecMount, type ExecMountSpec, type ExecOptions, type ExecRequest, type ExecResult, type FileSystem, type GCSMount, type GrepMatch, type GrepOptions, type GrepResult, type GrepStoppedReason, type ListDisksOptions, type ListMultipartUploadsOptions, type ListObjectsOptions, type ListObjectsResult, type ListPartsOptions, type ListSandboxesOptions, type ListTokensOptions, type MountConfig, type MountConfigResponse, type MountOptions, type MountResponse, type MultipartUpload, type MultipartUploadListing, type MultipartUploadSummary, type ObjectMetadata, type PartInfo, type PartListing, type PosixCreateAttrs, type PutObjectOptions, type PutObjectResult, type R2Mount, type RootAttrs, type S3CompatibleMount, type S3Mount, type S3Object, Sandbox, type SandboxEgressPolicy, type SandboxEndpoint, type SandboxFileSource, SandboxFileTransferError, type SandboxFileUploadOptions, type SandboxFileWriter, SandboxFiles, type SandboxForkOptions, type SandboxNetwork, type SandboxNetworkAction, SandboxProcess, type SandboxProcessConnectOptions, type SandboxProcessOutput, type SandboxProcessOutputHandler, type SandboxProcessResult, type SandboxProcessStartOptions, type SandboxProcessStatus, type SandboxProcessStream, SandboxProcesses, type SandboxResponse, type SandboxStatus, type SandboxTerminalOptions, type SandboxWaitOptions, Sandboxes, type ShareUrlOptions, type ShareUrlResult, type TokenUser, Tokens, USER_AGENT, type UploadPart, VERSION, Workspace, configure, createApiKey, createDisk, createSandbox, deleteApiKey, effectiveUploadPartSize, exec, getDisk, getSandbox, listApiKeys, listDisks, listSandboxes, workspace };
568
+ export { type ApiTokenResponse, type AppendObjectOptions, Archil, ArchilApiError, ArchilError, type ArchilOptions, ArchilS3Error, type AuthorizedUser, type AwsStsUser, type AzureBlobMount, type CompletedMultipartUpload, type ConnectedClient, type CreateApiTokenRequest, type CreateDiskRequest, type CreateDiskResult, type CreateSandboxRequest, type Delegation, type DeleteObjectsError, type DeleteObjectsOptions, type DeleteObjectsResult, Disk, type DiskListPage, type DiskMetrics, DiskMultipart, type DiskResponse, type DiskStatus, type DiskUser, Disks, type ExecMount, type ExecMountSpec, type ExecOptions, type ExecRequest, type ExecResult, type FileSystem, type GCSMount, type GrepMatch, type GrepOptions, type GrepResult, type GrepStoppedReason, type ListDisksOptions, type ListMultipartUploadsOptions, type ListObjectsOptions, type ListObjectsResult, type ListPartsOptions, type ListSandboxesOptions, type ListTokensOptions, type MountConfig, type MountConfigResponse, type MountOptions, type MountResponse, type MultipartUpload, type MultipartUploadListing, type MultipartUploadSummary, type ObjectMetadata, type PartInfo, type PartListing, type PosixCreateAttrs, type PutObjectOptions, type PutObjectResult, type R2Mount, type RootAttrs, type S3CompatibleMount, type S3Mount, type S3Object, Sandbox, type SandboxEgressPolicy, type SandboxEgressRule, type SandboxEgressTransform, type SandboxEndpoint, type SandboxFileSource, SandboxFileTransferError, type SandboxFileUploadOptions, type SandboxFileWriter, SandboxFiles, type SandboxForkOptions, type SandboxNetwork, type SandboxNetworkAction, SandboxProcess, type SandboxProcessConnectOptions, type SandboxProcessOutput, type SandboxProcessOutputHandler, type SandboxProcessResult, type SandboxProcessStartOptions, type SandboxProcessStatus, type SandboxProcessStream, SandboxProcesses, type SandboxResponse, type SandboxStatus, type SandboxTerminalOptions, type SandboxWaitOptions, Sandboxes, type ShareUrlOptions, type ShareUrlResult, type TokenUser, Tokens, USER_AGENT, type UploadPart, VERSION, Workspace, configure, createApiKey, createDisk, createSandbox, deleteApiKey, effectiveUploadPartSize, exec, getDisk, getSandbox, listApiKeys, listDisks, listSandboxes, workspace };
package/dist/index.d.mts CHANGED
@@ -57,6 +57,12 @@ declare class Disks {
57
57
  * Creation-time only.
58
58
  */
59
59
  create(req: CreateDiskRequest): Promise<CreateDiskResult>;
60
+ /**
61
+ * Execute a command on a disk that is already known to exist. Accepts the
62
+ * disk ID directly so callers that do not need its metadata can execute
63
+ * without fetching the disk first.
64
+ */
65
+ exec(id: string, command: string): Promise<ExecResult>;
60
66
  }
61
67
  //#endregion
62
68
  //#region src/sandbox-process.d.ts
@@ -191,6 +197,8 @@ declare class SandboxFiles {
191
197
  //#region src/sandbox.d.ts
192
198
  type SandboxNetworkAction = components["schemas"]["SandboxNetworkAction"];
193
199
  type SandboxEgressPolicy = components["schemas"]["SandboxEgressPolicy"];
200
+ type SandboxEgressRule = components["schemas"]["SandboxEgressRule"];
201
+ type SandboxEgressTransform = components["schemas"]["SandboxEgressTransform"];
194
202
  type SandboxNetwork = components["schemas"]["SandboxNetwork"];
195
203
  /** @internal */
196
204
  type SandboxWire = components["schemas"]["Sandbox"];
@@ -557,4 +565,4 @@ declare function exec(opts: ExecOptions): Promise<ExecDiskResult>;
557
565
  */
558
566
  declare function workspace(mounts: Record<string, ExecMount>): Workspace;
559
567
  //#endregion
560
- export { type ApiTokenResponse, type AppendObjectOptions, Archil, ArchilApiError, ArchilError, type ArchilOptions, ArchilS3Error, type AuthorizedUser, type AwsStsUser, type AzureBlobMount, type CompletedMultipartUpload, type ConnectedClient, type CreateApiTokenRequest, type CreateDiskRequest, type CreateDiskResult, type CreateSandboxRequest, type Delegation, type DeleteObjectsError, type DeleteObjectsOptions, type DeleteObjectsResult, Disk, type DiskListPage, type DiskMetrics, DiskMultipart, type DiskResponse, type DiskStatus, type DiskUser, Disks, type ExecMount, type ExecMountSpec, type ExecOptions, type ExecRequest, type ExecResult, type FileSystem, type GCSMount, type GrepMatch, type GrepOptions, type GrepResult, type GrepStoppedReason, type ListDisksOptions, type ListMultipartUploadsOptions, type ListObjectsOptions, type ListObjectsResult, type ListPartsOptions, type ListSandboxesOptions, type ListTokensOptions, type MountConfig, type MountConfigResponse, type MountOptions, type MountResponse, type MultipartUpload, type MultipartUploadListing, type MultipartUploadSummary, type ObjectMetadata, type PartInfo, type PartListing, type PosixCreateAttrs, type PutObjectOptions, type PutObjectResult, type R2Mount, type RootAttrs, type S3CompatibleMount, type S3Mount, type S3Object, Sandbox, type SandboxEgressPolicy, type SandboxEndpoint, type SandboxFileSource, SandboxFileTransferError, type SandboxFileUploadOptions, type SandboxFileWriter, SandboxFiles, type SandboxForkOptions, type SandboxNetwork, type SandboxNetworkAction, SandboxProcess, type SandboxProcessConnectOptions, type SandboxProcessOutput, type SandboxProcessOutputHandler, type SandboxProcessResult, type SandboxProcessStartOptions, type SandboxProcessStatus, type SandboxProcessStream, SandboxProcesses, type SandboxResponse, type SandboxStatus, type SandboxTerminalOptions, type SandboxWaitOptions, Sandboxes, type ShareUrlOptions, type ShareUrlResult, type TokenUser, Tokens, USER_AGENT, type UploadPart, VERSION, Workspace, configure, createApiKey, createDisk, createSandbox, deleteApiKey, effectiveUploadPartSize, exec, getDisk, getSandbox, listApiKeys, listDisks, listSandboxes, workspace };
568
+ export { type ApiTokenResponse, type AppendObjectOptions, Archil, ArchilApiError, ArchilError, type ArchilOptions, ArchilS3Error, type AuthorizedUser, type AwsStsUser, type AzureBlobMount, type CompletedMultipartUpload, type ConnectedClient, type CreateApiTokenRequest, type CreateDiskRequest, type CreateDiskResult, type CreateSandboxRequest, type Delegation, type DeleteObjectsError, type DeleteObjectsOptions, type DeleteObjectsResult, Disk, type DiskListPage, type DiskMetrics, DiskMultipart, type DiskResponse, type DiskStatus, type DiskUser, Disks, type ExecMount, type ExecMountSpec, type ExecOptions, type ExecRequest, type ExecResult, type FileSystem, type GCSMount, type GrepMatch, type GrepOptions, type GrepResult, type GrepStoppedReason, type ListDisksOptions, type ListMultipartUploadsOptions, type ListObjectsOptions, type ListObjectsResult, type ListPartsOptions, type ListSandboxesOptions, type ListTokensOptions, type MountConfig, type MountConfigResponse, type MountOptions, type MountResponse, type MultipartUpload, type MultipartUploadListing, type MultipartUploadSummary, type ObjectMetadata, type PartInfo, type PartListing, type PosixCreateAttrs, type PutObjectOptions, type PutObjectResult, type R2Mount, type RootAttrs, type S3CompatibleMount, type S3Mount, type S3Object, Sandbox, type SandboxEgressPolicy, type SandboxEgressRule, type SandboxEgressTransform, type SandboxEndpoint, type SandboxFileSource, SandboxFileTransferError, type SandboxFileUploadOptions, type SandboxFileWriter, SandboxFiles, type SandboxForkOptions, type SandboxNetwork, type SandboxNetworkAction, SandboxProcess, type SandboxProcessConnectOptions, type SandboxProcessOutput, type SandboxProcessOutputHandler, type SandboxProcessResult, type SandboxProcessStartOptions, type SandboxProcessStatus, type SandboxProcessStream, SandboxProcesses, type SandboxResponse, type SandboxStatus, type SandboxTerminalOptions, type SandboxWaitOptions, Sandboxes, type ShareUrlOptions, type ShareUrlResult, type TokenUser, Tokens, USER_AGENT, type UploadPart, VERSION, Workspace, configure, createApiKey, createDisk, createSandbox, deleteApiKey, effectiveUploadPartSize, exec, getDisk, getSandbox, listApiKeys, listDisks, listSandboxes, workspace };
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { A as ArchilS3Error, C as DiskMultipart, E as VERSION, O as ArchilApiError, S as Disk, T as USER_AGENT, _ as Sandbox, a as deleteApiKey, b as SandboxProcesses, c as getSandbox, d as listSandboxes, f as workspace, g as Sandboxes, h as Tokens, i as createSandbox, j as SandboxFileTransferError, k as ArchilError, l as listApiKeys, m as Workspace, n as createApiKey, o as exec, p as Archil, r as createDisk, s as getDisk, t as configure, u as listDisks, v as SandboxFiles, w as effectiveUploadPartSize, x as Disks, y as SandboxProcess } from "./src-B_Vucedi.mjs";
1
+ import { A as ArchilS3Error, C as DiskMultipart, E as VERSION, O as ArchilApiError, S as Disk, T as USER_AGENT, _ as Sandbox, a as deleteApiKey, b as SandboxProcesses, c as getSandbox, d as listSandboxes, f as workspace, g as Sandboxes, h as Tokens, i as createSandbox, j as SandboxFileTransferError, k as ArchilError, l as listApiKeys, m as Workspace, n as createApiKey, o as exec, p as Archil, r as createDisk, s as getDisk, t as configure, u as listDisks, v as SandboxFiles, w as effectiveUploadPartSize, x as Disks, y as SandboxProcess } from "./src-DXNLDPID.mjs";
2
2
  export { Archil, ArchilApiError, ArchilError, ArchilS3Error, Disk, DiskMultipart, Disks, Sandbox, SandboxFileTransferError, SandboxFiles, SandboxProcess, SandboxProcesses, Sandboxes, Tokens, USER_AGENT, VERSION, Workspace, configure, createApiKey, createDisk, createSandbox, deleteApiKey, effectiveUploadPartSize, exec, getDisk, getSandbox, listApiKeys, listDisks, listSandboxes, workspace };
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { O as ArchilApiError, p as Archil } from "./src-B_Vucedi.mjs";
3
- import { a as renderTable, i as resolveProgramCredentials, n as addProfileCommands, r as isProfileCommand, t as addGlobalOptions } from "./common-CIf8wLtI.mjs";
2
+ import { O as ArchilApiError, p as Archil } from "./src-DXNLDPID.mjs";
3
+ import { a as renderTable, i as resolveProgramCredentials, n as addProfileCommands, r as isProfileCommand, t as addGlobalOptions } from "./common-DUyyWu2M.mjs";
4
4
  import { createRequire } from "node:module";
5
5
  import { Command } from "commander";
6
6
  import { spinner } from "@clack/prompts";
@@ -122,17 +122,54 @@ function deriveS3BaseUrl(controlBaseUrl) {
122
122
  }
123
123
  //#endregion
124
124
  //#region src/version.ts
125
- const VERSION = "1.1.0";
125
+ const VERSION = "1.1.2";
126
126
  const USER_AGENT = `archil-js/${VERSION}`;
127
127
  //#endregion
128
128
  //#region src/client.ts
129
129
  const createClient = typeof createClientDefault === "function" ? createClientDefault : createClientDefault.default;
130
+ function isNodeRuntime() {
131
+ return typeof process !== "undefined" && typeof process.versions?.node === "string";
132
+ }
133
+ const undiciModule = isNodeRuntime() ? import("undici") : void 0;
134
+ const sharedDispatchers = /* @__PURE__ */ new Map();
135
+ function dispatcherKey(baseUrl, apiKey) {
136
+ return `${new URL(baseUrl).origin}\0${apiKey}`;
137
+ }
138
+ function getSharedDispatcher(baseUrl, apiKey) {
139
+ const key = dispatcherKey(baseUrl, apiKey);
140
+ const existing = sharedDispatchers.get(key);
141
+ if (existing) return existing;
142
+ const dispatcher = (async () => {
143
+ if (!undiciModule) throw new Error("The pooled control-plane transport requires Node.js");
144
+ const { Agent } = await undiciModule;
145
+ return new Agent({
146
+ allowH2: true,
147
+ connections: 100,
148
+ keepAliveTimeout: 6e4,
149
+ keepAliveMaxTimeout: 6e5
150
+ });
151
+ })();
152
+ sharedDispatchers.set(key, dispatcher);
153
+ dispatcher.catch(() => {
154
+ if (sharedDispatchers.get(key) === dispatcher) sharedDispatchers.delete(key);
155
+ });
156
+ return dispatcher;
157
+ }
158
+ function createPooledFetch(baseUrl, apiKey) {
159
+ if (!isNodeRuntime()) return void 0;
160
+ return async (request) => {
161
+ const dispatcher = await getSharedDispatcher(baseUrl, apiKey);
162
+ return globalThis.fetch(request, { dispatcher });
163
+ };
164
+ }
130
165
  function createApiClient(opts) {
131
166
  const baseUrl = opts.baseUrl ?? resolveBaseUrl(opts.region);
167
+ const apiKey = `key-${opts.apiKey.replace(/^key-/, "")}`;
132
168
  return createClient({
133
169
  baseUrl,
170
+ fetch: createPooledFetch(baseUrl, apiKey),
134
171
  headers: {
135
- Authorization: `key-${opts.apiKey.replace(/^key-/, "")}`,
172
+ Authorization: apiKey,
136
173
  "User-Agent": USER_AGENT
137
174
  }
138
175
  });
@@ -166,6 +203,68 @@ async function unwrapEmpty(promise) {
166
203
  if (error || !body) throw new ArchilApiError(error?.error ?? `API request failed with status ${response.status}`, response.status);
167
204
  if (!body.success) throw new ArchilApiError(body.error ?? "Unknown API error", response.status);
168
205
  }
206
+ const RETRY_BASE_MS = 100;
207
+ const RETRY_CAP_MS = 2e3;
208
+ const TRANSIENT_STATUSES = /* @__PURE__ */ new Set([
209
+ 429,
210
+ 500,
211
+ 502,
212
+ 503,
213
+ 504
214
+ ]);
215
+ const CONNECT_ERROR_CODES = /* @__PURE__ */ new Set([
216
+ "CERT_HAS_EXPIRED",
217
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
218
+ "EAI_AGAIN",
219
+ "ECONNREFUSED",
220
+ "EHOSTUNREACH",
221
+ "ENETUNREACH",
222
+ "ENOTFOUND",
223
+ "ETIMEDOUT",
224
+ "ERR_TLS_CERT_ALTNAME_INVALID",
225
+ "SELF_SIGNED_CERT_IN_CHAIN",
226
+ "UNABLE_TO_GET_ISSUER_CERT",
227
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
228
+ "UND_ERR_CONNECT_TIMEOUT"
229
+ ]);
230
+ function isTransientStatus(status) {
231
+ return TRANSIENT_STATUSES.has(status);
232
+ }
233
+ function retryDelayMs(attempt) {
234
+ const ceiling = Math.min(RETRY_CAP_MS, RETRY_BASE_MS * 2 ** attempt);
235
+ return Math.random() * ceiling;
236
+ }
237
+ function retrySleep(attempt) {
238
+ return new Promise((resolve) => setTimeout(resolve, retryDelayMs(attempt)));
239
+ }
240
+ function isConnectionEstablishmentError(error) {
241
+ const seen = /* @__PURE__ */ new Set();
242
+ const pending = [error];
243
+ while (pending.length > 0) {
244
+ const current = pending.pop();
245
+ if (!current || seen.has(current)) continue;
246
+ seen.add(current);
247
+ if (typeof current !== "object") continue;
248
+ const value = current;
249
+ const code = typeof value.code === "string" ? value.code : "";
250
+ if (CONNECT_ERROR_CODES.has(code) || code.startsWith("ERR_SSL_") || code.startsWith("ERR_TLS_")) return true;
251
+ if (typeof value.message === "string" && value.message.includes("before secure TLS connection was established")) return true;
252
+ if (value.cause) pending.push(value.cause);
253
+ if (Array.isArray(value.errors)) pending.push(...value.errors);
254
+ }
255
+ return false;
256
+ }
257
+ async function retryApiRequest(request, mode) {
258
+ for (let attempt = 0;; attempt++) {
259
+ try {
260
+ const result = await request();
261
+ if (mode !== "transient" || !isTransientStatus(result.response.status) || attempt >= 3) return result;
262
+ } catch (error) {
263
+ if (!(mode === "transient" || mode === "connect" && isConnectionEstablishmentError(error)) || attempt >= 3) throw error;
264
+ }
265
+ await retrySleep(attempt);
266
+ }
267
+ }
169
268
  //#endregion
170
269
  //#region src/disk.ts
171
270
  var Disk = class {
@@ -694,7 +793,7 @@ var Disk = class {
694
793
  } } : {}
695
794
  };
696
795
  const hasBody = method === "GET" || method === "POST";
697
- const maxRetries = opts.retry === false ? 0 : MAX_S3_RETRIES;
796
+ const maxRetries = opts.retry === false ? 0 : 3;
698
797
  for (let attempt = 0;; attempt++) {
699
798
  let error;
700
799
  let response;
@@ -702,15 +801,15 @@ var Disk = class {
702
801
  ({error, response} = await call(path, init));
703
802
  } catch (transportError) {
704
803
  if (attempt < maxRetries) {
705
- await sleep$1(s3RetryDelayMs(attempt));
804
+ await retrySleep(attempt);
706
805
  continue;
707
806
  }
708
807
  throw transportError;
709
808
  }
710
809
  if (!response.ok) {
711
- if (isTransientS3Status(response.status) && attempt < maxRetries) {
810
+ if (isTransientStatus(response.status) && attempt < maxRetries) {
712
811
  await response.body?.cancel().catch(() => {});
713
- await sleep$1(s3RetryDelayMs(attempt));
812
+ await retrySleep(attempt);
714
813
  continue;
715
814
  }
716
815
  const message = typeof error === "string" ? error : error ? JSON.stringify(error) : "";
@@ -926,28 +1025,6 @@ function posixCreateHeaders(attrs) {
926
1025
  }
927
1026
  /** S3's per-request cap on DeleteObjects keys; larger inputs are batched. */
928
1027
  const MAX_DELETE_OBJECTS_PER_REQUEST = 1e3;
929
- /** Automatic retries for a transient S3 failure (5xx / 429 / network error). */
930
- const MAX_S3_RETRIES = 3;
931
- /** Base backoff for S3 retries (ms); grows exponentially, then full-jittered. */
932
- const S3_RETRY_BASE_MS = 100;
933
- /** Ceiling for a single retry backoff (ms). */
934
- const S3_RETRY_CAP_MS = 2e3;
935
- /**
936
- * Statuses worth retrying: throttling (429) and the gateway's transient 5xx
937
- * (e.g. a journal-commit timeout surfaced as 500). 4xx other than 429 are
938
- * caller errors and never retried.
939
- */
940
- function isTransientS3Status(status) {
941
- return status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
942
- }
943
- /** Full-jittered exponential backoff for retry `attempt` (0-based). */
944
- function s3RetryDelayMs(attempt) {
945
- const ceiling = Math.min(S3_RETRY_CAP_MS, S3_RETRY_BASE_MS * 2 ** attempt);
946
- return Math.random() * ceiling;
947
- }
948
- function sleep$1(ms) {
949
- return new Promise((resolve) => setTimeout(resolve, ms));
950
- }
951
1028
  /** S3's minimum size for every multipart part but the last (5 MiB). */
952
1029
  const MIN_PART_SIZE = 5 * 1024 * 1024;
953
1030
  /** Default part size {@link Disk.putObject} uses on the multipart path (16 MiB). */
@@ -1164,10 +1241,63 @@ var Disks = class {
1164
1241
  authorizedUsers
1165
1242
  };
1166
1243
  }
1244
+ /**
1245
+ * Execute a command on a disk that is already known to exist. Accepts the
1246
+ * disk ID directly so callers that do not need its metadata can execute
1247
+ * without fetching the disk first.
1248
+ */
1249
+ async exec(id, command) {
1250
+ return unwrap(this._client.POST("/api/disks/{id}/exec", {
1251
+ params: { path: { id } },
1252
+ body: { command }
1253
+ }));
1254
+ }
1167
1255
  };
1168
1256
  //#endregion
1169
1257
  //#region src/sandbox-process.ts
1170
1258
  const PROCESS_STDIN_CHUNK_BYTES = 1024 * 1024;
1259
+ async function waitForSocketOpen(socket) {
1260
+ if (socket.readyState === WebSocket.OPEN) return;
1261
+ await new Promise((resolve, reject) => {
1262
+ const cleanup = () => {
1263
+ socket.removeEventListener("open", opened);
1264
+ socket.removeEventListener("error", failed);
1265
+ socket.removeEventListener("close", closed);
1266
+ };
1267
+ const opened = () => {
1268
+ cleanup();
1269
+ resolve();
1270
+ };
1271
+ const failed = () => {
1272
+ cleanup();
1273
+ reject(/* @__PURE__ */ new Error("Process connection failed"));
1274
+ };
1275
+ const closed = () => {
1276
+ cleanup();
1277
+ reject(/* @__PURE__ */ new Error("Process connection closed before opening"));
1278
+ };
1279
+ socket.addEventListener("open", opened, { once: true });
1280
+ socket.addEventListener("error", failed, { once: true });
1281
+ socket.addEventListener("close", closed, { once: true });
1282
+ });
1283
+ }
1284
+ async function openProcessSocket(connectionUrl) {
1285
+ for (let attempt = 0;; attempt++) {
1286
+ const url = await connectionUrl();
1287
+ let socket;
1288
+ try {
1289
+ socket = new WebSocket(url);
1290
+ await waitForSocketOpen(socket);
1291
+ return socket;
1292
+ } catch (error) {
1293
+ try {
1294
+ socket?.close();
1295
+ } catch {}
1296
+ if (attempt >= 3) throw new Error(`Process connection failed after ${attempt + 1} attempts`, { cause: error });
1297
+ }
1298
+ await retrySleep(attempt);
1299
+ }
1300
+ }
1171
1301
  var SandboxProcesses = class {
1172
1302
  _sandboxId;
1173
1303
  _client;
@@ -1202,13 +1332,12 @@ var SandboxProcesses = class {
1202
1332
  return process;
1203
1333
  }
1204
1334
  async _connectionUrl() {
1205
- return (await unwrap(this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this._sandboxId } } }))).url;
1335
+ return (await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this._sandboxId } } }), "transient"))).url;
1206
1336
  }
1207
1337
  async _control(request) {
1208
- const socket = new WebSocket(await this._connectionUrl());
1338
+ const socket = await openProcessSocket(() => this._connectionUrl());
1209
1339
  const expected = request.type === "kill" ? "killed" : "resized";
1210
1340
  await new Promise((resolve, reject) => {
1211
- socket.addEventListener("open", () => socket.send(JSON.stringify(request)), { once: true });
1212
1341
  socket.addEventListener("message", (message) => {
1213
1342
  try {
1214
1343
  const event = JSON.parse(message.data);
@@ -1223,6 +1352,7 @@ var SandboxProcesses = class {
1223
1352
  }, { once: true });
1224
1353
  socket.addEventListener("error", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} request failed`)));
1225
1354
  socket.addEventListener("close", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} connection closed before confirmation`)));
1355
+ socket.send(JSON.stringify(request));
1226
1356
  });
1227
1357
  }
1228
1358
  };
@@ -1312,8 +1442,7 @@ var SandboxProcess = class {
1312
1442
  }
1313
1443
  /** @internal */
1314
1444
  async _connect(request) {
1315
- const url = await this._connectionUrl();
1316
- const socket = new WebSocket(url);
1445
+ const socket = await openProcessSocket(this._connectionUrl);
1317
1446
  socket.binaryType = "arraybuffer";
1318
1447
  this._socket = socket;
1319
1448
  let resolveClosed;
@@ -1350,7 +1479,6 @@ var SandboxProcess = class {
1350
1479
  }
1351
1480
  if (output) this._onOutput?.(output);
1352
1481
  });
1353
- socket.addEventListener("open", () => socket.send(JSON.stringify(request)), { once: true });
1354
1482
  socket.addEventListener("error", () => {
1355
1483
  const error = /* @__PURE__ */ new Error("Process connection failed");
1356
1484
  this._connectionError = error;
@@ -1361,6 +1489,7 @@ var SandboxProcess = class {
1361
1489
  if (!readySettled) rejectReady(/* @__PURE__ */ new Error("Process connection closed before ready"));
1362
1490
  resolveClosed();
1363
1491
  }, { once: true });
1492
+ socket.send(JSON.stringify(request));
1364
1493
  await ready;
1365
1494
  }
1366
1495
  _openSocket() {
@@ -1735,67 +1864,67 @@ var Sandbox = class Sandbox {
1735
1864
  }
1736
1865
  /** Re-fetch this sandbox. */
1737
1866
  async refresh() {
1738
- const data = await unwrap(this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }));
1867
+ const data = await unwrap(retryApiRequest(() => this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }), "transient"));
1739
1868
  return this._apply(data);
1740
1869
  }
1741
1870
  /** Start this sandbox. */
1742
1871
  async start(options = {}) {
1743
- const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/start", { params: {
1872
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/start", { params: {
1744
1873
  path: { sid: this.id },
1745
1874
  query: { wait: options.wait ?? true }
1746
- } }));
1875
+ } }), "transient"));
1747
1876
  this._apply(data);
1748
1877
  return options.wait === false ? this : waitForSandboxStart(this);
1749
1878
  }
1750
1879
  /** Stop this sandbox. */
1751
1880
  async stop(options = {}) {
1752
- const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/stop", { params: { path: { sid: this.id } } }));
1881
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/stop", { params: { path: { sid: this.id } } }), "transient"));
1753
1882
  this._apply(data);
1754
1883
  return options.wait === false ? this : waitWhileSandboxStatus(this, "stopping");
1755
1884
  }
1756
1885
  /** Pause this sandbox, preserving its CPU and memory state. */
1757
1886
  async pause(options = {}) {
1758
- const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/pause", { params: { path: { sid: this.id } } }));
1887
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/pause", { params: { path: { sid: this.id } } }), "transient"));
1759
1888
  this._apply(data);
1760
1889
  return options.wait === false ? this : waitWhileSandboxStatus(this, "pausing");
1761
1890
  }
1762
1891
  /** Resume this sandbox from its preserved CPU and memory state. */
1763
1892
  async resume(options = {}) {
1764
- const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/resume", { params: {
1893
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/resume", { params: {
1765
1894
  path: { sid: this.id },
1766
1895
  query: { wait: options.wait ?? true }
1767
- } }));
1896
+ } }), "transient"));
1768
1897
  this._apply(data);
1769
1898
  return options.wait === false ? this : waitForSandboxStart(this);
1770
1899
  }
1771
1900
  /** Create an isolated writable branch from this sandbox's current state. */
1772
1901
  async fork(options = {}) {
1773
- const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/fork", {
1902
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/fork", {
1774
1903
  params: {
1775
1904
  path: { sid: this.id },
1776
1905
  query: { wait: options.wait ?? true }
1777
1906
  },
1778
1907
  body: options.name === void 0 ? void 0 : { name: options.name }
1779
- }));
1908
+ }), "connect"));
1780
1909
  const fork = new Sandbox(data, this._client);
1781
1910
  return options.wait === false ? fork : waitForSandboxStart(fork);
1782
1911
  }
1783
1912
  /** Get this running sandbox's effective network policy. */
1784
1913
  async getNetwork() {
1785
1914
  const client = this._client;
1786
- return unwrap(client.GET("/api/sandboxes/{sid}/network", { params: { path: { sid: this.id } } }));
1915
+ return unwrap(retryApiRequest(() => client.GET("/api/sandboxes/{sid}/network", { params: { path: { sid: this.id } } }), "transient"));
1787
1916
  }
1788
1917
  /** Replace this running sandbox's complete network policy and return the effective policy. */
1789
1918
  async updateNetwork(network) {
1790
1919
  const client = this._client;
1791
- return unwrap(client.PUT("/api/sandboxes/{sid}/network", {
1920
+ return unwrap(retryApiRequest(() => client.PUT("/api/sandboxes/{sid}/network", {
1792
1921
  params: { path: { sid: this.id } },
1793
1922
  body: network
1794
- }));
1923
+ }), "transient"));
1795
1924
  }
1796
1925
  /** Delete this sandbox and its backing disk. */
1797
1926
  async delete() {
1798
- await unwrapEmpty(this._client.DELETE("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }));
1927
+ await unwrapEmpty(retryApiRequest(() => this._client.DELETE("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }), "transient"));
1799
1928
  }
1800
1929
  };
1801
1930
  /** @internal Continue waiting if the server returned before startup completed. */
@@ -1821,10 +1950,10 @@ var Sandboxes = class {
1821
1950
  /** List the account's sandboxes, oldest first. */
1822
1951
  async list(options = {}) {
1823
1952
  const filesystem = typeof options.disk === "string" ? options.disk : options.disk?.id;
1824
- return ((await unwrap(this._client.GET("/api/sandboxes", { params: { query: { filesystem } } })))?.sandboxes ?? []).map((sandbox) => new Sandbox(sandbox, this._client));
1953
+ return ((await unwrap(retryApiRequest(() => this._client.GET("/api/sandboxes", { params: { query: { filesystem } } }), "transient")))?.sandboxes ?? []).map((sandbox) => new Sandbox(sandbox, this._client));
1825
1954
  }
1826
1955
  async get(id) {
1827
- return new Sandbox(await unwrap(this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: id } } })), this._client);
1956
+ return new Sandbox(await unwrap(retryApiRequest(() => this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: id } } }), "transient")), this._client);
1828
1957
  }
1829
1958
  async create(request = {}, options = {}) {
1830
1959
  const body = {
@@ -1837,10 +1966,10 @@ var Sandboxes = class {
1837
1966
  max_concurrent_execs: request.maxConcurrentExecs,
1838
1967
  network: request.network
1839
1968
  };
1840
- const sandbox = new Sandbox(await unwrap(this._client.POST("/api/sandboxes", {
1969
+ const sandbox = new Sandbox(await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes", {
1841
1970
  params: { query: { wait: options.wait ?? true } },
1842
1971
  body
1843
- })), this._client);
1972
+ }), "connect")), this._client);
1844
1973
  return options.wait === false ? sandbox : waitForSandboxStart(sandbox);
1845
1974
  }
1846
1975
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "disk",
3
- "version": "1.1.0",
3
+ "version": "1.1.2",
4
4
  "description": "Pure-JS client and CLIs for Archil disks and sandboxes",
5
5
  "keywords": [
6
6
  "archil",
@@ -40,11 +40,12 @@
40
40
  "LICENSE"
41
41
  ],
42
42
  "dependencies": {
43
- "@archildata/api-types": "^0.0.23",
43
+ "@archildata/api-types": "^0.0.24",
44
44
  "@clack/prompts": "^1.7.0",
45
45
  "commander": "^14.0.3",
46
46
  "fast-xml-parser": "^5.7.0",
47
47
  "openapi-fetch": "^0.13.5",
48
+ "undici": "7.29.0",
48
49
  "uuid": "^11.1.1",
49
50
  "zod": "^4.4.3"
50
51
  },