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.
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" });
@@ -235,6 +261,36 @@ a duration up to `"8760h"` (365 days). `listPortTokens` follows all pages (its
235
261
  Public ports bypass token authentication. Revocation and expiry deny new
236
262
  connections with HTTP 401; existing connections remain open.
237
263
 
264
+ Archil disks can be mounted inside the sandbox at creation. They are mounted on every
265
+ boot and persist across stop/start and pause/resume. A sandbox with mounts must be stopped
266
+ before it is forked; the fork inherits them:
267
+
268
+ ```ts
269
+ const workspace = await client.sandboxes.create({
270
+ mounts: [
271
+ { disk: "dsk-0123456789abcdef", path: "/mnt/archil" },
272
+ { disk: "dsk-fedcba9876543210", path: "/mnt/models", subdirectory: "llama", readOnly: true },
273
+ { disk: "dsk-0000000000000001", path: "/workspace", conditional: true },
274
+ ],
275
+ });
276
+ console.log(workspace.mounts.map((mount) => mount.path));
277
+
278
+ await workspace.stop();
279
+ await workspace.start({ mounts: [{ disk: "dsk-0123456789abcdef", path: "/mnt/other" }] });
280
+ ```
281
+
282
+ These disks are additional mounts; the sandbox retains its internal root disk.
283
+ A sole mount defaults to `/mnt/archil`; `path` is required for every mount when
284
+ more than one disk is mounted. Options: `readOnly`, `conditional`
285
+ (concurrent writers without delegation checkouts), `subdirectory`, and `queueMs` (how long a
286
+ plain mount waits for the disk's exclusive root delegation). A plain read-write mount holds
287
+ that delegation for as long as the sandbox does, including while paused, so use `readOnly`
288
+ or `conditional` for disks that other clients or forks also write.
289
+
290
+ On a cold start, omit `mounts` to retain the current list, pass `mounts: []` to
291
+ clear it, or supply a list to replace it. Mounts cannot be changed on resume or
292
+ while the sandbox is running. `queueMs` cannot be combined with `readOnly` or `conditional`.
293
+
238
294
  Network egress can optionally be restricted when creating a sandbox:
239
295
 
240
296
  ```ts
@@ -304,11 +360,15 @@ Sandboxes support 1–32 vCPUs and 256–65,536 MiB of memory. When omitted,
304
360
  `vcpuCount` defaults to 1 and `memSizeMiB` defaults to 2,048 MiB. Sandbox
305
361
  timeouts default to 24 hours and can be reset up to 24 hours from now.
306
362
 
307
- `sandbox.processes.start()` always returns a runtime-owned process immediately.
363
+ Pass an absolute `cwd` to `sandbox.run()` or `sandbox.exec()` to choose the
364
+ working directory, for example `sandbox.exec("pytest", { cwd: "/workspace/app" })`.
365
+ Omitting it keeps the sandbox's default working directory.
366
+
367
+ `sandbox.run()` always returns a runtime-owned process immediately.
308
368
  Pass `terminal: true` when the command needs terminal behavior, or provide
309
369
  `{ cols, rows }` for an initial size. Terminal processes merge stdout and stderr
310
370
  into `stdout`; non-terminal processes keep the streams separate. Disconnecting
311
- leaves the process running. Reconnect with `sandbox.processes.connect(id)` to
371
+ leaves the process running. Reconnect with `sandbox.attach(id)` to
312
372
  replay buffered output from the beginning, or pass `{ offset: process.cursor }`
313
373
  to continue where the previous connection stopped. `onOutput` receives raw
314
374
  bytes with their stream and absolute offset. Call `closeStdin()` to deliver EOF
@@ -322,9 +382,12 @@ one-shot controls do not count. Pausing a sandbox disconnects attachments but
322
382
  preserves its processes for reattachment after resume. Processes end when
323
383
  their sandbox is stopped or expires.
324
384
  `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.
385
+ commands. It uses `sandbox.run()` internally and does not create a durable
386
+ control-plane exec record; use `sandbox.run()` when you need the
387
+ process handle. Replace `sandbox.processes.start()` with `sandbox.run()` and
388
+ `sandbox.processes.connect()` with `sandbox.attach()`. The old methods and the
389
+ `SandboxProcesses` export remain available as deprecated compatibility APIs and will
390
+ be removed in the next version.
328
391
 
329
392
  Transfer files through the sandbox process connection without buffering the
330
393
  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-c7xI3gpo.mjs";
3
+ import { a as renderTable, i as resolveProgramCredentials, n as addProfileCommands, r as isProfileCommand, t as addGlobalOptions } from "./common-CCIBdgS1.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-c7xI3gpo.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.8.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;
1408
- }
1409
- async _connectionUrl() {
1410
- return (await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this._sandboxId } } }), "transient"))).url;
1470
+ /** @deprecated Use sandbox.run(). Removed in the next version. */
1471
+ start(command, options = {}) {
1472
+ return this._sandbox.run(command, options);
1411
1473
  }
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()}`
@@ -1861,6 +1906,29 @@ function toError(error) {
1861
1906
  }
1862
1907
  //#endregion
1863
1908
  //#region src/sandbox.ts
1909
+ /** @internal */
1910
+ function sandboxMountWire(mount) {
1911
+ const entry = {
1912
+ disk_id: typeof mount.disk === "string" ? mount.disk : mount.disk.id,
1913
+ read_only: mount.readOnly ?? false,
1914
+ conditional: mount.conditional ?? false
1915
+ };
1916
+ if (mount.path !== void 0) entry.path = mount.path;
1917
+ if (mount.subdirectory !== void 0) entry.subdirectory = mount.subdirectory;
1918
+ if (mount.queueMs !== void 0) entry.queue_ms = mount.queueMs;
1919
+ return entry;
1920
+ }
1921
+ function sandboxMountFromWire(mount) {
1922
+ const out = {
1923
+ diskId: mount.disk_id,
1924
+ path: mount.path,
1925
+ readOnly: mount.read_only ?? false,
1926
+ conditional: mount.conditional ?? false
1927
+ };
1928
+ if (mount.subdirectory !== void 0) out.subdirectory = mount.subdirectory;
1929
+ if (mount.queue_ms !== void 0) out.queueMs = mount.queue_ms;
1930
+ return out;
1931
+ }
1864
1932
  function portTokenFromWire(data) {
1865
1933
  return {
1866
1934
  id: data.id,
@@ -1880,17 +1948,20 @@ var Sandbox = class Sandbox {
1880
1948
  vcpuCount;
1881
1949
  memSizeMiB;
1882
1950
  baseImage;
1951
+ imageDigest;
1883
1952
  platform;
1884
1953
  maxTtlSeconds;
1885
1954
  idleTtlSeconds;
1886
1955
  maxConcurrentExecs;
1887
1956
  endpoints;
1957
+ mounts;
1888
1958
  createdAt;
1889
1959
  runningAt;
1890
1960
  finishedAt;
1891
1961
  lastActiveAt;
1892
1962
  exitReason;
1893
1963
  checkpoint;
1964
+ /** @deprecated Use run() and attach(). Removed in the next version. */
1894
1965
  processes;
1895
1966
  files;
1896
1967
  /** @internal */
@@ -1899,8 +1970,8 @@ var Sandbox = class Sandbox {
1899
1970
  constructor(data, client) {
1900
1971
  this._client = client;
1901
1972
  this._apply(data);
1902
- this.processes = new SandboxProcesses(this.id, client);
1903
- this.files = new SandboxFiles(this.processes);
1973
+ this.processes = new SandboxProcesses(this);
1974
+ this.files = new SandboxFiles(this);
1904
1975
  }
1905
1976
  /** @internal Overwrite this sandbox's fields in place from a fresh wire snapshot. */
1906
1977
  _apply(data) {
@@ -1910,11 +1981,13 @@ var Sandbox = class Sandbox {
1910
1981
  this.vcpuCount = data.vcpu_count;
1911
1982
  this.memSizeMiB = data.mem_size_mib;
1912
1983
  this.baseImage = data.base_image;
1984
+ this.imageDigest = data.image_digest ?? "";
1913
1985
  this.platform = data.platform;
1914
1986
  this.maxTtlSeconds = data.max_ttl_seconds;
1915
1987
  this.idleTtlSeconds = data.idle_ttl_seconds ?? 0;
1916
1988
  this.maxConcurrentExecs = data.max_concurrent_execs;
1917
1989
  this.endpoints = data.endpoints?.map((endpoint) => ({ ...endpoint }));
1990
+ this.mounts = (data.mounts ?? []).map(sandboxMountFromWire);
1918
1991
  this.createdAt = new Date(data.created_at);
1919
1992
  this.runningAt = data.running_at ? new Date(data.running_at) : void 0;
1920
1993
  this.finishedAt = data.finished_at ? new Date(data.finished_at) : void 0;
@@ -1931,11 +2004,13 @@ var Sandbox = class Sandbox {
1931
2004
  vcpuCount: this.vcpuCount,
1932
2005
  memSizeMiB: this.memSizeMiB,
1933
2006
  baseImage: this.baseImage,
2007
+ imageDigest: this.imageDigest,
1934
2008
  platform: this.platform,
1935
2009
  maxTtlSeconds: this.maxTtlSeconds,
1936
2010
  idleTtlSeconds: this.idleTtlSeconds,
1937
2011
  maxConcurrentExecs: this.maxConcurrentExecs,
1938
2012
  endpoints: this.endpoints?.map((endpoint) => ({ ...endpoint })),
2013
+ mounts: this.mounts.map((mount) => ({ ...mount })),
1939
2014
  createdAt: this.createdAt,
1940
2015
  runningAt: this.runningAt,
1941
2016
  finishedAt: this.finishedAt,
@@ -1944,9 +2019,61 @@ var Sandbox = class Sandbox {
1944
2019
  checkpoint: this.checkpoint
1945
2020
  };
1946
2021
  }
2022
+ /** Start a process and return its handle without waiting for exit. */
2023
+ async run(command, options = {}) {
2024
+ const process = new SandboxProcess("", 0, options.onOutput, options.collectOutput ?? true, () => this._connectionUrl(), (request) => this._control(request));
2025
+ const terminal = typeof options.terminal === "object" ? {
2026
+ cols: options.terminal.cols ?? 80,
2027
+ rows: options.terminal.rows ?? 24
2028
+ } : options.terminal;
2029
+ await process._connect({
2030
+ type: "start",
2031
+ command,
2032
+ cwd: options.cwd,
2033
+ terminal,
2034
+ env: options.env ?? {},
2035
+ timeout_seconds: options.timeoutSeconds
2036
+ });
2037
+ return process;
2038
+ }
2039
+ /** Reattach to a process, optionally resuming output from a cursor. */
2040
+ async attach(processId, options = {}) {
2041
+ const offset = options.offset ?? 0;
2042
+ const process = new SandboxProcess(processId, offset, options.onOutput, options.collectOutput ?? true, () => this._connectionUrl(), (request) => this._control(request));
2043
+ await process._connect({
2044
+ type: "attach",
2045
+ process_id: processId,
2046
+ offset
2047
+ });
2048
+ return process;
2049
+ }
2050
+ async _connectionUrl() {
2051
+ return (await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this.id } } }), "transient"))).url;
2052
+ }
2053
+ async _control(request) {
2054
+ const socket = await openProcessSocket(() => this._connectionUrl());
2055
+ const expected = request.type === "kill" ? "killed" : "resized";
2056
+ await new Promise((resolve, reject) => {
2057
+ socket.addEventListener("message", (message) => {
2058
+ try {
2059
+ const event = JSON.parse(message.data);
2060
+ if (event.type === "error") reject(/* @__PURE__ */ new Error(`${event.error}: ${event.message}`));
2061
+ else if (event.type !== expected) reject(/* @__PURE__ */ new Error(`Expected ${expected}, received ${event.type}`));
2062
+ else resolve();
2063
+ } catch (error) {
2064
+ reject(error);
2065
+ } finally {
2066
+ socket.close();
2067
+ }
2068
+ }, { once: true });
2069
+ socket.addEventListener("error", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} request failed`)));
2070
+ socket.addEventListener("close", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} connection closed before confirmation`)));
2071
+ socket.send(JSON.stringify(request));
2072
+ });
2073
+ }
1947
2074
  /** Run a process and wait for it to exit. */
1948
2075
  async exec(command, options = {}) {
1949
- return (await this.processes.start(command, options)).wait();
2076
+ return (await this.run(command, options)).wait();
1950
2077
  }
1951
2078
  /** Re-fetch this sandbox. */
1952
2079
  async refresh() {
@@ -1955,10 +2082,13 @@ var Sandbox = class Sandbox {
1955
2082
  }
1956
2083
  /** Start this sandbox. */
1957
2084
  async start(options = {}) {
1958
- const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/start", { params: {
1959
- path: { sid: this.id },
1960
- query: { wait: options.wait ?? true }
1961
- } }), "transient"));
2085
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/start", {
2086
+ params: {
2087
+ path: { sid: this.id },
2088
+ query: { wait: options.wait ?? true }
2089
+ },
2090
+ ...options.mounts !== void 0 && { body: { mounts: options.mounts.map(sandboxMountWire) } }
2091
+ }), options.mounts === void 0 ? "transient" : "connect"));
1962
2092
  this._apply(data);
1963
2093
  return options.wait === false ? this : waitForSandboxStart(this);
1964
2094
  }
@@ -2163,12 +2293,14 @@ var Sandboxes = class {
2163
2293
  vcpu_count: request.vcpuCount,
2164
2294
  mem_size_mib: request.memSizeMiB,
2165
2295
  base_image: request.baseImage,
2296
+ image_id: request.imageId,
2166
2297
  env: request.env,
2167
2298
  max_ttl_seconds: request.maxTtlSeconds,
2168
2299
  idle_ttl_seconds: request.idleTtlSeconds,
2169
2300
  max_concurrent_execs: request.maxConcurrentExecs,
2170
2301
  network: request.network,
2171
- ports: request.ports
2302
+ ports: request.ports,
2303
+ ...request.mounts !== void 0 && { mounts: request.mounts.map(sandboxMountWire) }
2172
2304
  };
2173
2305
  const sandbox = new Sandbox(await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes", {
2174
2306
  params: { query: { wait: options.wait ?? true } },
@@ -2459,6 +2591,7 @@ function diskIdFromMount(m) {
2459
2591
  }
2460
2592
  var Archil = class {
2461
2593
  disks;
2594
+ images;
2462
2595
  sandboxes;
2463
2596
  tokens;
2464
2597
  /** @internal */
@@ -2478,6 +2611,7 @@ var Archil = class {
2478
2611
  const s3BaseUrl = opts.s3BaseUrl ?? envVar("ARCHIL_S3_BASE_URL") ?? deriveS3BaseUrl(controlBaseUrl);
2479
2612
  this._client = client;
2480
2613
  this.disks = new Disks(client, region, s3BaseUrl);
2614
+ this.images = new Images(client);
2481
2615
  this.sandboxes = new Sandboxes(client);
2482
2616
  this.tokens = new Tokens(client);
2483
2617
  }
@@ -2577,6 +2711,8 @@ exports.ArchilS3Error = ArchilS3Error;
2577
2711
  exports.Disk = Disk;
2578
2712
  exports.DiskMultipart = DiskMultipart;
2579
2713
  exports.Disks = Disks;
2714
+ exports.ImageBuildError = ImageBuildError;
2715
+ exports.Images = Images;
2580
2716
  exports.Sandbox = Sandbox;
2581
2717
  exports.SandboxFileTransferError = SandboxFileTransferError;
2582
2718
  exports.SandboxFiles = SandboxFiles;