disk 1.6.0 → 1.7.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.
package/README.md CHANGED
@@ -155,7 +155,7 @@ const sandbox = await client.sandboxes.create({
155
155
  const result = await sandbox.exec("uname -a");
156
156
  console.log(result.stdout);
157
157
 
158
- const terminal = await sandbox.processes.start("codex", {
158
+ const terminal = await sandbox.run("codex", {
159
159
  terminal: { cols: 120, rows: 40 },
160
160
  onOutput: ({ data }) => process.stdout.write(data),
161
161
  });
@@ -165,7 +165,7 @@ await terminal.resize({ cols: 160, rows: 50 });
165
165
  const cursor = terminal.cursor;
166
166
  await terminal.disconnect();
167
167
 
168
- const resumed = await sandbox.processes.connect(processId, {
168
+ const resumed = await sandbox.attach(processId, {
169
169
  offset: cursor,
170
170
  onOutput: ({ data }) => process.stdout.write(data),
171
171
  });
@@ -183,11 +183,37 @@ const all = await client.sandboxes.list();
183
183
  const usingDisk = await client.sandboxes.list({ disk: "dsk-abc123" });
184
184
  ```
185
185
 
186
+ Build a sandbox image from an OCI reference, then create sandboxes from it:
187
+
188
+ ```ts
189
+ const image = await client.images.build({
190
+ source: "ghcr.io/acme/agent:v3",
191
+ // Private images only.
192
+ registryAuth: { username: "bot", password: process.env.GHCR_TOKEN! },
193
+ });
194
+ const agent = await client.sandboxes.create({ imageId: image.imageId });
195
+ console.log(agent.imageDigest);
196
+ ```
197
+
198
+ `build()` waits until the image is ready, joining a build already in progress.
199
+ It times out after 30 minutes by default (`{ timeoutSeconds }` changes this)
200
+ with an `ArchilError` whose `code` is `IMAGE_BUILD_TIMEOUT`. Building a tag
201
+ again rebuilds it in case the tag moved, so build once and reuse `imageId`; a
202
+ built digest reference (`repo@sha256:...`) returns immediately. Archil never
203
+ stores registry credentials: pass `registryAuth` on every build of a private
204
+ image, since without it the same `source` names the public image. Interrupted
205
+ builds are requested again up to three times. A failed build throws
206
+ `ImageBuildError`; its `reason` is `invalid_source` when the registry reported
207
+ the image missing or denied access, or `interrupted`. `images.get(imageId)`
208
+ returns the image's current state. `imageId` cannot be combined with
209
+ `baseImage`, and creating a sandbox from an image without a successful build
210
+ fails with a 409 `ArchilApiError` whose `code` is `image_not_ready`.
211
+
186
212
  Expose TCP ports publicly when creating a sandbox or later with `exposePort`:
187
213
 
188
214
  ```ts
189
215
  const web = await client.sandboxes.create({ baseImage: "python:3.12-slim", ports: [8080] });
190
- const server = await web.processes.start("python -m http.server 8080 --bind 0.0.0.0");
216
+ const server = await web.run("python -m http.server 8080 --bind 0.0.0.0");
191
217
  await server.disconnect(); // The server keeps running.
192
218
 
193
219
  const hostname = await web.exposePort(8080); // Returns the hostname, including if already public.
@@ -211,7 +237,7 @@ For private HTTP access, create a port token without exposing the port publicly:
211
237
 
212
238
  ```ts
213
239
  const privateWeb = await client.sandboxes.create({ baseImage: "python:3.12-slim" });
214
- const server = await privateWeb.processes.start("python -m http.server 8080 --bind 0.0.0.0");
240
+ const server = await privateWeb.run("python -m http.server 8080 --bind 0.0.0.0");
215
241
  await server.disconnect();
216
242
 
217
243
  const access = await privateWeb.createPortToken(8080, { ttl: "1h" });
@@ -304,11 +330,15 @@ Sandboxes support 1–32 vCPUs and 256–65,536 MiB of memory. When omitted,
304
330
  `vcpuCount` defaults to 1 and `memSizeMiB` defaults to 2,048 MiB. Sandbox
305
331
  timeouts default to 24 hours and can be reset up to 24 hours from now.
306
332
 
307
- `sandbox.processes.start()` always returns a runtime-owned process immediately.
333
+ Pass an absolute `cwd` to `sandbox.run()` or `sandbox.exec()` to choose the
334
+ working directory, for example `sandbox.exec("pytest", { cwd: "/workspace/app" })`.
335
+ Omitting it keeps the sandbox's default working directory.
336
+
337
+ `sandbox.run()` always returns a runtime-owned process immediately.
308
338
  Pass `terminal: true` when the command needs terminal behavior, or provide
309
339
  `{ cols, rows }` for an initial size. Terminal processes merge stdout and stderr
310
340
  into `stdout`; non-terminal processes keep the streams separate. Disconnecting
311
- leaves the process running. Reconnect with `sandbox.processes.connect(id)` to
341
+ leaves the process running. Reconnect with `sandbox.attach(id)` to
312
342
  replay buffered output from the beginning, or pass `{ offset: process.cursor }`
313
343
  to continue where the previous connection stopped. `onOutput` receives raw
314
344
  bytes with their stream and absolute offset. Call `closeStdin()` to deliver EOF
@@ -322,9 +352,12 @@ one-shot controls do not count. Pausing a sandbox disconnects attachments but
322
352
  preserves its processes for reattachment after resume. Processes end when
323
353
  their sandbox is stopped or expires.
324
354
  `sandbox.exec()` is the one-call start-and-wait convenience for ordinary
325
- commands. It uses `sandbox.processes` internally and does not create a durable
326
- control-plane exec record; use `sandbox.processes.start()` when you need the
327
- process handle.
355
+ commands. It uses `sandbox.run()` internally and does not create a durable
356
+ control-plane exec record; use `sandbox.run()` when you need the
357
+ process handle. Replace `sandbox.processes.start()` with `sandbox.run()` and
358
+ `sandbox.processes.connect()` with `sandbox.attach()`. The old methods and the
359
+ `SandboxProcesses` export remain available as deprecated compatibility APIs and will
360
+ be removed in the next version.
328
361
 
329
362
  Transfer files through the sandbox process connection without buffering the
330
363
  whole file in memory:
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-CxdnwAiv.mjs";
3
- import { a as renderTable, i as resolveProgramCredentials, n as addProfileCommands, r as isProfileCommand, t as addGlobalOptions } from "./common-DglyXr-d.mjs";
2
+ import { a as deleteApiKey, k as ArchilApiError, l as listApiKeys, n as createApiKey, r as createDisk, s as getDisk, t as configure, u as listDisks } from "./src-CXTEUmMV.mjs";
3
+ import { a as renderTable, i as resolveProgramCredentials, n as addProfileCommands, r as isProfileCommand, t as addGlobalOptions } from "./common-BkH4aHPf.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-CxdnwAiv.mjs";
1
+ import { O as REGION_URLS, p as Archil } from "./src-CXTEUmMV.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
@@ -70,6 +70,16 @@ var SandboxPauseError = class extends ArchilError {
70
70
  this.name = "SandboxPauseError";
71
71
  }
72
72
  };
73
+ var ImageBuildError = class extends ArchilError {
74
+ latest;
75
+ reason;
76
+ constructor(latest) {
77
+ super(`Image ${latest.imageId} build failed: ${latest.failureReason}`, 409, "IMAGE_BUILD_FAILED");
78
+ this.latest = latest;
79
+ this.name = "ImageBuildError";
80
+ this.reason = latest.failureReason;
81
+ }
82
+ };
73
83
  var SandboxFileTransferError = class extends ArchilError {
74
84
  operation;
75
85
  path;
@@ -153,7 +163,7 @@ function deriveS3BaseUrl(controlBaseUrl) {
153
163
  }
154
164
  //#endregion
155
165
  //#region src/version.ts
156
- const VERSION = "1.6.0";
166
+ const VERSION = "1.7.0";
157
167
  const USER_AGENT = `archil-js/${VERSION}`;
158
168
  //#endregion
159
169
  //#region src/client.ts
@@ -262,8 +272,11 @@ async function unwrap(promise) {
262
272
  */
263
273
  async function unwrapPage(promise) {
264
274
  const { data: body, error, response } = await promise;
265
- if (error || !body) throw new ArchilApiError(error?.error ?? `API request failed with status ${response.status}`, response.status);
266
- if (!body.success) throw new ArchilApiError(body.error ?? "Unknown API error", response.status);
275
+ if (error || !body) {
276
+ const errBody = error;
277
+ throw new ArchilApiError(errBody?.error ?? `API request failed with status ${response.status}`, response.status, errBody?.code);
278
+ }
279
+ if (!body.success) throw new ArchilApiError(body.error ?? "Unknown API error", response.status, body.code);
267
280
  return {
268
281
  data: body.data,
269
282
  nextCursor: body.nextCursor
@@ -275,8 +288,11 @@ async function unwrapPage(promise) {
275
288
  async function unwrapEmpty(promise) {
276
289
  const { data: body, error, response } = await promise;
277
290
  if (!error && response.status === 204) return;
278
- if (error || !body) throw new ArchilApiError(error?.error ?? `API request failed with status ${response.status}`, response.status);
279
- if (!body.success) throw new ArchilApiError(body.error ?? "Unknown API error", response.status);
291
+ if (error || !body) {
292
+ const errBody = error;
293
+ throw new ArchilApiError(errBody?.error ?? `API request failed with status ${response.status}`, response.status, errBody?.code);
294
+ }
295
+ if (!body.success) throw new ArchilApiError(body.error ?? "Unknown API error", response.status, body.code);
280
296
  }
281
297
  const RETRY_BASE_MS = 100;
282
298
  const RETRY_CAP_MS = 2e3;
@@ -1329,6 +1345,77 @@ var Disks = class {
1329
1345
  }
1330
1346
  };
1331
1347
  //#endregion
1348
+ //#region src/images.ts
1349
+ const DEFAULT_BUILD_TIMEOUT_SECONDS = 1800;
1350
+ const MAX_INTERRUPTED_RETRIES = 3;
1351
+ const REQUEST_AGAIN_MS = 2 * 6e4;
1352
+ const FIRST_POLL_MS = 1e3;
1353
+ const MAX_POLL_MS = 5e3;
1354
+ function imageFromWire(data) {
1355
+ return {
1356
+ imageId: data.image_id,
1357
+ source: data.source,
1358
+ private: data.private,
1359
+ status: data.status,
1360
+ digest: data.digest,
1361
+ canonicalSource: data.canonical_source,
1362
+ failureReason: data.failure_reason,
1363
+ createdAt: new Date(data.created_at),
1364
+ updatedAt: new Date(data.updated_at)
1365
+ };
1366
+ }
1367
+ var Images = class {
1368
+ /** @internal */
1369
+ _client;
1370
+ /** @internal */
1371
+ constructor(client) {
1372
+ this._client = client;
1373
+ }
1374
+ async get(imageId) {
1375
+ return imageFromWire(await unwrap(retryApiRequest(() => this._client.GET("/api/images/{image_id}", { params: { path: { image_id: imageId } } }), "transient")));
1376
+ }
1377
+ /**
1378
+ * Build a sandbox image from an OCI reference and wait until it is ready.
1379
+ * Returns at once when the image is already built from a digest reference
1380
+ * and joins a build that is already running. A tag is rebuilt on each call
1381
+ * in case it moved, so call this once and reuse `imageId`. Interrupted
1382
+ * builds are requested again up to three times; other failures throw
1383
+ * {@link ImageBuildError}.
1384
+ */
1385
+ async build(request, options = {}) {
1386
+ const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_BUILD_TIMEOUT_SECONDS;
1387
+ const deadline = Date.now() + timeoutSeconds * 1e3;
1388
+ let image = await this._request(request);
1389
+ let lastRequest = Date.now();
1390
+ let retries = 0;
1391
+ let pollMs = FIRST_POLL_MS;
1392
+ for (;;) {
1393
+ if (image.status === "ready") return image;
1394
+ if (image.status === "failed") {
1395
+ if (image.failureReason !== "interrupted" || retries >= MAX_INTERRUPTED_RETRIES) throw new ImageBuildError(image);
1396
+ retries++;
1397
+ image = await this._request(request);
1398
+ lastRequest = Date.now();
1399
+ continue;
1400
+ }
1401
+ if (Date.now() >= deadline) throw new ArchilError(`Image ${image.imageId} was not ready after ${timeoutSeconds} seconds`, 408, "IMAGE_BUILD_TIMEOUT");
1402
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
1403
+ pollMs = Math.min(pollMs * 2, MAX_POLL_MS);
1404
+ image = await this.get(image.imageId);
1405
+ if (image.status === "building" && Date.now() - lastRequest >= REQUEST_AGAIN_MS) {
1406
+ image = await this._request(request);
1407
+ lastRequest = Date.now();
1408
+ }
1409
+ }
1410
+ }
1411
+ async _request(request) {
1412
+ return imageFromWire(await unwrap(retryApiRequest(() => this._client.POST("/api/images", { body: {
1413
+ source: request.source,
1414
+ registry_auth: request.registryAuth
1415
+ } }), "transient")));
1416
+ }
1417
+ };
1418
+ //#endregion
1332
1419
  //#region src/sandbox-process.ts
1333
1420
  const PROCESS_STDIN_CHUNK_BYTES = 1024 * 1024;
1334
1421
  async function waitForSocketOpen(socket) {
@@ -1373,62 +1460,20 @@ async function openProcessSocket(connectionUrl) {
1373
1460
  await retrySleep(attempt);
1374
1461
  }
1375
1462
  }
1463
+ /** @deprecated Use Sandbox.run() and Sandbox.attach(). Removed in the next version. */
1376
1464
  var SandboxProcesses = class {
1377
- _sandboxId;
1378
- _client;
1465
+ _sandbox;
1379
1466
  /** @internal */
1380
- constructor(sandboxId, client) {
1381
- this._sandboxId = sandboxId;
1382
- this._client = client;
1467
+ constructor(_sandbox) {
1468
+ this._sandbox = _sandbox;
1383
1469
  }
1384
- async start(command, options = {}) {
1385
- const process = new SandboxProcess("", 0, options.onOutput, options.collectOutput ?? true, () => this._connectionUrl(), (request) => this._control(request));
1386
- const terminal = typeof options.terminal === "object" ? {
1387
- cols: options.terminal.cols ?? 80,
1388
- rows: options.terminal.rows ?? 24
1389
- } : options.terminal;
1390
- await process._connect({
1391
- type: "start",
1392
- command,
1393
- terminal,
1394
- env: options.env ?? {},
1395
- timeout_seconds: options.timeoutSeconds
1396
- });
1397
- return process;
1398
- }
1399
- async connect(processId, options = {}) {
1400
- const offset = options.offset ?? 0;
1401
- const process = new SandboxProcess(processId, offset, options.onOutput, options.collectOutput ?? true, () => this._connectionUrl(), (request) => this._control(request));
1402
- await process._connect({
1403
- type: "attach",
1404
- process_id: processId,
1405
- offset
1406
- });
1407
- return process;
1470
+ /** @deprecated Use sandbox.run(). Removed in the next version. */
1471
+ start(command, options = {}) {
1472
+ return this._sandbox.run(command, options);
1408
1473
  }
1409
- async _connectionUrl() {
1410
- return (await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this._sandboxId } } }), "transient"))).url;
1411
- }
1412
- async _control(request) {
1413
- const socket = await openProcessSocket(() => this._connectionUrl());
1414
- const expected = request.type === "kill" ? "killed" : "resized";
1415
- await new Promise((resolve, reject) => {
1416
- socket.addEventListener("message", (message) => {
1417
- try {
1418
- const event = JSON.parse(message.data);
1419
- if (event.type === "error") reject(/* @__PURE__ */ new Error(`${event.error}: ${event.message}`));
1420
- else if (event.type !== expected) reject(/* @__PURE__ */ new Error(`Expected ${expected}, received ${event.type}`));
1421
- else resolve();
1422
- } catch (error) {
1423
- reject(error);
1424
- } finally {
1425
- socket.close();
1426
- }
1427
- }, { once: true });
1428
- socket.addEventListener("error", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} request failed`)));
1429
- socket.addEventListener("close", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} connection closed before confirmation`)));
1430
- socket.send(JSON.stringify(request));
1431
- });
1474
+ /** @deprecated Use sandbox.attach(). Removed in the next version. */
1475
+ connect(processId, options = {}) {
1476
+ return this._sandbox.attach(processId, options);
1432
1477
  }
1433
1478
  };
1434
1479
  var SandboxProcess = class {
@@ -1738,10 +1783,10 @@ var ProcessOutputReader = class {
1738
1783
  }
1739
1784
  };
1740
1785
  var SandboxFiles = class {
1741
- _processes;
1786
+ _sandbox;
1742
1787
  /** @internal */
1743
- constructor(processes) {
1744
- this._processes = processes;
1788
+ constructor(sandbox) {
1789
+ this._sandbox = sandbox;
1745
1790
  }
1746
1791
  async uploadFile(source, remotePath, options = {}) {
1747
1792
  const { path, parent } = remoteFilePath(remotePath);
@@ -1749,7 +1794,7 @@ var SandboxFiles = class {
1749
1794
  if (!Number.isInteger(mode) || mode < 0 || mode > 4095) throw new RangeError("mode must be between 0 and 0o7777");
1750
1795
  let process;
1751
1796
  try {
1752
- process = await this._processes.start(UPLOAD_COMMAND, { env: {
1797
+ process = await this._sandbox.run(UPLOAD_COMMAND, { env: {
1753
1798
  ARCHIL_FILE_PARENT: parent,
1754
1799
  ARCHIL_FILE_TARGET: path,
1755
1800
  ARCHIL_FILE_TEMP: `${parent}/.archil-upload-${transferId()}`,
@@ -1771,7 +1816,7 @@ var SandboxFiles = class {
1771
1816
  const reader = new ProcessOutputReader();
1772
1817
  let process;
1773
1818
  try {
1774
- process = await this._processes.start(DOWNLOAD_COMMAND, {
1819
+ process = await this._sandbox.run(DOWNLOAD_COMMAND, {
1775
1820
  env: {
1776
1821
  ARCHIL_FILE_PATH: path,
1777
1822
  ARCHIL_FILE_TEMP: `/tmp/.archil-download-${transferId()}`
@@ -1880,6 +1925,7 @@ var Sandbox = class Sandbox {
1880
1925
  vcpuCount;
1881
1926
  memSizeMiB;
1882
1927
  baseImage;
1928
+ imageDigest;
1883
1929
  platform;
1884
1930
  maxTtlSeconds;
1885
1931
  idleTtlSeconds;
@@ -1891,6 +1937,7 @@ var Sandbox = class Sandbox {
1891
1937
  lastActiveAt;
1892
1938
  exitReason;
1893
1939
  checkpoint;
1940
+ /** @deprecated Use run() and attach(). Removed in the next version. */
1894
1941
  processes;
1895
1942
  files;
1896
1943
  /** @internal */
@@ -1899,8 +1946,8 @@ var Sandbox = class Sandbox {
1899
1946
  constructor(data, client) {
1900
1947
  this._client = client;
1901
1948
  this._apply(data);
1902
- this.processes = new SandboxProcesses(this.id, client);
1903
- this.files = new SandboxFiles(this.processes);
1949
+ this.processes = new SandboxProcesses(this);
1950
+ this.files = new SandboxFiles(this);
1904
1951
  }
1905
1952
  /** @internal Overwrite this sandbox's fields in place from a fresh wire snapshot. */
1906
1953
  _apply(data) {
@@ -1910,6 +1957,7 @@ var Sandbox = class Sandbox {
1910
1957
  this.vcpuCount = data.vcpu_count;
1911
1958
  this.memSizeMiB = data.mem_size_mib;
1912
1959
  this.baseImage = data.base_image;
1960
+ this.imageDigest = data.image_digest ?? "";
1913
1961
  this.platform = data.platform;
1914
1962
  this.maxTtlSeconds = data.max_ttl_seconds;
1915
1963
  this.idleTtlSeconds = data.idle_ttl_seconds ?? 0;
@@ -1931,6 +1979,7 @@ var Sandbox = class Sandbox {
1931
1979
  vcpuCount: this.vcpuCount,
1932
1980
  memSizeMiB: this.memSizeMiB,
1933
1981
  baseImage: this.baseImage,
1982
+ imageDigest: this.imageDigest,
1934
1983
  platform: this.platform,
1935
1984
  maxTtlSeconds: this.maxTtlSeconds,
1936
1985
  idleTtlSeconds: this.idleTtlSeconds,
@@ -1944,9 +1993,61 @@ var Sandbox = class Sandbox {
1944
1993
  checkpoint: this.checkpoint
1945
1994
  };
1946
1995
  }
1996
+ /** Start a process and return its handle without waiting for exit. */
1997
+ async run(command, options = {}) {
1998
+ const process = new SandboxProcess("", 0, options.onOutput, options.collectOutput ?? true, () => this._connectionUrl(), (request) => this._control(request));
1999
+ const terminal = typeof options.terminal === "object" ? {
2000
+ cols: options.terminal.cols ?? 80,
2001
+ rows: options.terminal.rows ?? 24
2002
+ } : options.terminal;
2003
+ await process._connect({
2004
+ type: "start",
2005
+ command,
2006
+ cwd: options.cwd,
2007
+ terminal,
2008
+ env: options.env ?? {},
2009
+ timeout_seconds: options.timeoutSeconds
2010
+ });
2011
+ return process;
2012
+ }
2013
+ /** Reattach to a process, optionally resuming output from a cursor. */
2014
+ async attach(processId, options = {}) {
2015
+ const offset = options.offset ?? 0;
2016
+ const process = new SandboxProcess(processId, offset, options.onOutput, options.collectOutput ?? true, () => this._connectionUrl(), (request) => this._control(request));
2017
+ await process._connect({
2018
+ type: "attach",
2019
+ process_id: processId,
2020
+ offset
2021
+ });
2022
+ return process;
2023
+ }
2024
+ async _connectionUrl() {
2025
+ return (await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this.id } } }), "transient"))).url;
2026
+ }
2027
+ async _control(request) {
2028
+ const socket = await openProcessSocket(() => this._connectionUrl());
2029
+ const expected = request.type === "kill" ? "killed" : "resized";
2030
+ await new Promise((resolve, reject) => {
2031
+ socket.addEventListener("message", (message) => {
2032
+ try {
2033
+ const event = JSON.parse(message.data);
2034
+ if (event.type === "error") reject(/* @__PURE__ */ new Error(`${event.error}: ${event.message}`));
2035
+ else if (event.type !== expected) reject(/* @__PURE__ */ new Error(`Expected ${expected}, received ${event.type}`));
2036
+ else resolve();
2037
+ } catch (error) {
2038
+ reject(error);
2039
+ } finally {
2040
+ socket.close();
2041
+ }
2042
+ }, { once: true });
2043
+ socket.addEventListener("error", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} request failed`)));
2044
+ socket.addEventListener("close", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} connection closed before confirmation`)));
2045
+ socket.send(JSON.stringify(request));
2046
+ });
2047
+ }
1947
2048
  /** Run a process and wait for it to exit. */
1948
2049
  async exec(command, options = {}) {
1949
- return (await this.processes.start(command, options)).wait();
2050
+ return (await this.run(command, options)).wait();
1950
2051
  }
1951
2052
  /** Re-fetch this sandbox. */
1952
2053
  async refresh() {
@@ -2163,6 +2264,7 @@ var Sandboxes = class {
2163
2264
  vcpu_count: request.vcpuCount,
2164
2265
  mem_size_mib: request.memSizeMiB,
2165
2266
  base_image: request.baseImage,
2267
+ image_id: request.imageId,
2166
2268
  env: request.env,
2167
2269
  max_ttl_seconds: request.maxTtlSeconds,
2168
2270
  idle_ttl_seconds: request.idleTtlSeconds,
@@ -2459,6 +2561,7 @@ function diskIdFromMount(m) {
2459
2561
  }
2460
2562
  var Archil = class {
2461
2563
  disks;
2564
+ images;
2462
2565
  sandboxes;
2463
2566
  tokens;
2464
2567
  /** @internal */
@@ -2478,6 +2581,7 @@ var Archil = class {
2478
2581
  const s3BaseUrl = opts.s3BaseUrl ?? envVar("ARCHIL_S3_BASE_URL") ?? deriveS3BaseUrl(controlBaseUrl);
2479
2582
  this._client = client;
2480
2583
  this.disks = new Disks(client, region, s3BaseUrl);
2584
+ this.images = new Images(client);
2481
2585
  this.sandboxes = new Sandboxes(client);
2482
2586
  this.tokens = new Tokens(client);
2483
2587
  }
@@ -2577,6 +2681,8 @@ exports.ArchilS3Error = ArchilS3Error;
2577
2681
  exports.Disk = Disk;
2578
2682
  exports.DiskMultipart = DiskMultipart;
2579
2683
  exports.Disks = Disks;
2684
+ exports.ImageBuildError = ImageBuildError;
2685
+ exports.Images = Images;
2580
2686
  exports.Sandbox = Sandbox;
2581
2687
  exports.SandboxFileTransferError = SandboxFileTransferError;
2582
2688
  exports.SandboxFiles = SandboxFiles;
package/dist/index.d.cts CHANGED
@@ -65,6 +65,61 @@ declare class Disks {
65
65
  exec(id: string, command: string): Promise<ExecResult>;
66
66
  }
67
67
  //#endregion
68
+ //#region src/images.d.ts
69
+ type ImageWire = components["schemas"]["Image"];
70
+ type ImageStatus = components["schemas"]["ImageState"];
71
+ /**
72
+ * Why a build failed. `invalid_source`: the registry reported the image missing
73
+ * or denied access, so retrying won't help. `interrupted`: the build did not
74
+ * finish; requesting it again starts a new build.
75
+ */
76
+ type ImageFailureReason = NonNullable<ImageWire["failure_reason"]>;
77
+ interface Image {
78
+ /** 64-character hex id; pass it to `sandboxes.create({ imageId })`. */
79
+ imageId: string;
80
+ /** Normalized OCI reference. */
81
+ source: string;
82
+ private: boolean;
83
+ status: ImageStatus;
84
+ /** `sha256:` digest of the last successful build, kept while a tag rebuilds. */
85
+ digest?: string;
86
+ /** `repo@sha256:` reference of the last successful build. */
87
+ canonicalSource?: string;
88
+ /** Present only when `status` is `failed`. */
89
+ failureReason?: ImageFailureReason;
90
+ createdAt: Date;
91
+ updatedAt: Date;
92
+ }
93
+ /** Registry credentials for a private image. Archil never stores them. */
94
+ type RegistryAuth = components["schemas"]["RegistryAuth"];
95
+ interface BuildImageRequest {
96
+ /** OCI image reference, such as `node:24-bookworm` or `ghcr.io/owner/app@sha256:<digest>`. */
97
+ source: string;
98
+ /** Required for private images on every build request; without it `source` names the public image. */
99
+ registryAuth?: RegistryAuth;
100
+ }
101
+ interface BuildImageOptions {
102
+ /** Seconds to wait for the build. Defaults to 1800 (30 minutes). */
103
+ timeoutSeconds?: number;
104
+ }
105
+ declare class Images {
106
+ /** @internal */
107
+ private readonly _client;
108
+ /** @internal */
109
+ constructor(client: ApiClient);
110
+ get(imageId: string): Promise<Image>;
111
+ /**
112
+ * Build a sandbox image from an OCI reference and wait until it is ready.
113
+ * Returns at once when the image is already built from a digest reference
114
+ * and joins a build that is already running. A tag is rebuilt on each call
115
+ * in case it moved, so call this once and reuse `imageId`. Interrupted
116
+ * builds are requested again up to three times; other failures throw
117
+ * {@link ImageBuildError}.
118
+ */
119
+ build(request: BuildImageRequest, options?: BuildImageOptions): Promise<Image>;
120
+ private _request;
121
+ }
122
+ //#endregion
68
123
  //#region src/sandbox-process.d.ts
69
124
  type SandboxProcessStatus = "running" | "completed" | "failed" | "cancelled" | "timed_out";
70
125
  type SandboxProcessStream = "stdout" | "stderr";
@@ -85,6 +140,8 @@ interface SandboxProcessConnectOptions {
85
140
  collectOutput?: boolean;
86
141
  }
87
142
  interface SandboxProcessStartOptions {
143
+ /** Absolute working directory inside the sandbox. */
144
+ cwd?: string;
88
145
  /** Enables a PTY. PTY output is merged into stdout and stderr remains empty. */
89
146
  terminal?: boolean | SandboxTerminalOptions;
90
147
  env?: Record<string, string>;
@@ -103,6 +160,7 @@ interface SandboxProcessResult {
103
160
  type ProcessConnectionRequest = {
104
161
  type: "start";
105
162
  command: string;
163
+ cwd?: string;
106
164
  terminal?: boolean | {
107
165
  cols: number;
108
166
  rows: number;
@@ -123,15 +181,15 @@ type ProcessControlRequest = {
123
181
  cols: number;
124
182
  rows: number;
125
183
  };
184
+ /** @deprecated Use Sandbox.run() and Sandbox.attach(). Removed in the next version. */
126
185
  declare class SandboxProcesses {
127
- private readonly _sandboxId;
128
- private readonly _client;
186
+ private readonly _sandbox;
129
187
  /** @internal */
130
- constructor(sandboxId: string, client: ApiClient);
188
+ constructor(_sandbox: Pick<Sandbox, "run" | "attach">);
189
+ /** @deprecated Use sandbox.run(). Removed in the next version. */
131
190
  start(command: string, options?: SandboxProcessStartOptions): Promise<SandboxProcess>;
191
+ /** @deprecated Use sandbox.attach(). Removed in the next version. */
132
192
  connect(processId: string, options?: SandboxProcessConnectOptions): Promise<SandboxProcess>;
133
- private _connectionUrl;
134
- private _control;
135
193
  }
136
194
  declare class SandboxProcess {
137
195
  status: SandboxProcessStatus;
@@ -187,9 +245,9 @@ interface SandboxFileUploadOptions {
187
245
  mode?: number;
188
246
  }
189
247
  declare class SandboxFiles {
190
- private readonly _processes;
248
+ private readonly _sandbox;
191
249
  /** @internal */
192
- constructor(processes: SandboxProcesses);
250
+ constructor(sandbox: Pick<Sandbox, "run">);
193
251
  uploadFile(source: SandboxFileSource, remotePath: string, options?: SandboxFileUploadOptions): Promise<void>;
194
252
  downloadFile(remotePath: string, write: SandboxFileWriter): Promise<void>;
195
253
  }
@@ -243,7 +301,10 @@ interface SandboxResponse {
243
301
  status: SandboxStatus;
244
302
  vcpuCount: number;
245
303
  memSizeMiB: number;
304
+ /** Empty for sandboxes created from `imageId`. */
246
305
  baseImage: string;
306
+ /** Digest of the image the sandbox was created from; may be empty. */
307
+ imageDigest: string;
247
308
  platform?: "arm64" | "amd64";
248
309
  maxTtlSeconds: number;
249
310
  idleTtlSeconds: number;
@@ -282,6 +343,7 @@ declare class Sandbox {
282
343
  vcpuCount: number;
283
344
  memSizeMiB: number;
284
345
  baseImage: string;
346
+ imageDigest: string;
285
347
  platform?: "arm64" | "amd64";
286
348
  maxTtlSeconds: number;
287
349
  idleTtlSeconds: number;
@@ -293,6 +355,7 @@ declare class Sandbox {
293
355
  lastActiveAt: Date;
294
356
  exitReason?: string;
295
357
  checkpoint?: string;
358
+ /** @deprecated Use run() and attach(). Removed in the next version. */
296
359
  readonly processes: SandboxProcesses;
297
360
  readonly files: SandboxFiles;
298
361
  /** @internal */
@@ -302,6 +365,12 @@ declare class Sandbox {
302
365
  /** @internal Overwrite this sandbox's fields in place from a fresh wire snapshot. */
303
366
  private _apply;
304
367
  toJSON(): SandboxResponse;
368
+ /** Start a process and return its handle without waiting for exit. */
369
+ run(command: string, options?: SandboxProcessStartOptions): Promise<SandboxProcess>;
370
+ /** Reattach to a process, optionally resuming output from a cursor. */
371
+ attach(processId: string, options?: SandboxProcessConnectOptions): Promise<SandboxProcess>;
372
+ private _connectionUrl;
373
+ private _control;
305
374
  /** Run a process and wait for it to exit. */
306
375
  exec(command: string, options?: SandboxProcessStartOptions): Promise<SandboxProcessResult>;
307
376
  /** Re-fetch this sandbox. */
@@ -368,6 +437,8 @@ interface CreateSandboxRequest {
368
437
  * `alpine@sha256:<digest>`.
369
438
  */
370
439
  baseImage?: string;
440
+ /** Ready image from `images.build()`. Cannot be combined with `baseImage`. */
441
+ imageId?: string;
371
442
  env?: Record<string, string>;
372
443
  maxTtlSeconds?: number;
373
444
  /** Seconds without a direct process connection before pausing. Omitted or zero disables idle expiry. */
@@ -542,6 +613,7 @@ interface ExecOptions {
542
613
  }
543
614
  declare class Archil {
544
615
  readonly disks: Disks;
616
+ readonly images: Images;
545
617
  readonly sandboxes: Sandboxes;
546
618
  readonly tokens: Tokens;
547
619
  /** @internal */
@@ -584,6 +656,11 @@ declare class SandboxPauseError extends ArchilError {
584
656
  readonly latest: Sandbox;
585
657
  constructor(latest: Sandbox);
586
658
  }
659
+ declare class ImageBuildError extends ArchilError {
660
+ readonly latest: Image;
661
+ readonly reason?: ImageFailureReason;
662
+ constructor(latest: Image);
663
+ }
587
664
  declare class SandboxFileTransferError extends ArchilError {
588
665
  readonly operation: "upload" | "download";
589
666
  readonly path: string;
@@ -640,4 +717,4 @@ declare function exec(opts: ExecOptions): Promise<ExecDiskResult>;
640
717
  */
641
718
  declare function workspace(mounts: Record<string, ExecMount>): Workspace;
642
719
  //#endregion
643
- export { type ApiTokenResponse, type AppendObjectOptions, Archil, ArchilApiError, ArchilError, type ArchilOptions, ArchilS3Error, type ArchilTlsOptions, type AuthorizedUser, type AwsStsUser, type AzureBlobMount, type CompletedMultipartUpload, type ConnectedClient, type CreateApiTokenRequest, type CreateDiskRequest, type CreateDiskResult, type CreateSandboxPortTokenOptions, type CreateSandboxRequest, type CreatedSandboxPortToken, 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 ListSandboxPortTokensOptions, 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, SandboxPauseError, type SandboxPortToken, type SandboxPortTokenPage, SandboxProcess, type SandboxProcessConnectOptions, type SandboxProcessOutput, type SandboxProcessOutputHandler, type SandboxProcessResult, type SandboxProcessStartOptions, type SandboxProcessStatus, type SandboxProcessStream, SandboxProcesses, type SandboxResponse, type SandboxStatus, type SandboxTerminalOptions, type SandboxTimeoutOptions, 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 };
720
+ export { type ApiTokenResponse, type AppendObjectOptions, Archil, ArchilApiError, ArchilError, type ArchilOptions, ArchilS3Error, type ArchilTlsOptions, type AuthorizedUser, type AwsStsUser, type AzureBlobMount, type BuildImageOptions, type BuildImageRequest, type CompletedMultipartUpload, type ConnectedClient, type CreateApiTokenRequest, type CreateDiskRequest, type CreateDiskResult, type CreateSandboxPortTokenOptions, type CreateSandboxRequest, type CreatedSandboxPortToken, 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 Image, ImageBuildError, type ImageFailureReason, type ImageStatus, Images, type ListDisksOptions, type ListMultipartUploadsOptions, type ListObjectsOptions, type ListObjectsResult, type ListPartsOptions, type ListSandboxPortTokensOptions, 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 RegistryAuth, 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, SandboxPauseError, type SandboxPortToken, type SandboxPortTokenPage, SandboxProcess, type SandboxProcessConnectOptions, type SandboxProcessOutput, type SandboxProcessOutputHandler, type SandboxProcessResult, type SandboxProcessStartOptions, type SandboxProcessStatus, type SandboxProcessStream, SandboxProcesses, type SandboxResponse, type SandboxStatus, type SandboxTerminalOptions, type SandboxTimeoutOptions, 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
@@ -65,6 +65,61 @@ declare class Disks {
65
65
  exec(id: string, command: string): Promise<ExecResult>;
66
66
  }
67
67
  //#endregion
68
+ //#region src/images.d.ts
69
+ type ImageWire = components["schemas"]["Image"];
70
+ type ImageStatus = components["schemas"]["ImageState"];
71
+ /**
72
+ * Why a build failed. `invalid_source`: the registry reported the image missing
73
+ * or denied access, so retrying won't help. `interrupted`: the build did not
74
+ * finish; requesting it again starts a new build.
75
+ */
76
+ type ImageFailureReason = NonNullable<ImageWire["failure_reason"]>;
77
+ interface Image {
78
+ /** 64-character hex id; pass it to `sandboxes.create({ imageId })`. */
79
+ imageId: string;
80
+ /** Normalized OCI reference. */
81
+ source: string;
82
+ private: boolean;
83
+ status: ImageStatus;
84
+ /** `sha256:` digest of the last successful build, kept while a tag rebuilds. */
85
+ digest?: string;
86
+ /** `repo@sha256:` reference of the last successful build. */
87
+ canonicalSource?: string;
88
+ /** Present only when `status` is `failed`. */
89
+ failureReason?: ImageFailureReason;
90
+ createdAt: Date;
91
+ updatedAt: Date;
92
+ }
93
+ /** Registry credentials for a private image. Archil never stores them. */
94
+ type RegistryAuth = components["schemas"]["RegistryAuth"];
95
+ interface BuildImageRequest {
96
+ /** OCI image reference, such as `node:24-bookworm` or `ghcr.io/owner/app@sha256:<digest>`. */
97
+ source: string;
98
+ /** Required for private images on every build request; without it `source` names the public image. */
99
+ registryAuth?: RegistryAuth;
100
+ }
101
+ interface BuildImageOptions {
102
+ /** Seconds to wait for the build. Defaults to 1800 (30 minutes). */
103
+ timeoutSeconds?: number;
104
+ }
105
+ declare class Images {
106
+ /** @internal */
107
+ private readonly _client;
108
+ /** @internal */
109
+ constructor(client: ApiClient);
110
+ get(imageId: string): Promise<Image>;
111
+ /**
112
+ * Build a sandbox image from an OCI reference and wait until it is ready.
113
+ * Returns at once when the image is already built from a digest reference
114
+ * and joins a build that is already running. A tag is rebuilt on each call
115
+ * in case it moved, so call this once and reuse `imageId`. Interrupted
116
+ * builds are requested again up to three times; other failures throw
117
+ * {@link ImageBuildError}.
118
+ */
119
+ build(request: BuildImageRequest, options?: BuildImageOptions): Promise<Image>;
120
+ private _request;
121
+ }
122
+ //#endregion
68
123
  //#region src/sandbox-process.d.ts
69
124
  type SandboxProcessStatus = "running" | "completed" | "failed" | "cancelled" | "timed_out";
70
125
  type SandboxProcessStream = "stdout" | "stderr";
@@ -85,6 +140,8 @@ interface SandboxProcessConnectOptions {
85
140
  collectOutput?: boolean;
86
141
  }
87
142
  interface SandboxProcessStartOptions {
143
+ /** Absolute working directory inside the sandbox. */
144
+ cwd?: string;
88
145
  /** Enables a PTY. PTY output is merged into stdout and stderr remains empty. */
89
146
  terminal?: boolean | SandboxTerminalOptions;
90
147
  env?: Record<string, string>;
@@ -103,6 +160,7 @@ interface SandboxProcessResult {
103
160
  type ProcessConnectionRequest = {
104
161
  type: "start";
105
162
  command: string;
163
+ cwd?: string;
106
164
  terminal?: boolean | {
107
165
  cols: number;
108
166
  rows: number;
@@ -123,15 +181,15 @@ type ProcessControlRequest = {
123
181
  cols: number;
124
182
  rows: number;
125
183
  };
184
+ /** @deprecated Use Sandbox.run() and Sandbox.attach(). Removed in the next version. */
126
185
  declare class SandboxProcesses {
127
- private readonly _sandboxId;
128
- private readonly _client;
186
+ private readonly _sandbox;
129
187
  /** @internal */
130
- constructor(sandboxId: string, client: ApiClient);
188
+ constructor(_sandbox: Pick<Sandbox, "run" | "attach">);
189
+ /** @deprecated Use sandbox.run(). Removed in the next version. */
131
190
  start(command: string, options?: SandboxProcessStartOptions): Promise<SandboxProcess>;
191
+ /** @deprecated Use sandbox.attach(). Removed in the next version. */
132
192
  connect(processId: string, options?: SandboxProcessConnectOptions): Promise<SandboxProcess>;
133
- private _connectionUrl;
134
- private _control;
135
193
  }
136
194
  declare class SandboxProcess {
137
195
  status: SandboxProcessStatus;
@@ -187,9 +245,9 @@ interface SandboxFileUploadOptions {
187
245
  mode?: number;
188
246
  }
189
247
  declare class SandboxFiles {
190
- private readonly _processes;
248
+ private readonly _sandbox;
191
249
  /** @internal */
192
- constructor(processes: SandboxProcesses);
250
+ constructor(sandbox: Pick<Sandbox, "run">);
193
251
  uploadFile(source: SandboxFileSource, remotePath: string, options?: SandboxFileUploadOptions): Promise<void>;
194
252
  downloadFile(remotePath: string, write: SandboxFileWriter): Promise<void>;
195
253
  }
@@ -243,7 +301,10 @@ interface SandboxResponse {
243
301
  status: SandboxStatus;
244
302
  vcpuCount: number;
245
303
  memSizeMiB: number;
304
+ /** Empty for sandboxes created from `imageId`. */
246
305
  baseImage: string;
306
+ /** Digest of the image the sandbox was created from; may be empty. */
307
+ imageDigest: string;
247
308
  platform?: "arm64" | "amd64";
248
309
  maxTtlSeconds: number;
249
310
  idleTtlSeconds: number;
@@ -282,6 +343,7 @@ declare class Sandbox {
282
343
  vcpuCount: number;
283
344
  memSizeMiB: number;
284
345
  baseImage: string;
346
+ imageDigest: string;
285
347
  platform?: "arm64" | "amd64";
286
348
  maxTtlSeconds: number;
287
349
  idleTtlSeconds: number;
@@ -293,6 +355,7 @@ declare class Sandbox {
293
355
  lastActiveAt: Date;
294
356
  exitReason?: string;
295
357
  checkpoint?: string;
358
+ /** @deprecated Use run() and attach(). Removed in the next version. */
296
359
  readonly processes: SandboxProcesses;
297
360
  readonly files: SandboxFiles;
298
361
  /** @internal */
@@ -302,6 +365,12 @@ declare class Sandbox {
302
365
  /** @internal Overwrite this sandbox's fields in place from a fresh wire snapshot. */
303
366
  private _apply;
304
367
  toJSON(): SandboxResponse;
368
+ /** Start a process and return its handle without waiting for exit. */
369
+ run(command: string, options?: SandboxProcessStartOptions): Promise<SandboxProcess>;
370
+ /** Reattach to a process, optionally resuming output from a cursor. */
371
+ attach(processId: string, options?: SandboxProcessConnectOptions): Promise<SandboxProcess>;
372
+ private _connectionUrl;
373
+ private _control;
305
374
  /** Run a process and wait for it to exit. */
306
375
  exec(command: string, options?: SandboxProcessStartOptions): Promise<SandboxProcessResult>;
307
376
  /** Re-fetch this sandbox. */
@@ -368,6 +437,8 @@ interface CreateSandboxRequest {
368
437
  * `alpine@sha256:<digest>`.
369
438
  */
370
439
  baseImage?: string;
440
+ /** Ready image from `images.build()`. Cannot be combined with `baseImage`. */
441
+ imageId?: string;
371
442
  env?: Record<string, string>;
372
443
  maxTtlSeconds?: number;
373
444
  /** Seconds without a direct process connection before pausing. Omitted or zero disables idle expiry. */
@@ -542,6 +613,7 @@ interface ExecOptions {
542
613
  }
543
614
  declare class Archil {
544
615
  readonly disks: Disks;
616
+ readonly images: Images;
545
617
  readonly sandboxes: Sandboxes;
546
618
  readonly tokens: Tokens;
547
619
  /** @internal */
@@ -584,6 +656,11 @@ declare class SandboxPauseError extends ArchilError {
584
656
  readonly latest: Sandbox;
585
657
  constructor(latest: Sandbox);
586
658
  }
659
+ declare class ImageBuildError extends ArchilError {
660
+ readonly latest: Image;
661
+ readonly reason?: ImageFailureReason;
662
+ constructor(latest: Image);
663
+ }
587
664
  declare class SandboxFileTransferError extends ArchilError {
588
665
  readonly operation: "upload" | "download";
589
666
  readonly path: string;
@@ -640,4 +717,4 @@ declare function exec(opts: ExecOptions): Promise<ExecDiskResult>;
640
717
  */
641
718
  declare function workspace(mounts: Record<string, ExecMount>): Workspace;
642
719
  //#endregion
643
- export { type ApiTokenResponse, type AppendObjectOptions, Archil, ArchilApiError, ArchilError, type ArchilOptions, ArchilS3Error, type ArchilTlsOptions, type AuthorizedUser, type AwsStsUser, type AzureBlobMount, type CompletedMultipartUpload, type ConnectedClient, type CreateApiTokenRequest, type CreateDiskRequest, type CreateDiskResult, type CreateSandboxPortTokenOptions, type CreateSandboxRequest, type CreatedSandboxPortToken, 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 ListSandboxPortTokensOptions, 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, SandboxPauseError, type SandboxPortToken, type SandboxPortTokenPage, SandboxProcess, type SandboxProcessConnectOptions, type SandboxProcessOutput, type SandboxProcessOutputHandler, type SandboxProcessResult, type SandboxProcessStartOptions, type SandboxProcessStatus, type SandboxProcessStream, SandboxProcesses, type SandboxResponse, type SandboxStatus, type SandboxTerminalOptions, type SandboxTimeoutOptions, 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 };
720
+ export { type ApiTokenResponse, type AppendObjectOptions, Archil, ArchilApiError, ArchilError, type ArchilOptions, ArchilS3Error, type ArchilTlsOptions, type AuthorizedUser, type AwsStsUser, type AzureBlobMount, type BuildImageOptions, type BuildImageRequest, type CompletedMultipartUpload, type ConnectedClient, type CreateApiTokenRequest, type CreateDiskRequest, type CreateDiskResult, type CreateSandboxPortTokenOptions, type CreateSandboxRequest, type CreatedSandboxPortToken, 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 Image, ImageBuildError, type ImageFailureReason, type ImageStatus, Images, type ListDisksOptions, type ListMultipartUploadsOptions, type ListObjectsOptions, type ListObjectsResult, type ListPartsOptions, type ListSandboxPortTokensOptions, 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 RegistryAuth, 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, SandboxPauseError, type SandboxPortToken, type SandboxPortTokenPage, SandboxProcess, type SandboxProcessConnectOptions, type SandboxProcessOutput, type SandboxProcessOutputHandler, type SandboxProcessResult, type SandboxProcessStartOptions, type SandboxProcessStatus, type SandboxProcessStream, SandboxProcesses, type SandboxResponse, type SandboxStatus, type SandboxTerminalOptions, type SandboxTimeoutOptions, 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, M as SandboxPauseError, 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-CxdnwAiv.mjs";
2
- export { Archil, ArchilApiError, ArchilError, ArchilS3Error, Disk, DiskMultipart, Disks, Sandbox, SandboxFileTransferError, SandboxFiles, SandboxPauseError, SandboxProcess, SandboxProcesses, Sandboxes, Tokens, USER_AGENT, VERSION, Workspace, configure, createApiKey, createDisk, createSandbox, deleteApiKey, effectiveUploadPartSize, exec, getDisk, getSandbox, listApiKeys, listDisks, listSandboxes, workspace };
1
+ import { A as ArchilError, C as Disk, D as VERSION, E as USER_AGENT, M as ImageBuildError, N as SandboxFileTransferError, P as SandboxPauseError, S as Disks, T as effectiveUploadPartSize, _ 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 ArchilS3Error, k as ArchilApiError, 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 DiskMultipart, x as Images, y as SandboxProcess } from "./src-CXTEUmMV.mjs";
2
+ export { Archil, ArchilApiError, ArchilError, ArchilS3Error, Disk, DiskMultipart, Disks, ImageBuildError, Images, Sandbox, SandboxFileTransferError, SandboxFiles, SandboxPauseError, 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-CxdnwAiv.mjs";
3
- import { a as renderTable, i as resolveProgramCredentials, n as addProfileCommands, r as isProfileCommand, t as addGlobalOptions } from "./common-DglyXr-d.mjs";
2
+ import { k as ArchilApiError, p as Archil } from "./src-CXTEUmMV.mjs";
3
+ import { a as renderTable, i as resolveProgramCredentials, n as addProfileCommands, r as isProfileCommand, t as addGlobalOptions } from "./common-BkH4aHPf.mjs";
4
4
  import { createRequire } from "node:module";
5
5
  import { Command } from "commander";
6
6
  import { spinner } from "@clack/prompts";
@@ -193,7 +193,7 @@ async function runSandboxShell(options) {
193
193
  const onSighup = () => requestTermination("terminated by local signal", "SIGHUP");
194
194
  const priorRaw = stdin.isRaw ?? false;
195
195
  try {
196
- remote = await options.sandbox.processes.start("/bin/sh -l", {
196
+ remote = await options.sandbox.run("/bin/sh -l", {
197
197
  terminal: {
198
198
  cols: stdout.columns ?? 80,
199
199
  rows: stdout.rows ?? 24
@@ -457,7 +457,7 @@ Use -- before the command so its flags are not parsed as sandbox options.
457
457
  const onSighup = () => onSignal("SIGHUP");
458
458
  try {
459
459
  const shellCommand = command.map((argument) => argument === "" ? "''" : `'${argument.replaceAll("'", `'"'"'`)}'`).join(" ");
460
- remote = await sandbox.processes.start(shellCommand, {
460
+ remote = await sandbox.run(shellCommand, {
461
461
  ...runOptions,
462
462
  collectOutput: options.output === "json",
463
463
  onOutput: options.output === "json" ? void 0 : ({ stream, data }) => {
@@ -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.7.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;
1447
+ /** @deprecated Use sandbox.run(). Removed in the next version. */
1448
+ start(command, options = {}) {
1449
+ return this._sandbox.run(command, options);
1385
1450
  }
1386
- async _connectionUrl() {
1387
- return (await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this._sandboxId } } }), "transient"))).url;
1388
- }
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()}`
@@ -1857,6 +1902,7 @@ var Sandbox = class Sandbox {
1857
1902
  vcpuCount;
1858
1903
  memSizeMiB;
1859
1904
  baseImage;
1905
+ imageDigest;
1860
1906
  platform;
1861
1907
  maxTtlSeconds;
1862
1908
  idleTtlSeconds;
@@ -1868,6 +1914,7 @@ var Sandbox = class Sandbox {
1868
1914
  lastActiveAt;
1869
1915
  exitReason;
1870
1916
  checkpoint;
1917
+ /** @deprecated Use run() and attach(). Removed in the next version. */
1871
1918
  processes;
1872
1919
  files;
1873
1920
  /** @internal */
@@ -1876,8 +1923,8 @@ var Sandbox = class Sandbox {
1876
1923
  constructor(data, client) {
1877
1924
  this._client = client;
1878
1925
  this._apply(data);
1879
- this.processes = new SandboxProcesses(this.id, client);
1880
- this.files = new SandboxFiles(this.processes);
1926
+ this.processes = new SandboxProcesses(this);
1927
+ this.files = new SandboxFiles(this);
1881
1928
  }
1882
1929
  /** @internal Overwrite this sandbox's fields in place from a fresh wire snapshot. */
1883
1930
  _apply(data) {
@@ -1887,6 +1934,7 @@ var Sandbox = class Sandbox {
1887
1934
  this.vcpuCount = data.vcpu_count;
1888
1935
  this.memSizeMiB = data.mem_size_mib;
1889
1936
  this.baseImage = data.base_image;
1937
+ this.imageDigest = data.image_digest ?? "";
1890
1938
  this.platform = data.platform;
1891
1939
  this.maxTtlSeconds = data.max_ttl_seconds;
1892
1940
  this.idleTtlSeconds = data.idle_ttl_seconds ?? 0;
@@ -1908,6 +1956,7 @@ var Sandbox = class Sandbox {
1908
1956
  vcpuCount: this.vcpuCount,
1909
1957
  memSizeMiB: this.memSizeMiB,
1910
1958
  baseImage: this.baseImage,
1959
+ imageDigest: this.imageDigest,
1911
1960
  platform: this.platform,
1912
1961
  maxTtlSeconds: this.maxTtlSeconds,
1913
1962
  idleTtlSeconds: this.idleTtlSeconds,
@@ -1921,9 +1970,61 @@ var Sandbox = class Sandbox {
1921
1970
  checkpoint: this.checkpoint
1922
1971
  };
1923
1972
  }
1973
+ /** Start a process and return its handle without waiting for exit. */
1974
+ async run(command, options = {}) {
1975
+ const process = new SandboxProcess("", 0, options.onOutput, options.collectOutput ?? true, () => this._connectionUrl(), (request) => this._control(request));
1976
+ const terminal = typeof options.terminal === "object" ? {
1977
+ cols: options.terminal.cols ?? 80,
1978
+ rows: options.terminal.rows ?? 24
1979
+ } : options.terminal;
1980
+ await process._connect({
1981
+ type: "start",
1982
+ command,
1983
+ cwd: options.cwd,
1984
+ terminal,
1985
+ env: options.env ?? {},
1986
+ timeout_seconds: options.timeoutSeconds
1987
+ });
1988
+ return process;
1989
+ }
1990
+ /** Reattach to a process, optionally resuming output from a cursor. */
1991
+ async attach(processId, options = {}) {
1992
+ const offset = options.offset ?? 0;
1993
+ const process = new SandboxProcess(processId, offset, options.onOutput, options.collectOutput ?? true, () => this._connectionUrl(), (request) => this._control(request));
1994
+ await process._connect({
1995
+ type: "attach",
1996
+ process_id: processId,
1997
+ offset
1998
+ });
1999
+ return process;
2000
+ }
2001
+ async _connectionUrl() {
2002
+ return (await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this.id } } }), "transient"))).url;
2003
+ }
2004
+ async _control(request) {
2005
+ const socket = await openProcessSocket(() => this._connectionUrl());
2006
+ const expected = request.type === "kill" ? "killed" : "resized";
2007
+ await new Promise((resolve, reject) => {
2008
+ socket.addEventListener("message", (message) => {
2009
+ try {
2010
+ const event = JSON.parse(message.data);
2011
+ if (event.type === "error") reject(/* @__PURE__ */ new Error(`${event.error}: ${event.message}`));
2012
+ else if (event.type !== expected) reject(/* @__PURE__ */ new Error(`Expected ${expected}, received ${event.type}`));
2013
+ else resolve();
2014
+ } catch (error) {
2015
+ reject(error);
2016
+ } finally {
2017
+ socket.close();
2018
+ }
2019
+ }, { once: true });
2020
+ socket.addEventListener("error", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} request failed`)));
2021
+ socket.addEventListener("close", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} connection closed before confirmation`)));
2022
+ socket.send(JSON.stringify(request));
2023
+ });
2024
+ }
1924
2025
  /** Run a process and wait for it to exit. */
1925
2026
  async exec(command, options = {}) {
1926
- return (await this.processes.start(command, options)).wait();
2027
+ return (await this.run(command, options)).wait();
1927
2028
  }
1928
2029
  /** Re-fetch this sandbox. */
1929
2030
  async refresh() {
@@ -2140,6 +2241,7 @@ var Sandboxes = class {
2140
2241
  vcpu_count: request.vcpuCount,
2141
2242
  mem_size_mib: request.memSizeMiB,
2142
2243
  base_image: request.baseImage,
2244
+ image_id: request.imageId,
2143
2245
  env: request.env,
2144
2246
  max_ttl_seconds: request.maxTtlSeconds,
2145
2247
  idle_ttl_seconds: request.idleTtlSeconds,
@@ -2436,6 +2538,7 @@ function diskIdFromMount(m) {
2436
2538
  }
2437
2539
  var Archil = class {
2438
2540
  disks;
2541
+ images;
2439
2542
  sandboxes;
2440
2543
  tokens;
2441
2544
  /** @internal */
@@ -2455,6 +2558,7 @@ var Archil = class {
2455
2558
  const s3BaseUrl = opts.s3BaseUrl ?? envVar("ARCHIL_S3_BASE_URL") ?? deriveS3BaseUrl(controlBaseUrl);
2456
2559
  this._client = client;
2457
2560
  this.disks = new Disks(client, region, s3BaseUrl);
2561
+ this.images = new Images(client);
2458
2562
  this.sandboxes = new Sandboxes(client);
2459
2563
  this.tokens = new Tokens(client);
2460
2564
  }
@@ -2547,4 +2651,4 @@ function workspace(mounts) {
2547
2651
  return archil().workspace(mounts);
2548
2652
  }
2549
2653
  //#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 };
2654
+ 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.7.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",