disk 1.5.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/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.5.0";
166
+ const VERSION = "1.7.0";
157
167
  const USER_AGENT = `archil-js/${VERSION}`;
158
168
  //#endregion
159
169
  //#region src/client.ts
@@ -163,7 +173,7 @@ function isNodeRuntime() {
163
173
  }
164
174
  const undiciModule = isNodeRuntime() ? import("undici") : void 0;
165
175
  const CONTROL_PLANE_CONNECTIONS = 1;
166
- const CONTROL_PLANE_CONCURRENT_STREAMS = 100;
176
+ const IDLE_SESSION_TIMEOUT_MS = 3e4;
167
177
  function isAsyncIterableBody(body) {
168
178
  return body != null && typeof body === "object" && Symbol.asyncIterator in body;
169
179
  }
@@ -172,30 +182,12 @@ async function bufferBody(body) {
172
182
  for await (const chunk of body) chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
173
183
  return Buffer.concat(chunks);
174
184
  }
175
- const multiplexHttp2Requests = (dispatch) => (options, handler) => {
176
- let requestStarted = false;
177
- const guardedHandler = {
178
- onRequestStart(controller, context) {
179
- if (requestStarted) {
180
- controller.abort(/* @__PURE__ */ new Error("Archil control-plane requests are not replayed after a connection failure"));
181
- return;
182
- }
183
- requestStarted = true;
184
- handler.onRequestStart?.(controller, context);
185
- },
186
- onRequestUpgrade: handler.onRequestUpgrade?.bind(handler),
187
- onResponseStart: handler.onResponseStart?.bind(handler),
188
- onResponseData: handler.onResponseData?.bind(handler),
189
- onResponseEnd: handler.onResponseEnd?.bind(handler),
190
- onResponseError: handler.onResponseError?.bind(handler)
191
- };
192
- const dispatchBody = (body) => dispatch({
185
+ const bufferRequestBodies = (dispatch) => (options, handler) => {
186
+ if (!isAsyncIterableBody(options.body)) return dispatch(options, handler);
187
+ bufferBody(options.body).then((body) => dispatch({
193
188
  ...options,
194
- body,
195
- idempotent: true
196
- }, guardedHandler);
197
- if (!isAsyncIterableBody(options.body)) return dispatchBody(options.body);
198
- bufferBody(options.body).then(dispatchBody, (error) => handler.onResponseError?.({
189
+ body
190
+ }, handler), (error) => handler.onResponseError?.({
199
191
  aborted: false,
200
192
  paused: false,
201
193
  reason: null,
@@ -205,7 +197,7 @@ const multiplexHttp2Requests = (dispatch) => (options, handler) => {
205
197
  }, error instanceof Error ? error : new Error(String(error))));
206
198
  return true;
207
199
  };
208
- const sharedDispatchers = /* @__PURE__ */ new Map();
200
+ const sharedTransports = /* @__PURE__ */ new Map();
209
201
  function dispatcherKey(baseUrl, apiKey, ca) {
210
202
  return JSON.stringify([
211
203
  new URL(baseUrl).origin,
@@ -213,26 +205,27 @@ function dispatcherKey(baseUrl, apiKey, ca) {
213
205
  ca?.map((cert) => cert.toString("base64"))
214
206
  ]);
215
207
  }
216
- function getSharedDispatcher(key, ca) {
217
- const existing = sharedDispatchers.get(key);
208
+ function getSharedTransport(key, ca) {
209
+ const existing = sharedTransports.get(key);
218
210
  if (existing) return existing;
219
- const dispatcher = (async () => {
211
+ const transport = (async () => {
220
212
  if (!undiciModule) throw new Error("The pooled control-plane transport requires Node.js");
221
- const { Agent } = await undiciModule;
222
- return new Agent({
223
- allowH2: true,
224
- connections: CONTROL_PLANE_CONNECTIONS,
225
- pipelining: CONTROL_PLANE_CONCURRENT_STREAMS,
226
- keepAliveTimeout: 6e4,
227
- keepAliveMaxTimeout: 6e5,
228
- ...ca === void 0 ? {} : { connect: { ca } }
229
- }).compose(multiplexHttp2Requests);
213
+ const { Agent, fetch } = await undiciModule;
214
+ return {
215
+ fetch,
216
+ dispatcher: new Agent({
217
+ allowH2: true,
218
+ connections: CONTROL_PLANE_CONNECTIONS,
219
+ keepAliveTimeout: IDLE_SESSION_TIMEOUT_MS,
220
+ ...ca === void 0 ? {} : { connect: { ca } }
221
+ }).compose(bufferRequestBodies)
222
+ };
230
223
  })();
231
- sharedDispatchers.set(key, dispatcher);
232
- dispatcher.catch(() => {
233
- if (sharedDispatchers.get(key) === dispatcher) sharedDispatchers.delete(key);
224
+ sharedTransports.set(key, transport);
225
+ transport.catch(() => {
226
+ if (sharedTransports.get(key) === transport) sharedTransports.delete(key);
234
227
  });
235
- return dispatcher;
228
+ return transport;
236
229
  }
237
230
  function createPooledFetch(baseUrl, apiKey, tls) {
238
231
  if (!isNodeRuntime()) {
@@ -242,8 +235,16 @@ function createPooledFetch(baseUrl, apiKey, tls) {
242
235
  const ca = tls?.ca === void 0 ? void 0 : (Array.isArray(tls.ca) ? tls.ca : [tls.ca]).map((cert) => Buffer.from(cert));
243
236
  const key = dispatcherKey(baseUrl, apiKey, ca);
244
237
  return async (request) => {
245
- const dispatcher = await getSharedDispatcher(key, ca);
246
- return globalThis.fetch(request, { dispatcher });
238
+ const { fetch, dispatcher } = await getSharedTransport(key, ca);
239
+ const body = request.body === null ? null : new Uint8Array(await request.arrayBuffer());
240
+ return await fetch(request.url, {
241
+ method: request.method,
242
+ headers: [...request.headers],
243
+ body,
244
+ redirect: request.redirect,
245
+ signal: request.signal,
246
+ dispatcher
247
+ });
247
248
  };
248
249
  }
249
250
  function createApiClient(opts) {
@@ -271,8 +272,11 @@ async function unwrap(promise) {
271
272
  */
272
273
  async function unwrapPage(promise) {
273
274
  const { data: body, error, response } = await promise;
274
- if (error || !body) throw new ArchilApiError(error?.error ?? `API request failed with status ${response.status}`, response.status);
275
- 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);
276
280
  return {
277
281
  data: body.data,
278
282
  nextCursor: body.nextCursor
@@ -284,8 +288,11 @@ async function unwrapPage(promise) {
284
288
  async function unwrapEmpty(promise) {
285
289
  const { data: body, error, response } = await promise;
286
290
  if (!error && response.status === 204) return;
287
- if (error || !body) throw new ArchilApiError(error?.error ?? `API request failed with status ${response.status}`, response.status);
288
- 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);
289
296
  }
290
297
  const RETRY_BASE_MS = 100;
291
298
  const RETRY_CAP_MS = 2e3;
@@ -429,28 +436,28 @@ var Disk = class {
429
436
  };
430
437
  }
431
438
  async addUser(user) {
432
- return unwrap(this._client.POST("/api/disks/{id}/users", {
439
+ return unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/users", {
433
440
  params: { path: { id: this.id } },
434
441
  body: user
435
- }));
442
+ }), "connect"));
436
443
  }
437
444
  async removeUser(userType, identifier) {
438
- await unwrapEmpty(this._client.DELETE("/api/disks/{id}/users/{userType}", { params: {
445
+ await unwrapEmpty(retryApiRequest(() => this._client.DELETE("/api/disks/{id}/users/{userType}", { params: {
439
446
  path: {
440
447
  id: this.id,
441
448
  userType
442
449
  },
443
450
  query: { identifier }
444
- } }));
451
+ } }), "connect"));
445
452
  }
446
453
  async createToken(nickname) {
447
- const user = await unwrap(this._client.POST("/api/disks/{id}/users", {
454
+ const user = await unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/users", {
448
455
  params: { path: { id: this.id } },
449
456
  body: {
450
457
  type: "token",
451
458
  nickname
452
459
  }
453
- }));
460
+ }), "connect"));
454
461
  if (!user.token || !user.identifier) throw new Error("Server did not return a generated token");
455
462
  return user;
456
463
  }
@@ -467,7 +474,7 @@ var Disk = class {
467
474
  * absent.
468
475
  */
469
476
  async listDelegations() {
470
- return (await unwrap(this._client.GET("/api/disks/{id}/delegations", { params: { path: { id: this.id } } }))).delegations;
477
+ return (await unwrap(retryApiRequest(() => this._client.GET("/api/disks/{id}/delegations", { params: { path: { id: this.id } } }), "transient"))).delegations;
471
478
  }
472
479
  /**
473
480
  * Forcibly revoke a delegation, reclaiming write access from a client that
@@ -484,22 +491,22 @@ var Disk = class {
484
491
  */
485
492
  async revokeDelegation(delegation) {
486
493
  const { clientId, inodeId } = delegation;
487
- await unwrap(this._client.POST("/api/disks/{id}/revoke-delegation", {
494
+ await unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/revoke-delegation", {
488
495
  params: { path: { id: this.id } },
489
496
  body: {
490
497
  clientId,
491
498
  inodeId
492
499
  }
493
- }));
500
+ }), "connect"));
494
501
  }
495
502
  async getAllowedIPs() {
496
- return (await unwrap(this._client.GET("/api/disks/{id}/allowed-ips", { params: { path: { id: this.id } } }))).allowedIps;
503
+ return (await unwrap(retryApiRequest(() => this._client.GET("/api/disks/{id}/allowed-ips", { params: { path: { id: this.id } } }), "transient"))).allowedIps;
497
504
  }
498
505
  async setAllowedIPs(allowedIps) {
499
- return (await unwrap(this._client.PUT("/api/disks/{id}/allowed-ips", {
506
+ return (await unwrap(retryApiRequest(() => this._client.PUT("/api/disks/{id}/allowed-ips", {
500
507
  params: { path: { id: this.id } },
501
508
  body: { allowedIps }
502
- }))).allowedIps;
509
+ }), "transient"))).allowedIps;
503
510
  }
504
511
  async addAllowedIP(ip) {
505
512
  const current = await this.getAllowedIPs();
@@ -511,17 +518,17 @@ var Disk = class {
511
518
  return this.setAllowedIPs(current.filter((i) => i !== ip));
512
519
  }
513
520
  async delete() {
514
- await unwrapEmpty(this._client.DELETE("/api/disks/{id}", { params: { path: { id: this.id } } }));
521
+ await unwrapEmpty(retryApiRequest(() => this._client.DELETE("/api/disks/{id}", { params: { path: { id: this.id } } }), "connect"));
515
522
  }
516
523
  /**
517
524
  * Execute a command in a container with this disk mounted.
518
525
  * Blocks until the command completes and returns stdout, stderr, and exit code.
519
526
  */
520
527
  async exec(command) {
521
- return unwrap(this._client.POST("/api/disks/{id}/exec", {
528
+ return unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/exec", {
522
529
  params: { path: { id: this.id } },
523
530
  body: { command }
524
- }));
531
+ }), "connect"));
525
532
  }
526
533
  /**
527
534
  * Constant-time parallel grep across files on this disk. Listing and
@@ -534,7 +541,7 @@ var Disk = class {
534
541
  * reported first), not the lexicographically first N.
535
542
  */
536
543
  async grep(opts) {
537
- return unwrap(this._client.POST("/api/disks/{id}/grep", {
544
+ return unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/grep", {
538
545
  params: { path: { id: this.id } },
539
546
  body: {
540
547
  directory: opts.directory,
@@ -544,7 +551,7 @@ var Disk = class {
544
551
  concurrency: opts.concurrency ?? 50,
545
552
  maxResults: opts.maxResults ?? 1e3
546
553
  }
547
- }));
554
+ }), "transient"));
548
555
  }
549
556
  /**
550
557
  * Create a signed, time-limited URL that lets anyone download a single file
@@ -560,7 +567,7 @@ var Disk = class {
560
567
  const body = { key };
561
568
  if (opts.expiresIn !== void 0) body.expiresIn = opts.expiresIn;
562
569
  const call = this._client.POST;
563
- return unwrap(call(`/api/disks/${this.id}/share`, { body }));
570
+ return unwrap(retryApiRequest(() => call(`/api/disks/${this.id}/share`, { body }), "connect"));
564
571
  }
565
572
  /**
566
573
  * Read an object from the disk via the S3-compatible GetObject API and return
@@ -1288,11 +1295,11 @@ var Disks = class {
1288
1295
  * listing (it can also be persisted, e.g. across requests of a paginated UI).
1289
1296
  */
1290
1297
  async listPage(opts) {
1291
- const { data, nextCursor } = await unwrapPage(this._client.GET("/api/disks", { params: { query: {
1298
+ const { data, nextCursor } = await unwrapPage(retryApiRequest(() => this._client.GET("/api/disks", { params: { query: {
1292
1299
  limit: opts?.limit,
1293
1300
  cursor: opts?.cursor,
1294
1301
  name: opts?.name
1295
- } } }));
1302
+ } } }), "transient"));
1296
1303
  const disks = (data ?? []).map((d) => new Disk(d, this._client, this._region, this._s3BaseUrl));
1297
1304
  return nextCursor ? {
1298
1305
  disks,
@@ -1300,7 +1307,7 @@ var Disks = class {
1300
1307
  } : { disks };
1301
1308
  }
1302
1309
  async get(id) {
1303
- return new Disk(await unwrap(this._client.GET("/api/disks/{id}", { params: { path: { id } } })), this._client, this._region, this._s3BaseUrl);
1310
+ return new Disk(await unwrap(retryApiRequest(() => this._client.GET("/api/disks/{id}", { params: { path: { id } } }), "transient")), this._client, this._region, this._s3BaseUrl);
1304
1311
  }
1305
1312
  /**
1306
1313
  * Create a new disk with an auto-generated mount token.
@@ -1314,7 +1321,7 @@ var Disks = class {
1314
1321
  * Creation-time only.
1315
1322
  */
1316
1323
  async create(req) {
1317
- const resp = await unwrap(this._client.POST("/api/disks", { body: req }));
1324
+ const resp = await unwrap(retryApiRequest(() => this._client.POST("/api/disks", { body: req }), "connect"));
1318
1325
  if (!resp.diskId) throw new Error("API returned success but no diskId");
1319
1326
  const authorizedUsers = resp.authorizedUsers ?? [];
1320
1327
  const tokenUser = authorizedUsers.find((u) => u.token);
@@ -1331,10 +1338,81 @@ var Disks = class {
1331
1338
  * without fetching the disk first.
1332
1339
  */
1333
1340
  async exec(id, command) {
1334
- return unwrap(this._client.POST("/api/disks/{id}/exec", {
1341
+ return unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/exec", {
1335
1342
  params: { path: { id } },
1336
1343
  body: { command }
1337
- }));
1344
+ }), "connect"));
1345
+ }
1346
+ };
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")));
1338
1416
  }
1339
1417
  };
1340
1418
  //#endregion
@@ -1382,62 +1460,20 @@ async function openProcessSocket(connectionUrl) {
1382
1460
  await retrySleep(attempt);
1383
1461
  }
1384
1462
  }
1463
+ /** @deprecated Use Sandbox.run() and Sandbox.attach(). Removed in the next version. */
1385
1464
  var SandboxProcesses = class {
1386
- _sandboxId;
1387
- _client;
1465
+ _sandbox;
1388
1466
  /** @internal */
1389
- constructor(sandboxId, client) {
1390
- this._sandboxId = sandboxId;
1391
- this._client = client;
1392
- }
1393
- async start(command, options = {}) {
1394
- const process = new SandboxProcess("", 0, options.onOutput, options.collectOutput ?? true, () => this._connectionUrl(), (request) => this._control(request));
1395
- const terminal = typeof options.terminal === "object" ? {
1396
- cols: options.terminal.cols ?? 80,
1397
- rows: options.terminal.rows ?? 24
1398
- } : options.terminal;
1399
- await process._connect({
1400
- type: "start",
1401
- command,
1402
- terminal,
1403
- env: options.env ?? {},
1404
- timeout_seconds: options.timeoutSeconds
1405
- });
1406
- return process;
1407
- }
1408
- async connect(processId, options = {}) {
1409
- const offset = options.offset ?? 0;
1410
- const process = new SandboxProcess(processId, offset, options.onOutput, options.collectOutput ?? true, () => this._connectionUrl(), (request) => this._control(request));
1411
- await process._connect({
1412
- type: "attach",
1413
- process_id: processId,
1414
- offset
1415
- });
1416
- return process;
1467
+ constructor(_sandbox) {
1468
+ this._sandbox = _sandbox;
1417
1469
  }
1418
- async _connectionUrl() {
1419
- 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);
1420
1473
  }
1421
- async _control(request) {
1422
- const socket = await openProcessSocket(() => this._connectionUrl());
1423
- const expected = request.type === "kill" ? "killed" : "resized";
1424
- await new Promise((resolve, reject) => {
1425
- socket.addEventListener("message", (message) => {
1426
- try {
1427
- const event = JSON.parse(message.data);
1428
- if (event.type === "error") reject(/* @__PURE__ */ new Error(`${event.error}: ${event.message}`));
1429
- else if (event.type !== expected) reject(/* @__PURE__ */ new Error(`Expected ${expected}, received ${event.type}`));
1430
- else resolve();
1431
- } catch (error) {
1432
- reject(error);
1433
- } finally {
1434
- socket.close();
1435
- }
1436
- }, { once: true });
1437
- socket.addEventListener("error", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} request failed`)));
1438
- socket.addEventListener("close", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} connection closed before confirmation`)));
1439
- socket.send(JSON.stringify(request));
1440
- });
1474
+ /** @deprecated Use sandbox.attach(). Removed in the next version. */
1475
+ connect(processId, options = {}) {
1476
+ return this._sandbox.attach(processId, options);
1441
1477
  }
1442
1478
  };
1443
1479
  var SandboxProcess = class {
@@ -1747,10 +1783,10 @@ var ProcessOutputReader = class {
1747
1783
  }
1748
1784
  };
1749
1785
  var SandboxFiles = class {
1750
- _processes;
1786
+ _sandbox;
1751
1787
  /** @internal */
1752
- constructor(processes) {
1753
- this._processes = processes;
1788
+ constructor(sandbox) {
1789
+ this._sandbox = sandbox;
1754
1790
  }
1755
1791
  async uploadFile(source, remotePath, options = {}) {
1756
1792
  const { path, parent } = remoteFilePath(remotePath);
@@ -1758,7 +1794,7 @@ var SandboxFiles = class {
1758
1794
  if (!Number.isInteger(mode) || mode < 0 || mode > 4095) throw new RangeError("mode must be between 0 and 0o7777");
1759
1795
  let process;
1760
1796
  try {
1761
- process = await this._processes.start(UPLOAD_COMMAND, { env: {
1797
+ process = await this._sandbox.run(UPLOAD_COMMAND, { env: {
1762
1798
  ARCHIL_FILE_PARENT: parent,
1763
1799
  ARCHIL_FILE_TARGET: path,
1764
1800
  ARCHIL_FILE_TEMP: `${parent}/.archil-upload-${transferId()}`,
@@ -1780,7 +1816,7 @@ var SandboxFiles = class {
1780
1816
  const reader = new ProcessOutputReader();
1781
1817
  let process;
1782
1818
  try {
1783
- process = await this._processes.start(DOWNLOAD_COMMAND, {
1819
+ process = await this._sandbox.run(DOWNLOAD_COMMAND, {
1784
1820
  env: {
1785
1821
  ARCHIL_FILE_PATH: path,
1786
1822
  ARCHIL_FILE_TEMP: `/tmp/.archil-download-${transferId()}`
@@ -1889,6 +1925,7 @@ var Sandbox = class Sandbox {
1889
1925
  vcpuCount;
1890
1926
  memSizeMiB;
1891
1927
  baseImage;
1928
+ imageDigest;
1892
1929
  platform;
1893
1930
  maxTtlSeconds;
1894
1931
  idleTtlSeconds;
@@ -1900,6 +1937,7 @@ var Sandbox = class Sandbox {
1900
1937
  lastActiveAt;
1901
1938
  exitReason;
1902
1939
  checkpoint;
1940
+ /** @deprecated Use run() and attach(). Removed in the next version. */
1903
1941
  processes;
1904
1942
  files;
1905
1943
  /** @internal */
@@ -1908,8 +1946,8 @@ var Sandbox = class Sandbox {
1908
1946
  constructor(data, client) {
1909
1947
  this._client = client;
1910
1948
  this._apply(data);
1911
- this.processes = new SandboxProcesses(this.id, client);
1912
- this.files = new SandboxFiles(this.processes);
1949
+ this.processes = new SandboxProcesses(this);
1950
+ this.files = new SandboxFiles(this);
1913
1951
  }
1914
1952
  /** @internal Overwrite this sandbox's fields in place from a fresh wire snapshot. */
1915
1953
  _apply(data) {
@@ -1919,6 +1957,7 @@ var Sandbox = class Sandbox {
1919
1957
  this.vcpuCount = data.vcpu_count;
1920
1958
  this.memSizeMiB = data.mem_size_mib;
1921
1959
  this.baseImage = data.base_image;
1960
+ this.imageDigest = data.image_digest ?? "";
1922
1961
  this.platform = data.platform;
1923
1962
  this.maxTtlSeconds = data.max_ttl_seconds;
1924
1963
  this.idleTtlSeconds = data.idle_ttl_seconds ?? 0;
@@ -1940,6 +1979,7 @@ var Sandbox = class Sandbox {
1940
1979
  vcpuCount: this.vcpuCount,
1941
1980
  memSizeMiB: this.memSizeMiB,
1942
1981
  baseImage: this.baseImage,
1982
+ imageDigest: this.imageDigest,
1943
1983
  platform: this.platform,
1944
1984
  maxTtlSeconds: this.maxTtlSeconds,
1945
1985
  idleTtlSeconds: this.idleTtlSeconds,
@@ -1953,9 +1993,61 @@ var Sandbox = class Sandbox {
1953
1993
  checkpoint: this.checkpoint
1954
1994
  };
1955
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
+ }
1956
2048
  /** Run a process and wait for it to exit. */
1957
2049
  async exec(command, options = {}) {
1958
- return (await this.processes.start(command, options)).wait();
2050
+ return (await this.run(command, options)).wait();
1959
2051
  }
1960
2052
  /** Re-fetch this sandbox. */
1961
2053
  async refresh() {
@@ -2172,6 +2264,7 @@ var Sandboxes = class {
2172
2264
  vcpu_count: request.vcpuCount,
2173
2265
  mem_size_mib: request.memSizeMiB,
2174
2266
  base_image: request.baseImage,
2267
+ image_id: request.imageId,
2175
2268
  env: request.env,
2176
2269
  max_ttl_seconds: request.maxTtlSeconds,
2177
2270
  idle_ttl_seconds: request.idleTtlSeconds,
@@ -2196,16 +2289,16 @@ var Tokens = class {
2196
2289
  this._client = client;
2197
2290
  }
2198
2291
  async list(opts) {
2199
- return (await unwrap(this._client.GET("/api/tokens", { params: { query: {
2292
+ return (await unwrap(retryApiRequest(() => this._client.GET("/api/tokens", { params: { query: {
2200
2293
  limit: opts?.limit,
2201
2294
  cursor: opts?.cursor
2202
- } } }))).tokens ?? [];
2295
+ } } }), "transient"))).tokens ?? [];
2203
2296
  }
2204
2297
  async create(req) {
2205
- return await unwrap(this._client.POST("/api/tokens", { body: req }));
2298
+ return await unwrap(retryApiRequest(() => this._client.POST("/api/tokens", { body: req }), "connect"));
2206
2299
  }
2207
2300
  async delete(id) {
2208
- await unwrapEmpty(this._client.DELETE("/api/tokens/{tokenId}", { params: { path: { tokenId: id } } }));
2301
+ await unwrapEmpty(retryApiRequest(() => this._client.DELETE("/api/tokens/{tokenId}", { params: { path: { tokenId: id } } }), "connect"));
2209
2302
  }
2210
2303
  };
2211
2304
  //#endregion
@@ -2468,6 +2561,7 @@ function diskIdFromMount(m) {
2468
2561
  }
2469
2562
  var Archil = class {
2470
2563
  disks;
2564
+ images;
2471
2565
  sandboxes;
2472
2566
  tokens;
2473
2567
  /** @internal */
@@ -2487,6 +2581,7 @@ var Archil = class {
2487
2581
  const s3BaseUrl = opts.s3BaseUrl ?? envVar("ARCHIL_S3_BASE_URL") ?? deriveS3BaseUrl(controlBaseUrl);
2488
2582
  this._client = client;
2489
2583
  this.disks = new Disks(client, region, s3BaseUrl);
2584
+ this.images = new Images(client);
2490
2585
  this.sandboxes = new Sandboxes(client);
2491
2586
  this.tokens = new Tokens(client);
2492
2587
  }
@@ -2508,10 +2603,10 @@ var Archil = class {
2508
2603
  if (mount.checkoutPaths !== void 0) entry.checkoutPaths = mount.checkoutPaths;
2509
2604
  disks[relPath] = entry;
2510
2605
  } else disks[relPath] = diskIdFromMount(mount);
2511
- return unwrap(this._client.POST("/api/exec", { body: {
2606
+ return unwrap(retryApiRequest(() => this._client.POST("/api/exec", { body: {
2512
2607
  disks,
2513
2608
  command: opts.command
2514
- } }));
2609
+ } }), "connect"));
2515
2610
  }
2516
2611
  /**
2517
2612
  * Build an agent filesystem toolset spanning several disks at once. `mounts`
@@ -2586,6 +2681,8 @@ exports.ArchilS3Error = ArchilS3Error;
2586
2681
  exports.Disk = Disk;
2587
2682
  exports.DiskMultipart = DiskMultipart;
2588
2683
  exports.Disks = Disks;
2684
+ exports.ImageBuildError = ImageBuildError;
2685
+ exports.Images = Images;
2589
2686
  exports.Sandbox = Sandbox;
2590
2687
  exports.SandboxFileTransferError = SandboxFileTransferError;
2591
2688
  exports.SandboxFiles = SandboxFiles;