disk 1.6.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -47,6 +47,16 @@ var SandboxPauseError = class extends ArchilError {
47
47
  this.name = "SandboxPauseError";
48
48
  }
49
49
  };
50
+ var ImageBuildError = class extends ArchilError {
51
+ latest;
52
+ reason;
53
+ constructor(latest) {
54
+ super(`Image ${latest.imageId} build failed: ${latest.failureReason}`, 409, "IMAGE_BUILD_FAILED");
55
+ this.latest = latest;
56
+ this.name = "ImageBuildError";
57
+ this.reason = latest.failureReason;
58
+ }
59
+ };
50
60
  var SandboxFileTransferError = class extends ArchilError {
51
61
  operation;
52
62
  path;
@@ -130,7 +140,7 @@ function deriveS3BaseUrl(controlBaseUrl) {
130
140
  }
131
141
  //#endregion
132
142
  //#region src/version.ts
133
- const VERSION = "1.6.0";
143
+ const VERSION = "1.8.0";
134
144
  const USER_AGENT = `archil-js/${VERSION}`;
135
145
  //#endregion
136
146
  //#region src/client.ts
@@ -239,8 +249,11 @@ async function unwrap(promise) {
239
249
  */
240
250
  async function unwrapPage(promise) {
241
251
  const { data: body, error, response } = await promise;
242
- if (error || !body) throw new ArchilApiError(error?.error ?? `API request failed with status ${response.status}`, response.status);
243
- if (!body.success) throw new ArchilApiError(body.error ?? "Unknown API error", response.status);
252
+ if (error || !body) {
253
+ const errBody = error;
254
+ throw new ArchilApiError(errBody?.error ?? `API request failed with status ${response.status}`, response.status, errBody?.code);
255
+ }
256
+ if (!body.success) throw new ArchilApiError(body.error ?? "Unknown API error", response.status, body.code);
244
257
  return {
245
258
  data: body.data,
246
259
  nextCursor: body.nextCursor
@@ -252,8 +265,11 @@ async function unwrapPage(promise) {
252
265
  async function unwrapEmpty(promise) {
253
266
  const { data: body, error, response } = await promise;
254
267
  if (!error && response.status === 204) return;
255
- if (error || !body) throw new ArchilApiError(error?.error ?? `API request failed with status ${response.status}`, response.status);
256
- if (!body.success) throw new ArchilApiError(body.error ?? "Unknown API error", response.status);
268
+ if (error || !body) {
269
+ const errBody = error;
270
+ throw new ArchilApiError(errBody?.error ?? `API request failed with status ${response.status}`, response.status, errBody?.code);
271
+ }
272
+ if (!body.success) throw new ArchilApiError(body.error ?? "Unknown API error", response.status, body.code);
257
273
  }
258
274
  const RETRY_BASE_MS = 100;
259
275
  const RETRY_CAP_MS = 2e3;
@@ -1306,6 +1322,77 @@ var Disks = class {
1306
1322
  }
1307
1323
  };
1308
1324
  //#endregion
1325
+ //#region src/images.ts
1326
+ const DEFAULT_BUILD_TIMEOUT_SECONDS = 1800;
1327
+ const MAX_INTERRUPTED_RETRIES = 3;
1328
+ const REQUEST_AGAIN_MS = 2 * 6e4;
1329
+ const FIRST_POLL_MS = 1e3;
1330
+ const MAX_POLL_MS = 5e3;
1331
+ function imageFromWire(data) {
1332
+ return {
1333
+ imageId: data.image_id,
1334
+ source: data.source,
1335
+ private: data.private,
1336
+ status: data.status,
1337
+ digest: data.digest,
1338
+ canonicalSource: data.canonical_source,
1339
+ failureReason: data.failure_reason,
1340
+ createdAt: new Date(data.created_at),
1341
+ updatedAt: new Date(data.updated_at)
1342
+ };
1343
+ }
1344
+ var Images = class {
1345
+ /** @internal */
1346
+ _client;
1347
+ /** @internal */
1348
+ constructor(client) {
1349
+ this._client = client;
1350
+ }
1351
+ async get(imageId) {
1352
+ return imageFromWire(await unwrap(retryApiRequest(() => this._client.GET("/api/images/{image_id}", { params: { path: { image_id: imageId } } }), "transient")));
1353
+ }
1354
+ /**
1355
+ * Build a sandbox image from an OCI reference and wait until it is ready.
1356
+ * Returns at once when the image is already built from a digest reference
1357
+ * and joins a build that is already running. A tag is rebuilt on each call
1358
+ * in case it moved, so call this once and reuse `imageId`. Interrupted
1359
+ * builds are requested again up to three times; other failures throw
1360
+ * {@link ImageBuildError}.
1361
+ */
1362
+ async build(request, options = {}) {
1363
+ const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_BUILD_TIMEOUT_SECONDS;
1364
+ const deadline = Date.now() + timeoutSeconds * 1e3;
1365
+ let image = await this._request(request);
1366
+ let lastRequest = Date.now();
1367
+ let retries = 0;
1368
+ let pollMs = FIRST_POLL_MS;
1369
+ for (;;) {
1370
+ if (image.status === "ready") return image;
1371
+ if (image.status === "failed") {
1372
+ if (image.failureReason !== "interrupted" || retries >= MAX_INTERRUPTED_RETRIES) throw new ImageBuildError(image);
1373
+ retries++;
1374
+ image = await this._request(request);
1375
+ lastRequest = Date.now();
1376
+ continue;
1377
+ }
1378
+ if (Date.now() >= deadline) throw new ArchilError(`Image ${image.imageId} was not ready after ${timeoutSeconds} seconds`, 408, "IMAGE_BUILD_TIMEOUT");
1379
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
1380
+ pollMs = Math.min(pollMs * 2, MAX_POLL_MS);
1381
+ image = await this.get(image.imageId);
1382
+ if (image.status === "building" && Date.now() - lastRequest >= REQUEST_AGAIN_MS) {
1383
+ image = await this._request(request);
1384
+ lastRequest = Date.now();
1385
+ }
1386
+ }
1387
+ }
1388
+ async _request(request) {
1389
+ return imageFromWire(await unwrap(retryApiRequest(() => this._client.POST("/api/images", { body: {
1390
+ source: request.source,
1391
+ registry_auth: request.registryAuth
1392
+ } }), "transient")));
1393
+ }
1394
+ };
1395
+ //#endregion
1309
1396
  //#region src/sandbox-process.ts
1310
1397
  const PROCESS_STDIN_CHUNK_BYTES = 1024 * 1024;
1311
1398
  async function waitForSocketOpen(socket) {
@@ -1350,62 +1437,20 @@ async function openProcessSocket(connectionUrl) {
1350
1437
  await retrySleep(attempt);
1351
1438
  }
1352
1439
  }
1440
+ /** @deprecated Use Sandbox.run() and Sandbox.attach(). Removed in the next version. */
1353
1441
  var SandboxProcesses = class {
1354
- _sandboxId;
1355
- _client;
1442
+ _sandbox;
1356
1443
  /** @internal */
1357
- constructor(sandboxId, client) {
1358
- this._sandboxId = sandboxId;
1359
- this._client = client;
1444
+ constructor(_sandbox) {
1445
+ this._sandbox = _sandbox;
1360
1446
  }
1361
- async start(command, options = {}) {
1362
- const process = new SandboxProcess("", 0, options.onOutput, options.collectOutput ?? true, () => this._connectionUrl(), (request) => this._control(request));
1363
- const terminal = typeof options.terminal === "object" ? {
1364
- cols: options.terminal.cols ?? 80,
1365
- rows: options.terminal.rows ?? 24
1366
- } : options.terminal;
1367
- await process._connect({
1368
- type: "start",
1369
- command,
1370
- terminal,
1371
- env: options.env ?? {},
1372
- timeout_seconds: options.timeoutSeconds
1373
- });
1374
- return process;
1375
- }
1376
- async connect(processId, options = {}) {
1377
- const offset = options.offset ?? 0;
1378
- const process = new SandboxProcess(processId, offset, options.onOutput, options.collectOutput ?? true, () => this._connectionUrl(), (request) => this._control(request));
1379
- await process._connect({
1380
- type: "attach",
1381
- process_id: processId,
1382
- offset
1383
- });
1384
- return process;
1385
- }
1386
- async _connectionUrl() {
1387
- return (await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this._sandboxId } } }), "transient"))).url;
1447
+ /** @deprecated Use sandbox.run(). Removed in the next version. */
1448
+ start(command, options = {}) {
1449
+ return this._sandbox.run(command, options);
1388
1450
  }
1389
- async _control(request) {
1390
- const socket = await openProcessSocket(() => this._connectionUrl());
1391
- const expected = request.type === "kill" ? "killed" : "resized";
1392
- await new Promise((resolve, reject) => {
1393
- socket.addEventListener("message", (message) => {
1394
- try {
1395
- const event = JSON.parse(message.data);
1396
- if (event.type === "error") reject(/* @__PURE__ */ new Error(`${event.error}: ${event.message}`));
1397
- else if (event.type !== expected) reject(/* @__PURE__ */ new Error(`Expected ${expected}, received ${event.type}`));
1398
- else resolve();
1399
- } catch (error) {
1400
- reject(error);
1401
- } finally {
1402
- socket.close();
1403
- }
1404
- }, { once: true });
1405
- socket.addEventListener("error", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} request failed`)));
1406
- socket.addEventListener("close", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} connection closed before confirmation`)));
1407
- socket.send(JSON.stringify(request));
1408
- });
1451
+ /** @deprecated Use sandbox.attach(). Removed in the next version. */
1452
+ connect(processId, options = {}) {
1453
+ return this._sandbox.attach(processId, options);
1409
1454
  }
1410
1455
  };
1411
1456
  var SandboxProcess = class {
@@ -1715,10 +1760,10 @@ var ProcessOutputReader = class {
1715
1760
  }
1716
1761
  };
1717
1762
  var SandboxFiles = class {
1718
- _processes;
1763
+ _sandbox;
1719
1764
  /** @internal */
1720
- constructor(processes) {
1721
- this._processes = processes;
1765
+ constructor(sandbox) {
1766
+ this._sandbox = sandbox;
1722
1767
  }
1723
1768
  async uploadFile(source, remotePath, options = {}) {
1724
1769
  const { path, parent } = remoteFilePath(remotePath);
@@ -1726,7 +1771,7 @@ var SandboxFiles = class {
1726
1771
  if (!Number.isInteger(mode) || mode < 0 || mode > 4095) throw new RangeError("mode must be between 0 and 0o7777");
1727
1772
  let process;
1728
1773
  try {
1729
- process = await this._processes.start(UPLOAD_COMMAND, { env: {
1774
+ process = await this._sandbox.run(UPLOAD_COMMAND, { env: {
1730
1775
  ARCHIL_FILE_PARENT: parent,
1731
1776
  ARCHIL_FILE_TARGET: path,
1732
1777
  ARCHIL_FILE_TEMP: `${parent}/.archil-upload-${transferId()}`,
@@ -1748,7 +1793,7 @@ var SandboxFiles = class {
1748
1793
  const reader = new ProcessOutputReader();
1749
1794
  let process;
1750
1795
  try {
1751
- process = await this._processes.start(DOWNLOAD_COMMAND, {
1796
+ process = await this._sandbox.run(DOWNLOAD_COMMAND, {
1752
1797
  env: {
1753
1798
  ARCHIL_FILE_PATH: path,
1754
1799
  ARCHIL_FILE_TEMP: `/tmp/.archil-download-${transferId()}`
@@ -1838,6 +1883,29 @@ function toError(error) {
1838
1883
  }
1839
1884
  //#endregion
1840
1885
  //#region src/sandbox.ts
1886
+ /** @internal */
1887
+ function sandboxMountWire(mount) {
1888
+ const entry = {
1889
+ disk_id: typeof mount.disk === "string" ? mount.disk : mount.disk.id,
1890
+ read_only: mount.readOnly ?? false,
1891
+ conditional: mount.conditional ?? false
1892
+ };
1893
+ if (mount.path !== void 0) entry.path = mount.path;
1894
+ if (mount.subdirectory !== void 0) entry.subdirectory = mount.subdirectory;
1895
+ if (mount.queueMs !== void 0) entry.queue_ms = mount.queueMs;
1896
+ return entry;
1897
+ }
1898
+ function sandboxMountFromWire(mount) {
1899
+ const out = {
1900
+ diskId: mount.disk_id,
1901
+ path: mount.path,
1902
+ readOnly: mount.read_only ?? false,
1903
+ conditional: mount.conditional ?? false
1904
+ };
1905
+ if (mount.subdirectory !== void 0) out.subdirectory = mount.subdirectory;
1906
+ if (mount.queue_ms !== void 0) out.queueMs = mount.queue_ms;
1907
+ return out;
1908
+ }
1841
1909
  function portTokenFromWire(data) {
1842
1910
  return {
1843
1911
  id: data.id,
@@ -1857,17 +1925,20 @@ var Sandbox = class Sandbox {
1857
1925
  vcpuCount;
1858
1926
  memSizeMiB;
1859
1927
  baseImage;
1928
+ imageDigest;
1860
1929
  platform;
1861
1930
  maxTtlSeconds;
1862
1931
  idleTtlSeconds;
1863
1932
  maxConcurrentExecs;
1864
1933
  endpoints;
1934
+ mounts;
1865
1935
  createdAt;
1866
1936
  runningAt;
1867
1937
  finishedAt;
1868
1938
  lastActiveAt;
1869
1939
  exitReason;
1870
1940
  checkpoint;
1941
+ /** @deprecated Use run() and attach(). Removed in the next version. */
1871
1942
  processes;
1872
1943
  files;
1873
1944
  /** @internal */
@@ -1876,8 +1947,8 @@ var Sandbox = class Sandbox {
1876
1947
  constructor(data, client) {
1877
1948
  this._client = client;
1878
1949
  this._apply(data);
1879
- this.processes = new SandboxProcesses(this.id, client);
1880
- this.files = new SandboxFiles(this.processes);
1950
+ this.processes = new SandboxProcesses(this);
1951
+ this.files = new SandboxFiles(this);
1881
1952
  }
1882
1953
  /** @internal Overwrite this sandbox's fields in place from a fresh wire snapshot. */
1883
1954
  _apply(data) {
@@ -1887,11 +1958,13 @@ var Sandbox = class Sandbox {
1887
1958
  this.vcpuCount = data.vcpu_count;
1888
1959
  this.memSizeMiB = data.mem_size_mib;
1889
1960
  this.baseImage = data.base_image;
1961
+ this.imageDigest = data.image_digest ?? "";
1890
1962
  this.platform = data.platform;
1891
1963
  this.maxTtlSeconds = data.max_ttl_seconds;
1892
1964
  this.idleTtlSeconds = data.idle_ttl_seconds ?? 0;
1893
1965
  this.maxConcurrentExecs = data.max_concurrent_execs;
1894
1966
  this.endpoints = data.endpoints?.map((endpoint) => ({ ...endpoint }));
1967
+ this.mounts = (data.mounts ?? []).map(sandboxMountFromWire);
1895
1968
  this.createdAt = new Date(data.created_at);
1896
1969
  this.runningAt = data.running_at ? new Date(data.running_at) : void 0;
1897
1970
  this.finishedAt = data.finished_at ? new Date(data.finished_at) : void 0;
@@ -1908,11 +1981,13 @@ var Sandbox = class Sandbox {
1908
1981
  vcpuCount: this.vcpuCount,
1909
1982
  memSizeMiB: this.memSizeMiB,
1910
1983
  baseImage: this.baseImage,
1984
+ imageDigest: this.imageDigest,
1911
1985
  platform: this.platform,
1912
1986
  maxTtlSeconds: this.maxTtlSeconds,
1913
1987
  idleTtlSeconds: this.idleTtlSeconds,
1914
1988
  maxConcurrentExecs: this.maxConcurrentExecs,
1915
1989
  endpoints: this.endpoints?.map((endpoint) => ({ ...endpoint })),
1990
+ mounts: this.mounts.map((mount) => ({ ...mount })),
1916
1991
  createdAt: this.createdAt,
1917
1992
  runningAt: this.runningAt,
1918
1993
  finishedAt: this.finishedAt,
@@ -1921,9 +1996,61 @@ var Sandbox = class Sandbox {
1921
1996
  checkpoint: this.checkpoint
1922
1997
  };
1923
1998
  }
1999
+ /** Start a process and return its handle without waiting for exit. */
2000
+ async run(command, options = {}) {
2001
+ const process = new SandboxProcess("", 0, options.onOutput, options.collectOutput ?? true, () => this._connectionUrl(), (request) => this._control(request));
2002
+ const terminal = typeof options.terminal === "object" ? {
2003
+ cols: options.terminal.cols ?? 80,
2004
+ rows: options.terminal.rows ?? 24
2005
+ } : options.terminal;
2006
+ await process._connect({
2007
+ type: "start",
2008
+ command,
2009
+ cwd: options.cwd,
2010
+ terminal,
2011
+ env: options.env ?? {},
2012
+ timeout_seconds: options.timeoutSeconds
2013
+ });
2014
+ return process;
2015
+ }
2016
+ /** Reattach to a process, optionally resuming output from a cursor. */
2017
+ async attach(processId, options = {}) {
2018
+ const offset = options.offset ?? 0;
2019
+ const process = new SandboxProcess(processId, offset, options.onOutput, options.collectOutput ?? true, () => this._connectionUrl(), (request) => this._control(request));
2020
+ await process._connect({
2021
+ type: "attach",
2022
+ process_id: processId,
2023
+ offset
2024
+ });
2025
+ return process;
2026
+ }
2027
+ async _connectionUrl() {
2028
+ return (await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this.id } } }), "transient"))).url;
2029
+ }
2030
+ async _control(request) {
2031
+ const socket = await openProcessSocket(() => this._connectionUrl());
2032
+ const expected = request.type === "kill" ? "killed" : "resized";
2033
+ await new Promise((resolve, reject) => {
2034
+ socket.addEventListener("message", (message) => {
2035
+ try {
2036
+ const event = JSON.parse(message.data);
2037
+ if (event.type === "error") reject(/* @__PURE__ */ new Error(`${event.error}: ${event.message}`));
2038
+ else if (event.type !== expected) reject(/* @__PURE__ */ new Error(`Expected ${expected}, received ${event.type}`));
2039
+ else resolve();
2040
+ } catch (error) {
2041
+ reject(error);
2042
+ } finally {
2043
+ socket.close();
2044
+ }
2045
+ }, { once: true });
2046
+ socket.addEventListener("error", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} request failed`)));
2047
+ socket.addEventListener("close", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} connection closed before confirmation`)));
2048
+ socket.send(JSON.stringify(request));
2049
+ });
2050
+ }
1924
2051
  /** Run a process and wait for it to exit. */
1925
2052
  async exec(command, options = {}) {
1926
- return (await this.processes.start(command, options)).wait();
2053
+ return (await this.run(command, options)).wait();
1927
2054
  }
1928
2055
  /** Re-fetch this sandbox. */
1929
2056
  async refresh() {
@@ -1932,10 +2059,13 @@ var Sandbox = class Sandbox {
1932
2059
  }
1933
2060
  /** Start this sandbox. */
1934
2061
  async start(options = {}) {
1935
- const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/start", { params: {
1936
- path: { sid: this.id },
1937
- query: { wait: options.wait ?? true }
1938
- } }), "transient"));
2062
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/start", {
2063
+ params: {
2064
+ path: { sid: this.id },
2065
+ query: { wait: options.wait ?? true }
2066
+ },
2067
+ ...options.mounts !== void 0 && { body: { mounts: options.mounts.map(sandboxMountWire) } }
2068
+ }), options.mounts === void 0 ? "transient" : "connect"));
1939
2069
  this._apply(data);
1940
2070
  return options.wait === false ? this : waitForSandboxStart(this);
1941
2071
  }
@@ -2140,12 +2270,14 @@ var Sandboxes = class {
2140
2270
  vcpu_count: request.vcpuCount,
2141
2271
  mem_size_mib: request.memSizeMiB,
2142
2272
  base_image: request.baseImage,
2273
+ image_id: request.imageId,
2143
2274
  env: request.env,
2144
2275
  max_ttl_seconds: request.maxTtlSeconds,
2145
2276
  idle_ttl_seconds: request.idleTtlSeconds,
2146
2277
  max_concurrent_execs: request.maxConcurrentExecs,
2147
2278
  network: request.network,
2148
- ports: request.ports
2279
+ ports: request.ports,
2280
+ ...request.mounts !== void 0 && { mounts: request.mounts.map(sandboxMountWire) }
2149
2281
  };
2150
2282
  const sandbox = new Sandbox(await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes", {
2151
2283
  params: { query: { wait: options.wait ?? true } },
@@ -2436,6 +2568,7 @@ function diskIdFromMount(m) {
2436
2568
  }
2437
2569
  var Archil = class {
2438
2570
  disks;
2571
+ images;
2439
2572
  sandboxes;
2440
2573
  tokens;
2441
2574
  /** @internal */
@@ -2455,6 +2588,7 @@ var Archil = class {
2455
2588
  const s3BaseUrl = opts.s3BaseUrl ?? envVar("ARCHIL_S3_BASE_URL") ?? deriveS3BaseUrl(controlBaseUrl);
2456
2589
  this._client = client;
2457
2590
  this.disks = new Disks(client, region, s3BaseUrl);
2591
+ this.images = new Images(client);
2458
2592
  this.sandboxes = new Sandboxes(client);
2459
2593
  this.tokens = new Tokens(client);
2460
2594
  }
@@ -2547,4 +2681,4 @@ function workspace(mounts) {
2547
2681
  return archil().workspace(mounts);
2548
2682
  }
2549
2683
  //#endregion
2550
- export { ArchilS3Error as A, DiskMultipart as C, REGION_URLS as D, VERSION as E, SandboxPauseError as M, ArchilApiError as O, Disk as S, USER_AGENT as T, Sandbox as _, deleteApiKey as a, SandboxProcesses as b, getSandbox as c, listSandboxes as d, workspace as f, Sandboxes as g, Tokens as h, createSandbox as i, SandboxFileTransferError as j, ArchilError as k, listApiKeys as l, Workspace as m, createApiKey as n, exec as o, Archil as p, createDisk as r, getDisk as s, configure as t, listDisks as u, SandboxFiles as v, effectiveUploadPartSize as w, Disks as x, SandboxProcess as y };
2684
+ export { ArchilError as A, Disk as C, VERSION as D, USER_AGENT as E, ImageBuildError as M, SandboxFileTransferError as N, REGION_URLS as O, SandboxPauseError as P, Disks as S, effectiveUploadPartSize as T, Sandbox as _, deleteApiKey as a, SandboxProcesses as b, getSandbox as c, listSandboxes as d, workspace as f, Sandboxes as g, Tokens as h, createSandbox as i, ArchilS3Error as j, ArchilApiError as k, listApiKeys as l, Workspace as m, createApiKey as n, exec as o, Archil as p, createDisk as r, getDisk as s, configure as t, listDisks as u, SandboxFiles as v, DiskMultipart as w, Images as x, SandboxProcess as y };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "disk",
3
- "version": "1.6.0",
3
+ "version": "1.8.0",
4
4
  "description": "Pure-JS client and CLIs for Archil disks and sandboxes",
5
5
  "keywords": [
6
6
  "archil",
@@ -40,7 +40,7 @@
40
40
  "LICENSE"
41
41
  ],
42
42
  "dependencies": {
43
- "@archildata/api-types": "^0.0.40",
43
+ "@archildata/api-types": "^0.0.49",
44
44
  "@clack/prompts": "^1.7.0",
45
45
  "commander": "^14.0.3",
46
46
  "fast-xml-parser": "^5.7.0",