disk 1.0.0 → 1.1.1

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
@@ -151,6 +151,49 @@ const all = await client.sandboxes.list();
151
151
  const usingDisk = await client.sandboxes.list({ disk: "dsk-abc123" });
152
152
  ```
153
153
 
154
+ Network egress can optionally be restricted when creating a sandbox:
155
+
156
+ ```ts
157
+ const restricted = await client.sandboxes.create({
158
+ network: {
159
+ egress: {
160
+ default: "deny",
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
+ ],
172
+ },
173
+ },
174
+ });
175
+ ```
176
+
177
+ An egress policy accepts IPv4 addresses, CIDR ranges, exact domains, and `*.`
178
+ wildcard domains. The `default` action applies when no target matches. `allow`
179
+ and `deny` can both be specified; deny matches take precedence. Domain matching
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
185
+ running sandbox's complete policy can be replaced without restarting it;
186
+ existing connections are not terminated:
187
+
188
+ ```ts
189
+ const effective = await restricted.updateNetwork({
190
+ egress: { default: "deny", allow: ["api.github.com"] },
191
+ });
192
+ console.log(effective, await restricted.getNetwork());
193
+
194
+ await restricted.updateNetwork({}); // Restore unrestricted egress.
195
+ ```
196
+
154
197
  Sandboxes support 1–32 vCPUs and 256–65,536 MiB of memory. When omitted,
155
198
  `vcpuCount` defaults to 1 and `memSizeMiB` defaults to 2,048 MiB.
156
199
 
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-Cw7ldF_H.mjs";
3
- import { a as renderTable, i as resolveProgramCredentials, n as addProfileCommands, r as isProfileCommand, t as addGlobalOptions } from "./common-DQ7T-_Xl.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-DHkfjGLy.mjs";
3
+ import { a as renderTable, i as resolveProgramCredentials, n as addProfileCommands, r as isProfileCommand, t as addGlobalOptions } from "./common-CgI3t0XZ.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-Cw7ldF_H.mjs";
1
+ import { D as REGION_URLS, p as Archil } from "./src-DHkfjGLy.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.0.0";
148
+ const VERSION = "1.1.1";
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). */
@@ -1191,6 +1268,48 @@ var Disks = class {
1191
1268
  //#endregion
1192
1269
  //#region src/sandbox-process.ts
1193
1270
  const PROCESS_STDIN_CHUNK_BYTES = 1024 * 1024;
1271
+ async function waitForSocketOpen(socket) {
1272
+ if (socket.readyState === WebSocket.OPEN) return;
1273
+ await new Promise((resolve, reject) => {
1274
+ const cleanup = () => {
1275
+ socket.removeEventListener("open", opened);
1276
+ socket.removeEventListener("error", failed);
1277
+ socket.removeEventListener("close", closed);
1278
+ };
1279
+ const opened = () => {
1280
+ cleanup();
1281
+ resolve();
1282
+ };
1283
+ const failed = () => {
1284
+ cleanup();
1285
+ reject(/* @__PURE__ */ new Error("Process connection failed"));
1286
+ };
1287
+ const closed = () => {
1288
+ cleanup();
1289
+ reject(/* @__PURE__ */ new Error("Process connection closed before opening"));
1290
+ };
1291
+ socket.addEventListener("open", opened, { once: true });
1292
+ socket.addEventListener("error", failed, { once: true });
1293
+ socket.addEventListener("close", closed, { once: true });
1294
+ });
1295
+ }
1296
+ async function openProcessSocket(connectionUrl) {
1297
+ for (let attempt = 0;; attempt++) {
1298
+ const url = await connectionUrl();
1299
+ let socket;
1300
+ try {
1301
+ socket = new WebSocket(url);
1302
+ await waitForSocketOpen(socket);
1303
+ return socket;
1304
+ } catch (error) {
1305
+ try {
1306
+ socket?.close();
1307
+ } catch {}
1308
+ if (attempt >= 3) throw new Error(`Process connection failed after ${attempt + 1} attempts`, { cause: error });
1309
+ }
1310
+ await retrySleep(attempt);
1311
+ }
1312
+ }
1194
1313
  var SandboxProcesses = class {
1195
1314
  _sandboxId;
1196
1315
  _client;
@@ -1225,13 +1344,12 @@ var SandboxProcesses = class {
1225
1344
  return process;
1226
1345
  }
1227
1346
  async _connectionUrl() {
1228
- return (await unwrap(this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this._sandboxId } } }))).url;
1347
+ return (await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this._sandboxId } } }), "transient"))).url;
1229
1348
  }
1230
1349
  async _control(request) {
1231
- const socket = new WebSocket(await this._connectionUrl());
1350
+ const socket = await openProcessSocket(() => this._connectionUrl());
1232
1351
  const expected = request.type === "kill" ? "killed" : "resized";
1233
1352
  await new Promise((resolve, reject) => {
1234
- socket.addEventListener("open", () => socket.send(JSON.stringify(request)), { once: true });
1235
1353
  socket.addEventListener("message", (message) => {
1236
1354
  try {
1237
1355
  const event = JSON.parse(message.data);
@@ -1246,6 +1364,7 @@ var SandboxProcesses = class {
1246
1364
  }, { once: true });
1247
1365
  socket.addEventListener("error", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} request failed`)));
1248
1366
  socket.addEventListener("close", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} connection closed before confirmation`)));
1367
+ socket.send(JSON.stringify(request));
1249
1368
  });
1250
1369
  }
1251
1370
  };
@@ -1335,8 +1454,7 @@ var SandboxProcess = class {
1335
1454
  }
1336
1455
  /** @internal */
1337
1456
  async _connect(request) {
1338
- const url = await this._connectionUrl();
1339
- const socket = new WebSocket(url);
1457
+ const socket = await openProcessSocket(this._connectionUrl);
1340
1458
  socket.binaryType = "arraybuffer";
1341
1459
  this._socket = socket;
1342
1460
  let resolveClosed;
@@ -1373,7 +1491,6 @@ var SandboxProcess = class {
1373
1491
  }
1374
1492
  if (output) this._onOutput?.(output);
1375
1493
  });
1376
- socket.addEventListener("open", () => socket.send(JSON.stringify(request)), { once: true });
1377
1494
  socket.addEventListener("error", () => {
1378
1495
  const error = /* @__PURE__ */ new Error("Process connection failed");
1379
1496
  this._connectionError = error;
@@ -1384,6 +1501,7 @@ var SandboxProcess = class {
1384
1501
  if (!readySettled) rejectReady(/* @__PURE__ */ new Error("Process connection closed before ready"));
1385
1502
  resolveClosed();
1386
1503
  }, { once: true });
1504
+ socket.send(JSON.stringify(request));
1387
1505
  await ready;
1388
1506
  }
1389
1507
  _openSocket() {
@@ -1758,54 +1876,67 @@ var Sandbox = class Sandbox {
1758
1876
  }
1759
1877
  /** Re-fetch this sandbox. */
1760
1878
  async refresh() {
1761
- const data = await unwrap(this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }));
1879
+ const data = await unwrap(retryApiRequest(() => this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }), "transient"));
1762
1880
  return this._apply(data);
1763
1881
  }
1764
1882
  /** Start this sandbox. */
1765
1883
  async start(options = {}) {
1766
- const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/start", { params: {
1884
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/start", { params: {
1767
1885
  path: { sid: this.id },
1768
1886
  query: { wait: options.wait ?? true }
1769
- } }));
1887
+ } }), "transient"));
1770
1888
  this._apply(data);
1771
1889
  return options.wait === false ? this : waitForSandboxStart(this);
1772
1890
  }
1773
1891
  /** Stop this sandbox. */
1774
1892
  async stop(options = {}) {
1775
- const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/stop", { params: { path: { sid: this.id } } }));
1893
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/stop", { params: { path: { sid: this.id } } }), "transient"));
1776
1894
  this._apply(data);
1777
1895
  return options.wait === false ? this : waitWhileSandboxStatus(this, "stopping");
1778
1896
  }
1779
1897
  /** Pause this sandbox, preserving its CPU and memory state. */
1780
1898
  async pause(options = {}) {
1781
- const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/pause", { params: { path: { sid: this.id } } }));
1899
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/pause", { params: { path: { sid: this.id } } }), "transient"));
1782
1900
  this._apply(data);
1783
1901
  return options.wait === false ? this : waitWhileSandboxStatus(this, "pausing");
1784
1902
  }
1785
1903
  /** Resume this sandbox from its preserved CPU and memory state. */
1786
1904
  async resume(options = {}) {
1787
- const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/resume", { params: {
1905
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/resume", { params: {
1788
1906
  path: { sid: this.id },
1789
1907
  query: { wait: options.wait ?? true }
1790
- } }));
1908
+ } }), "transient"));
1791
1909
  this._apply(data);
1792
1910
  return options.wait === false ? this : waitForSandboxStart(this);
1793
1911
  }
1794
1912
  /** Create an isolated writable branch from this sandbox's current state. */
1795
1913
  async fork(options = {}) {
1796
- const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/fork", {
1914
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/fork", {
1797
1915
  params: {
1798
1916
  path: { sid: this.id },
1799
1917
  query: { wait: options.wait ?? true }
1800
1918
  },
1801
1919
  body: options.name === void 0 ? void 0 : { name: options.name }
1802
- }));
1920
+ }), "connect"));
1803
1921
  const fork = new Sandbox(data, this._client);
1804
1922
  return options.wait === false ? fork : waitForSandboxStart(fork);
1805
1923
  }
1924
+ /** Get this running sandbox's effective network policy. */
1925
+ async getNetwork() {
1926
+ const client = this._client;
1927
+ return unwrap(retryApiRequest(() => client.GET("/api/sandboxes/{sid}/network", { params: { path: { sid: this.id } } }), "transient"));
1928
+ }
1929
+ /** Replace this running sandbox's complete network policy and return the effective policy. */
1930
+ async updateNetwork(network) {
1931
+ const client = this._client;
1932
+ return unwrap(retryApiRequest(() => client.PUT("/api/sandboxes/{sid}/network", {
1933
+ params: { path: { sid: this.id } },
1934
+ body: network
1935
+ }), "transient"));
1936
+ }
1806
1937
  /** Delete this sandbox and its backing disk. */
1807
1938
  async delete() {
1808
- await unwrapEmpty(this._client.DELETE("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }));
1939
+ await unwrapEmpty(retryApiRequest(() => this._client.DELETE("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }), "transient"));
1809
1940
  }
1810
1941
  };
1811
1942
  /** @internal Continue waiting if the server returned before startup completed. */
@@ -1831,10 +1962,10 @@ var Sandboxes = class {
1831
1962
  /** List the account's sandboxes, oldest first. */
1832
1963
  async list(options = {}) {
1833
1964
  const filesystem = typeof options.disk === "string" ? options.disk : options.disk?.id;
1834
- return ((await unwrap(this._client.GET("/api/sandboxes", { params: { query: { filesystem } } })))?.sandboxes ?? []).map((sandbox) => new Sandbox(sandbox, this._client));
1965
+ return ((await unwrap(retryApiRequest(() => this._client.GET("/api/sandboxes", { params: { query: { filesystem } } }), "transient")))?.sandboxes ?? []).map((sandbox) => new Sandbox(sandbox, this._client));
1835
1966
  }
1836
1967
  async get(id) {
1837
- return new Sandbox(await unwrap(this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: id } } })), this._client);
1968
+ return new Sandbox(await unwrap(retryApiRequest(() => this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: id } } }), "transient")), this._client);
1838
1969
  }
1839
1970
  async create(request = {}, options = {}) {
1840
1971
  const body = {
@@ -1844,12 +1975,13 @@ var Sandboxes = class {
1844
1975
  base_image: request.baseImage,
1845
1976
  env: request.env,
1846
1977
  max_ttl_seconds: request.maxTtlSeconds,
1847
- max_concurrent_execs: request.maxConcurrentExecs
1978
+ max_concurrent_execs: request.maxConcurrentExecs,
1979
+ network: request.network
1848
1980
  };
1849
- const sandbox = new Sandbox(await unwrap(this._client.POST("/api/sandboxes", {
1981
+ const sandbox = new Sandbox(await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes", {
1850
1982
  params: { query: { wait: options.wait ?? true } },
1851
1983
  body
1852
- })), this._client);
1984
+ }), "connect")), this._client);
1853
1985
  return options.wait === false ? sandbox : waitForSandboxStart(sandbox);
1854
1986
  }
1855
1987
  };
package/dist/index.d.cts CHANGED
@@ -189,6 +189,11 @@ declare class SandboxFiles {
189
189
  }
190
190
  //#endregion
191
191
  //#region src/sandbox.d.ts
192
+ type SandboxNetworkAction = components["schemas"]["SandboxNetworkAction"];
193
+ type SandboxEgressPolicy = components["schemas"]["SandboxEgressPolicy"];
194
+ type SandboxEgressRule = components["schemas"]["SandboxEgressRule"];
195
+ type SandboxEgressTransform = components["schemas"]["SandboxEgressTransform"];
196
+ type SandboxNetwork = components["schemas"]["SandboxNetwork"];
192
197
  /** @internal */
193
198
  type SandboxWire = components["schemas"]["Sandbox"];
194
199
  type SandboxStatus = components["schemas"]["SandboxState"];
@@ -266,6 +271,10 @@ declare class Sandbox {
266
271
  resume(options?: SandboxWaitOptions): Promise<Sandbox | this>;
267
272
  /** Create an isolated writable branch from this sandbox's current state. */
268
273
  fork(options?: SandboxForkOptions): Promise<Sandbox>;
274
+ /** Get this running sandbox's effective network policy. */
275
+ getNetwork(): Promise<SandboxNetwork>;
276
+ /** Replace this running sandbox's complete network policy and return the effective policy. */
277
+ updateNetwork(network: SandboxNetwork): Promise<SandboxNetwork>;
269
278
  /** Delete this sandbox and its backing disk. */
270
279
  delete(): Promise<void>;
271
280
  }
@@ -292,6 +301,8 @@ interface CreateSandboxRequest {
292
301
  maxTtlSeconds?: number;
293
302
  /** Maximum concurrently attached exec sessions. Detached processes and one-shot controls do not count. */
294
303
  maxConcurrentExecs?: number;
304
+ /** Creation-time network policy. Egress is unrestricted when omitted. */
305
+ network?: SandboxNetwork;
295
306
  }
296
307
  interface ListSandboxesOptions {
297
308
  /** Only return sandboxes that mount this disk. */
@@ -548,4 +559,4 @@ declare function exec(opts: ExecOptions): Promise<ExecDiskResult>;
548
559
  */
549
560
  declare function workspace(mounts: Record<string, ExecMount>): Workspace;
550
561
  //#endregion
551
- 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 SandboxEndpoint, type SandboxFileSource, SandboxFileTransferError, type SandboxFileUploadOptions, type SandboxFileWriter, SandboxFiles, type SandboxForkOptions, 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 };
562
+ 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
@@ -189,6 +189,11 @@ declare class SandboxFiles {
189
189
  }
190
190
  //#endregion
191
191
  //#region src/sandbox.d.ts
192
+ type SandboxNetworkAction = components["schemas"]["SandboxNetworkAction"];
193
+ type SandboxEgressPolicy = components["schemas"]["SandboxEgressPolicy"];
194
+ type SandboxEgressRule = components["schemas"]["SandboxEgressRule"];
195
+ type SandboxEgressTransform = components["schemas"]["SandboxEgressTransform"];
196
+ type SandboxNetwork = components["schemas"]["SandboxNetwork"];
192
197
  /** @internal */
193
198
  type SandboxWire = components["schemas"]["Sandbox"];
194
199
  type SandboxStatus = components["schemas"]["SandboxState"];
@@ -266,6 +271,10 @@ declare class Sandbox {
266
271
  resume(options?: SandboxWaitOptions): Promise<Sandbox | this>;
267
272
  /** Create an isolated writable branch from this sandbox's current state. */
268
273
  fork(options?: SandboxForkOptions): Promise<Sandbox>;
274
+ /** Get this running sandbox's effective network policy. */
275
+ getNetwork(): Promise<SandboxNetwork>;
276
+ /** Replace this running sandbox's complete network policy and return the effective policy. */
277
+ updateNetwork(network: SandboxNetwork): Promise<SandboxNetwork>;
269
278
  /** Delete this sandbox and its backing disk. */
270
279
  delete(): Promise<void>;
271
280
  }
@@ -292,6 +301,8 @@ interface CreateSandboxRequest {
292
301
  maxTtlSeconds?: number;
293
302
  /** Maximum concurrently attached exec sessions. Detached processes and one-shot controls do not count. */
294
303
  maxConcurrentExecs?: number;
304
+ /** Creation-time network policy. Egress is unrestricted when omitted. */
305
+ network?: SandboxNetwork;
295
306
  }
296
307
  interface ListSandboxesOptions {
297
308
  /** Only return sandboxes that mount this disk. */
@@ -548,4 +559,4 @@ declare function exec(opts: ExecOptions): Promise<ExecDiskResult>;
548
559
  */
549
560
  declare function workspace(mounts: Record<string, ExecMount>): Workspace;
550
561
  //#endregion
551
- 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 SandboxEndpoint, type SandboxFileSource, SandboxFileTransferError, type SandboxFileUploadOptions, type SandboxFileWriter, SandboxFiles, type SandboxForkOptions, 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 };
562
+ 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-Cw7ldF_H.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-DHkfjGLy.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-Cw7ldF_H.mjs";
3
- import { a as renderTable, i as resolveProgramCredentials, n as addProfileCommands, r as isProfileCommand, t as addGlobalOptions } from "./common-DQ7T-_Xl.mjs";
2
+ import { O as ArchilApiError, p as Archil } from "./src-DHkfjGLy.mjs";
3
+ import { a as renderTable, i as resolveProgramCredentials, n as addProfileCommands, r as isProfileCommand, t as addGlobalOptions } from "./common-CgI3t0XZ.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.0.0";
125
+ const VERSION = "1.1.1";
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). */
@@ -1168,6 +1245,48 @@ var Disks = class {
1168
1245
  //#endregion
1169
1246
  //#region src/sandbox-process.ts
1170
1247
  const PROCESS_STDIN_CHUNK_BYTES = 1024 * 1024;
1248
+ async function waitForSocketOpen(socket) {
1249
+ if (socket.readyState === WebSocket.OPEN) return;
1250
+ await new Promise((resolve, reject) => {
1251
+ const cleanup = () => {
1252
+ socket.removeEventListener("open", opened);
1253
+ socket.removeEventListener("error", failed);
1254
+ socket.removeEventListener("close", closed);
1255
+ };
1256
+ const opened = () => {
1257
+ cleanup();
1258
+ resolve();
1259
+ };
1260
+ const failed = () => {
1261
+ cleanup();
1262
+ reject(/* @__PURE__ */ new Error("Process connection failed"));
1263
+ };
1264
+ const closed = () => {
1265
+ cleanup();
1266
+ reject(/* @__PURE__ */ new Error("Process connection closed before opening"));
1267
+ };
1268
+ socket.addEventListener("open", opened, { once: true });
1269
+ socket.addEventListener("error", failed, { once: true });
1270
+ socket.addEventListener("close", closed, { once: true });
1271
+ });
1272
+ }
1273
+ async function openProcessSocket(connectionUrl) {
1274
+ for (let attempt = 0;; attempt++) {
1275
+ const url = await connectionUrl();
1276
+ let socket;
1277
+ try {
1278
+ socket = new WebSocket(url);
1279
+ await waitForSocketOpen(socket);
1280
+ return socket;
1281
+ } catch (error) {
1282
+ try {
1283
+ socket?.close();
1284
+ } catch {}
1285
+ if (attempt >= 3) throw new Error(`Process connection failed after ${attempt + 1} attempts`, { cause: error });
1286
+ }
1287
+ await retrySleep(attempt);
1288
+ }
1289
+ }
1171
1290
  var SandboxProcesses = class {
1172
1291
  _sandboxId;
1173
1292
  _client;
@@ -1202,13 +1321,12 @@ var SandboxProcesses = class {
1202
1321
  return process;
1203
1322
  }
1204
1323
  async _connectionUrl() {
1205
- return (await unwrap(this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this._sandboxId } } }))).url;
1324
+ return (await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this._sandboxId } } }), "transient"))).url;
1206
1325
  }
1207
1326
  async _control(request) {
1208
- const socket = new WebSocket(await this._connectionUrl());
1327
+ const socket = await openProcessSocket(() => this._connectionUrl());
1209
1328
  const expected = request.type === "kill" ? "killed" : "resized";
1210
1329
  await new Promise((resolve, reject) => {
1211
- socket.addEventListener("open", () => socket.send(JSON.stringify(request)), { once: true });
1212
1330
  socket.addEventListener("message", (message) => {
1213
1331
  try {
1214
1332
  const event = JSON.parse(message.data);
@@ -1223,6 +1341,7 @@ var SandboxProcesses = class {
1223
1341
  }, { once: true });
1224
1342
  socket.addEventListener("error", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} request failed`)));
1225
1343
  socket.addEventListener("close", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} connection closed before confirmation`)));
1344
+ socket.send(JSON.stringify(request));
1226
1345
  });
1227
1346
  }
1228
1347
  };
@@ -1312,8 +1431,7 @@ var SandboxProcess = class {
1312
1431
  }
1313
1432
  /** @internal */
1314
1433
  async _connect(request) {
1315
- const url = await this._connectionUrl();
1316
- const socket = new WebSocket(url);
1434
+ const socket = await openProcessSocket(this._connectionUrl);
1317
1435
  socket.binaryType = "arraybuffer";
1318
1436
  this._socket = socket;
1319
1437
  let resolveClosed;
@@ -1350,7 +1468,6 @@ var SandboxProcess = class {
1350
1468
  }
1351
1469
  if (output) this._onOutput?.(output);
1352
1470
  });
1353
- socket.addEventListener("open", () => socket.send(JSON.stringify(request)), { once: true });
1354
1471
  socket.addEventListener("error", () => {
1355
1472
  const error = /* @__PURE__ */ new Error("Process connection failed");
1356
1473
  this._connectionError = error;
@@ -1361,6 +1478,7 @@ var SandboxProcess = class {
1361
1478
  if (!readySettled) rejectReady(/* @__PURE__ */ new Error("Process connection closed before ready"));
1362
1479
  resolveClosed();
1363
1480
  }, { once: true });
1481
+ socket.send(JSON.stringify(request));
1364
1482
  await ready;
1365
1483
  }
1366
1484
  _openSocket() {
@@ -1735,54 +1853,67 @@ var Sandbox = class Sandbox {
1735
1853
  }
1736
1854
  /** Re-fetch this sandbox. */
1737
1855
  async refresh() {
1738
- const data = await unwrap(this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }));
1856
+ const data = await unwrap(retryApiRequest(() => this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }), "transient"));
1739
1857
  return this._apply(data);
1740
1858
  }
1741
1859
  /** Start this sandbox. */
1742
1860
  async start(options = {}) {
1743
- const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/start", { params: {
1861
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/start", { params: {
1744
1862
  path: { sid: this.id },
1745
1863
  query: { wait: options.wait ?? true }
1746
- } }));
1864
+ } }), "transient"));
1747
1865
  this._apply(data);
1748
1866
  return options.wait === false ? this : waitForSandboxStart(this);
1749
1867
  }
1750
1868
  /** Stop this sandbox. */
1751
1869
  async stop(options = {}) {
1752
- const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/stop", { params: { path: { sid: this.id } } }));
1870
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/stop", { params: { path: { sid: this.id } } }), "transient"));
1753
1871
  this._apply(data);
1754
1872
  return options.wait === false ? this : waitWhileSandboxStatus(this, "stopping");
1755
1873
  }
1756
1874
  /** Pause this sandbox, preserving its CPU and memory state. */
1757
1875
  async pause(options = {}) {
1758
- const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/pause", { params: { path: { sid: this.id } } }));
1876
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/pause", { params: { path: { sid: this.id } } }), "transient"));
1759
1877
  this._apply(data);
1760
1878
  return options.wait === false ? this : waitWhileSandboxStatus(this, "pausing");
1761
1879
  }
1762
1880
  /** Resume this sandbox from its preserved CPU and memory state. */
1763
1881
  async resume(options = {}) {
1764
- const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/resume", { params: {
1882
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/resume", { params: {
1765
1883
  path: { sid: this.id },
1766
1884
  query: { wait: options.wait ?? true }
1767
- } }));
1885
+ } }), "transient"));
1768
1886
  this._apply(data);
1769
1887
  return options.wait === false ? this : waitForSandboxStart(this);
1770
1888
  }
1771
1889
  /** Create an isolated writable branch from this sandbox's current state. */
1772
1890
  async fork(options = {}) {
1773
- const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/fork", {
1891
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/fork", {
1774
1892
  params: {
1775
1893
  path: { sid: this.id },
1776
1894
  query: { wait: options.wait ?? true }
1777
1895
  },
1778
1896
  body: options.name === void 0 ? void 0 : { name: options.name }
1779
- }));
1897
+ }), "connect"));
1780
1898
  const fork = new Sandbox(data, this._client);
1781
1899
  return options.wait === false ? fork : waitForSandboxStart(fork);
1782
1900
  }
1901
+ /** Get this running sandbox's effective network policy. */
1902
+ async getNetwork() {
1903
+ const client = this._client;
1904
+ return unwrap(retryApiRequest(() => client.GET("/api/sandboxes/{sid}/network", { params: { path: { sid: this.id } } }), "transient"));
1905
+ }
1906
+ /** Replace this running sandbox's complete network policy and return the effective policy. */
1907
+ async updateNetwork(network) {
1908
+ const client = this._client;
1909
+ return unwrap(retryApiRequest(() => client.PUT("/api/sandboxes/{sid}/network", {
1910
+ params: { path: { sid: this.id } },
1911
+ body: network
1912
+ }), "transient"));
1913
+ }
1783
1914
  /** Delete this sandbox and its backing disk. */
1784
1915
  async delete() {
1785
- await unwrapEmpty(this._client.DELETE("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }));
1916
+ await unwrapEmpty(retryApiRequest(() => this._client.DELETE("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }), "transient"));
1786
1917
  }
1787
1918
  };
1788
1919
  /** @internal Continue waiting if the server returned before startup completed. */
@@ -1808,10 +1939,10 @@ var Sandboxes = class {
1808
1939
  /** List the account's sandboxes, oldest first. */
1809
1940
  async list(options = {}) {
1810
1941
  const filesystem = typeof options.disk === "string" ? options.disk : options.disk?.id;
1811
- return ((await unwrap(this._client.GET("/api/sandboxes", { params: { query: { filesystem } } })))?.sandboxes ?? []).map((sandbox) => new Sandbox(sandbox, this._client));
1942
+ return ((await unwrap(retryApiRequest(() => this._client.GET("/api/sandboxes", { params: { query: { filesystem } } }), "transient")))?.sandboxes ?? []).map((sandbox) => new Sandbox(sandbox, this._client));
1812
1943
  }
1813
1944
  async get(id) {
1814
- return new Sandbox(await unwrap(this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: id } } })), this._client);
1945
+ return new Sandbox(await unwrap(retryApiRequest(() => this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: id } } }), "transient")), this._client);
1815
1946
  }
1816
1947
  async create(request = {}, options = {}) {
1817
1948
  const body = {
@@ -1821,12 +1952,13 @@ var Sandboxes = class {
1821
1952
  base_image: request.baseImage,
1822
1953
  env: request.env,
1823
1954
  max_ttl_seconds: request.maxTtlSeconds,
1824
- max_concurrent_execs: request.maxConcurrentExecs
1955
+ max_concurrent_execs: request.maxConcurrentExecs,
1956
+ network: request.network
1825
1957
  };
1826
- const sandbox = new Sandbox(await unwrap(this._client.POST("/api/sandboxes", {
1958
+ const sandbox = new Sandbox(await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes", {
1827
1959
  params: { query: { wait: options.wait ?? true } },
1828
1960
  body
1829
- })), this._client);
1961
+ }), "connect")), this._client);
1830
1962
  return options.wait === false ? sandbox : waitForSandboxStart(sandbox);
1831
1963
  }
1832
1964
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "disk",
3
- "version": "1.0.0",
3
+ "version": "1.1.1",
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.18",
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
  },