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.
@@ -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.5.0";
143
+ const VERSION = "1.7.0";
134
144
  const USER_AGENT = `archil-js/${VERSION}`;
135
145
  //#endregion
136
146
  //#region src/client.ts
@@ -140,7 +150,7 @@ function isNodeRuntime() {
140
150
  }
141
151
  const undiciModule = isNodeRuntime() ? import("undici") : void 0;
142
152
  const CONTROL_PLANE_CONNECTIONS = 1;
143
- const CONTROL_PLANE_CONCURRENT_STREAMS = 100;
153
+ const IDLE_SESSION_TIMEOUT_MS = 3e4;
144
154
  function isAsyncIterableBody(body) {
145
155
  return body != null && typeof body === "object" && Symbol.asyncIterator in body;
146
156
  }
@@ -149,30 +159,12 @@ async function bufferBody(body) {
149
159
  for await (const chunk of body) chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
150
160
  return Buffer.concat(chunks);
151
161
  }
152
- const multiplexHttp2Requests = (dispatch) => (options, handler) => {
153
- let requestStarted = false;
154
- const guardedHandler = {
155
- onRequestStart(controller, context) {
156
- if (requestStarted) {
157
- controller.abort(/* @__PURE__ */ new Error("Archil control-plane requests are not replayed after a connection failure"));
158
- return;
159
- }
160
- requestStarted = true;
161
- handler.onRequestStart?.(controller, context);
162
- },
163
- onRequestUpgrade: handler.onRequestUpgrade?.bind(handler),
164
- onResponseStart: handler.onResponseStart?.bind(handler),
165
- onResponseData: handler.onResponseData?.bind(handler),
166
- onResponseEnd: handler.onResponseEnd?.bind(handler),
167
- onResponseError: handler.onResponseError?.bind(handler)
168
- };
169
- const dispatchBody = (body) => dispatch({
162
+ const bufferRequestBodies = (dispatch) => (options, handler) => {
163
+ if (!isAsyncIterableBody(options.body)) return dispatch(options, handler);
164
+ bufferBody(options.body).then((body) => dispatch({
170
165
  ...options,
171
- body,
172
- idempotent: true
173
- }, guardedHandler);
174
- if (!isAsyncIterableBody(options.body)) return dispatchBody(options.body);
175
- bufferBody(options.body).then(dispatchBody, (error) => handler.onResponseError?.({
166
+ body
167
+ }, handler), (error) => handler.onResponseError?.({
176
168
  aborted: false,
177
169
  paused: false,
178
170
  reason: null,
@@ -182,7 +174,7 @@ const multiplexHttp2Requests = (dispatch) => (options, handler) => {
182
174
  }, error instanceof Error ? error : new Error(String(error))));
183
175
  return true;
184
176
  };
185
- const sharedDispatchers = /* @__PURE__ */ new Map();
177
+ const sharedTransports = /* @__PURE__ */ new Map();
186
178
  function dispatcherKey(baseUrl, apiKey, ca) {
187
179
  return JSON.stringify([
188
180
  new URL(baseUrl).origin,
@@ -190,26 +182,27 @@ function dispatcherKey(baseUrl, apiKey, ca) {
190
182
  ca?.map((cert) => cert.toString("base64"))
191
183
  ]);
192
184
  }
193
- function getSharedDispatcher(key, ca) {
194
- const existing = sharedDispatchers.get(key);
185
+ function getSharedTransport(key, ca) {
186
+ const existing = sharedTransports.get(key);
195
187
  if (existing) return existing;
196
- const dispatcher = (async () => {
188
+ const transport = (async () => {
197
189
  if (!undiciModule) throw new Error("The pooled control-plane transport requires Node.js");
198
- const { Agent } = await undiciModule;
199
- return new Agent({
200
- allowH2: true,
201
- connections: CONTROL_PLANE_CONNECTIONS,
202
- pipelining: CONTROL_PLANE_CONCURRENT_STREAMS,
203
- keepAliveTimeout: 6e4,
204
- keepAliveMaxTimeout: 6e5,
205
- ...ca === void 0 ? {} : { connect: { ca } }
206
- }).compose(multiplexHttp2Requests);
190
+ const { Agent, fetch } = await undiciModule;
191
+ return {
192
+ fetch,
193
+ dispatcher: new Agent({
194
+ allowH2: true,
195
+ connections: CONTROL_PLANE_CONNECTIONS,
196
+ keepAliveTimeout: IDLE_SESSION_TIMEOUT_MS,
197
+ ...ca === void 0 ? {} : { connect: { ca } }
198
+ }).compose(bufferRequestBodies)
199
+ };
207
200
  })();
208
- sharedDispatchers.set(key, dispatcher);
209
- dispatcher.catch(() => {
210
- if (sharedDispatchers.get(key) === dispatcher) sharedDispatchers.delete(key);
201
+ sharedTransports.set(key, transport);
202
+ transport.catch(() => {
203
+ if (sharedTransports.get(key) === transport) sharedTransports.delete(key);
211
204
  });
212
- return dispatcher;
205
+ return transport;
213
206
  }
214
207
  function createPooledFetch(baseUrl, apiKey, tls) {
215
208
  if (!isNodeRuntime()) {
@@ -219,8 +212,16 @@ function createPooledFetch(baseUrl, apiKey, tls) {
219
212
  const ca = tls?.ca === void 0 ? void 0 : (Array.isArray(tls.ca) ? tls.ca : [tls.ca]).map((cert) => Buffer.from(cert));
220
213
  const key = dispatcherKey(baseUrl, apiKey, ca);
221
214
  return async (request) => {
222
- const dispatcher = await getSharedDispatcher(key, ca);
223
- return globalThis.fetch(request, { dispatcher });
215
+ const { fetch, dispatcher } = await getSharedTransport(key, ca);
216
+ const body = request.body === null ? null : new Uint8Array(await request.arrayBuffer());
217
+ return await fetch(request.url, {
218
+ method: request.method,
219
+ headers: [...request.headers],
220
+ body,
221
+ redirect: request.redirect,
222
+ signal: request.signal,
223
+ dispatcher
224
+ });
224
225
  };
225
226
  }
226
227
  function createApiClient(opts) {
@@ -248,8 +249,11 @@ async function unwrap(promise) {
248
249
  */
249
250
  async function unwrapPage(promise) {
250
251
  const { data: body, error, response } = await promise;
251
- if (error || !body) throw new ArchilApiError(error?.error ?? `API request failed with status ${response.status}`, response.status);
252
- 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);
253
257
  return {
254
258
  data: body.data,
255
259
  nextCursor: body.nextCursor
@@ -261,8 +265,11 @@ async function unwrapPage(promise) {
261
265
  async function unwrapEmpty(promise) {
262
266
  const { data: body, error, response } = await promise;
263
267
  if (!error && response.status === 204) return;
264
- if (error || !body) throw new ArchilApiError(error?.error ?? `API request failed with status ${response.status}`, response.status);
265
- 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);
266
273
  }
267
274
  const RETRY_BASE_MS = 100;
268
275
  const RETRY_CAP_MS = 2e3;
@@ -406,28 +413,28 @@ var Disk = class {
406
413
  };
407
414
  }
408
415
  async addUser(user) {
409
- return unwrap(this._client.POST("/api/disks/{id}/users", {
416
+ return unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/users", {
410
417
  params: { path: { id: this.id } },
411
418
  body: user
412
- }));
419
+ }), "connect"));
413
420
  }
414
421
  async removeUser(userType, identifier) {
415
- await unwrapEmpty(this._client.DELETE("/api/disks/{id}/users/{userType}", { params: {
422
+ await unwrapEmpty(retryApiRequest(() => this._client.DELETE("/api/disks/{id}/users/{userType}", { params: {
416
423
  path: {
417
424
  id: this.id,
418
425
  userType
419
426
  },
420
427
  query: { identifier }
421
- } }));
428
+ } }), "connect"));
422
429
  }
423
430
  async createToken(nickname) {
424
- const user = await unwrap(this._client.POST("/api/disks/{id}/users", {
431
+ const user = await unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/users", {
425
432
  params: { path: { id: this.id } },
426
433
  body: {
427
434
  type: "token",
428
435
  nickname
429
436
  }
430
- }));
437
+ }), "connect"));
431
438
  if (!user.token || !user.identifier) throw new Error("Server did not return a generated token");
432
439
  return user;
433
440
  }
@@ -444,7 +451,7 @@ var Disk = class {
444
451
  * absent.
445
452
  */
446
453
  async listDelegations() {
447
- return (await unwrap(this._client.GET("/api/disks/{id}/delegations", { params: { path: { id: this.id } } }))).delegations;
454
+ return (await unwrap(retryApiRequest(() => this._client.GET("/api/disks/{id}/delegations", { params: { path: { id: this.id } } }), "transient"))).delegations;
448
455
  }
449
456
  /**
450
457
  * Forcibly revoke a delegation, reclaiming write access from a client that
@@ -461,22 +468,22 @@ var Disk = class {
461
468
  */
462
469
  async revokeDelegation(delegation) {
463
470
  const { clientId, inodeId } = delegation;
464
- await unwrap(this._client.POST("/api/disks/{id}/revoke-delegation", {
471
+ await unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/revoke-delegation", {
465
472
  params: { path: { id: this.id } },
466
473
  body: {
467
474
  clientId,
468
475
  inodeId
469
476
  }
470
- }));
477
+ }), "connect"));
471
478
  }
472
479
  async getAllowedIPs() {
473
- return (await unwrap(this._client.GET("/api/disks/{id}/allowed-ips", { params: { path: { id: this.id } } }))).allowedIps;
480
+ return (await unwrap(retryApiRequest(() => this._client.GET("/api/disks/{id}/allowed-ips", { params: { path: { id: this.id } } }), "transient"))).allowedIps;
474
481
  }
475
482
  async setAllowedIPs(allowedIps) {
476
- return (await unwrap(this._client.PUT("/api/disks/{id}/allowed-ips", {
483
+ return (await unwrap(retryApiRequest(() => this._client.PUT("/api/disks/{id}/allowed-ips", {
477
484
  params: { path: { id: this.id } },
478
485
  body: { allowedIps }
479
- }))).allowedIps;
486
+ }), "transient"))).allowedIps;
480
487
  }
481
488
  async addAllowedIP(ip) {
482
489
  const current = await this.getAllowedIPs();
@@ -488,17 +495,17 @@ var Disk = class {
488
495
  return this.setAllowedIPs(current.filter((i) => i !== ip));
489
496
  }
490
497
  async delete() {
491
- await unwrapEmpty(this._client.DELETE("/api/disks/{id}", { params: { path: { id: this.id } } }));
498
+ await unwrapEmpty(retryApiRequest(() => this._client.DELETE("/api/disks/{id}", { params: { path: { id: this.id } } }), "connect"));
492
499
  }
493
500
  /**
494
501
  * Execute a command in a container with this disk mounted.
495
502
  * Blocks until the command completes and returns stdout, stderr, and exit code.
496
503
  */
497
504
  async exec(command) {
498
- return unwrap(this._client.POST("/api/disks/{id}/exec", {
505
+ return unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/exec", {
499
506
  params: { path: { id: this.id } },
500
507
  body: { command }
501
- }));
508
+ }), "connect"));
502
509
  }
503
510
  /**
504
511
  * Constant-time parallel grep across files on this disk. Listing and
@@ -511,7 +518,7 @@ var Disk = class {
511
518
  * reported first), not the lexicographically first N.
512
519
  */
513
520
  async grep(opts) {
514
- return unwrap(this._client.POST("/api/disks/{id}/grep", {
521
+ return unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/grep", {
515
522
  params: { path: { id: this.id } },
516
523
  body: {
517
524
  directory: opts.directory,
@@ -521,7 +528,7 @@ var Disk = class {
521
528
  concurrency: opts.concurrency ?? 50,
522
529
  maxResults: opts.maxResults ?? 1e3
523
530
  }
524
- }));
531
+ }), "transient"));
525
532
  }
526
533
  /**
527
534
  * Create a signed, time-limited URL that lets anyone download a single file
@@ -537,7 +544,7 @@ var Disk = class {
537
544
  const body = { key };
538
545
  if (opts.expiresIn !== void 0) body.expiresIn = opts.expiresIn;
539
546
  const call = this._client.POST;
540
- return unwrap(call(`/api/disks/${this.id}/share`, { body }));
547
+ return unwrap(retryApiRequest(() => call(`/api/disks/${this.id}/share`, { body }), "connect"));
541
548
  }
542
549
  /**
543
550
  * Read an object from the disk via the S3-compatible GetObject API and return
@@ -1265,11 +1272,11 @@ var Disks = class {
1265
1272
  * listing (it can also be persisted, e.g. across requests of a paginated UI).
1266
1273
  */
1267
1274
  async listPage(opts) {
1268
- const { data, nextCursor } = await unwrapPage(this._client.GET("/api/disks", { params: { query: {
1275
+ const { data, nextCursor } = await unwrapPage(retryApiRequest(() => this._client.GET("/api/disks", { params: { query: {
1269
1276
  limit: opts?.limit,
1270
1277
  cursor: opts?.cursor,
1271
1278
  name: opts?.name
1272
- } } }));
1279
+ } } }), "transient"));
1273
1280
  const disks = (data ?? []).map((d) => new Disk(d, this._client, this._region, this._s3BaseUrl));
1274
1281
  return nextCursor ? {
1275
1282
  disks,
@@ -1277,7 +1284,7 @@ var Disks = class {
1277
1284
  } : { disks };
1278
1285
  }
1279
1286
  async get(id) {
1280
- return new Disk(await unwrap(this._client.GET("/api/disks/{id}", { params: { path: { id } } })), this._client, this._region, this._s3BaseUrl);
1287
+ return new Disk(await unwrap(retryApiRequest(() => this._client.GET("/api/disks/{id}", { params: { path: { id } } }), "transient")), this._client, this._region, this._s3BaseUrl);
1281
1288
  }
1282
1289
  /**
1283
1290
  * Create a new disk with an auto-generated mount token.
@@ -1291,7 +1298,7 @@ var Disks = class {
1291
1298
  * Creation-time only.
1292
1299
  */
1293
1300
  async create(req) {
1294
- const resp = await unwrap(this._client.POST("/api/disks", { body: req }));
1301
+ const resp = await unwrap(retryApiRequest(() => this._client.POST("/api/disks", { body: req }), "connect"));
1295
1302
  if (!resp.diskId) throw new Error("API returned success but no diskId");
1296
1303
  const authorizedUsers = resp.authorizedUsers ?? [];
1297
1304
  const tokenUser = authorizedUsers.find((u) => u.token);
@@ -1308,10 +1315,81 @@ var Disks = class {
1308
1315
  * without fetching the disk first.
1309
1316
  */
1310
1317
  async exec(id, command) {
1311
- return unwrap(this._client.POST("/api/disks/{id}/exec", {
1318
+ return unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/exec", {
1312
1319
  params: { path: { id } },
1313
1320
  body: { command }
1314
- }));
1321
+ }), "connect"));
1322
+ }
1323
+ };
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")));
1315
1393
  }
1316
1394
  };
1317
1395
  //#endregion
@@ -1359,62 +1437,20 @@ async function openProcessSocket(connectionUrl) {
1359
1437
  await retrySleep(attempt);
1360
1438
  }
1361
1439
  }
1440
+ /** @deprecated Use Sandbox.run() and Sandbox.attach(). Removed in the next version. */
1362
1441
  var SandboxProcesses = class {
1363
- _sandboxId;
1364
- _client;
1442
+ _sandbox;
1365
1443
  /** @internal */
1366
- constructor(sandboxId, client) {
1367
- this._sandboxId = sandboxId;
1368
- this._client = client;
1369
- }
1370
- async start(command, options = {}) {
1371
- const process = new SandboxProcess("", 0, options.onOutput, options.collectOutput ?? true, () => this._connectionUrl(), (request) => this._control(request));
1372
- const terminal = typeof options.terminal === "object" ? {
1373
- cols: options.terminal.cols ?? 80,
1374
- rows: options.terminal.rows ?? 24
1375
- } : options.terminal;
1376
- await process._connect({
1377
- type: "start",
1378
- command,
1379
- terminal,
1380
- env: options.env ?? {},
1381
- timeout_seconds: options.timeoutSeconds
1382
- });
1383
- return process;
1384
- }
1385
- async connect(processId, options = {}) {
1386
- const offset = options.offset ?? 0;
1387
- const process = new SandboxProcess(processId, offset, options.onOutput, options.collectOutput ?? true, () => this._connectionUrl(), (request) => this._control(request));
1388
- await process._connect({
1389
- type: "attach",
1390
- process_id: processId,
1391
- offset
1392
- });
1393
- return process;
1444
+ constructor(_sandbox) {
1445
+ this._sandbox = _sandbox;
1394
1446
  }
1395
- async _connectionUrl() {
1396
- return (await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this._sandboxId } } }), "transient"))).url;
1447
+ /** @deprecated Use sandbox.run(). Removed in the next version. */
1448
+ start(command, options = {}) {
1449
+ return this._sandbox.run(command, options);
1397
1450
  }
1398
- async _control(request) {
1399
- const socket = await openProcessSocket(() => this._connectionUrl());
1400
- const expected = request.type === "kill" ? "killed" : "resized";
1401
- await new Promise((resolve, reject) => {
1402
- socket.addEventListener("message", (message) => {
1403
- try {
1404
- const event = JSON.parse(message.data);
1405
- if (event.type === "error") reject(/* @__PURE__ */ new Error(`${event.error}: ${event.message}`));
1406
- else if (event.type !== expected) reject(/* @__PURE__ */ new Error(`Expected ${expected}, received ${event.type}`));
1407
- else resolve();
1408
- } catch (error) {
1409
- reject(error);
1410
- } finally {
1411
- socket.close();
1412
- }
1413
- }, { once: true });
1414
- socket.addEventListener("error", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} request failed`)));
1415
- socket.addEventListener("close", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} connection closed before confirmation`)));
1416
- socket.send(JSON.stringify(request));
1417
- });
1451
+ /** @deprecated Use sandbox.attach(). Removed in the next version. */
1452
+ connect(processId, options = {}) {
1453
+ return this._sandbox.attach(processId, options);
1418
1454
  }
1419
1455
  };
1420
1456
  var SandboxProcess = class {
@@ -1724,10 +1760,10 @@ var ProcessOutputReader = class {
1724
1760
  }
1725
1761
  };
1726
1762
  var SandboxFiles = class {
1727
- _processes;
1763
+ _sandbox;
1728
1764
  /** @internal */
1729
- constructor(processes) {
1730
- this._processes = processes;
1765
+ constructor(sandbox) {
1766
+ this._sandbox = sandbox;
1731
1767
  }
1732
1768
  async uploadFile(source, remotePath, options = {}) {
1733
1769
  const { path, parent } = remoteFilePath(remotePath);
@@ -1735,7 +1771,7 @@ var SandboxFiles = class {
1735
1771
  if (!Number.isInteger(mode) || mode < 0 || mode > 4095) throw new RangeError("mode must be between 0 and 0o7777");
1736
1772
  let process;
1737
1773
  try {
1738
- process = await this._processes.start(UPLOAD_COMMAND, { env: {
1774
+ process = await this._sandbox.run(UPLOAD_COMMAND, { env: {
1739
1775
  ARCHIL_FILE_PARENT: parent,
1740
1776
  ARCHIL_FILE_TARGET: path,
1741
1777
  ARCHIL_FILE_TEMP: `${parent}/.archil-upload-${transferId()}`,
@@ -1757,7 +1793,7 @@ var SandboxFiles = class {
1757
1793
  const reader = new ProcessOutputReader();
1758
1794
  let process;
1759
1795
  try {
1760
- process = await this._processes.start(DOWNLOAD_COMMAND, {
1796
+ process = await this._sandbox.run(DOWNLOAD_COMMAND, {
1761
1797
  env: {
1762
1798
  ARCHIL_FILE_PATH: path,
1763
1799
  ARCHIL_FILE_TEMP: `/tmp/.archil-download-${transferId()}`
@@ -1866,6 +1902,7 @@ var Sandbox = class Sandbox {
1866
1902
  vcpuCount;
1867
1903
  memSizeMiB;
1868
1904
  baseImage;
1905
+ imageDigest;
1869
1906
  platform;
1870
1907
  maxTtlSeconds;
1871
1908
  idleTtlSeconds;
@@ -1877,6 +1914,7 @@ var Sandbox = class Sandbox {
1877
1914
  lastActiveAt;
1878
1915
  exitReason;
1879
1916
  checkpoint;
1917
+ /** @deprecated Use run() and attach(). Removed in the next version. */
1880
1918
  processes;
1881
1919
  files;
1882
1920
  /** @internal */
@@ -1885,8 +1923,8 @@ var Sandbox = class Sandbox {
1885
1923
  constructor(data, client) {
1886
1924
  this._client = client;
1887
1925
  this._apply(data);
1888
- this.processes = new SandboxProcesses(this.id, client);
1889
- this.files = new SandboxFiles(this.processes);
1926
+ this.processes = new SandboxProcesses(this);
1927
+ this.files = new SandboxFiles(this);
1890
1928
  }
1891
1929
  /** @internal Overwrite this sandbox's fields in place from a fresh wire snapshot. */
1892
1930
  _apply(data) {
@@ -1896,6 +1934,7 @@ var Sandbox = class Sandbox {
1896
1934
  this.vcpuCount = data.vcpu_count;
1897
1935
  this.memSizeMiB = data.mem_size_mib;
1898
1936
  this.baseImage = data.base_image;
1937
+ this.imageDigest = data.image_digest ?? "";
1899
1938
  this.platform = data.platform;
1900
1939
  this.maxTtlSeconds = data.max_ttl_seconds;
1901
1940
  this.idleTtlSeconds = data.idle_ttl_seconds ?? 0;
@@ -1917,6 +1956,7 @@ var Sandbox = class Sandbox {
1917
1956
  vcpuCount: this.vcpuCount,
1918
1957
  memSizeMiB: this.memSizeMiB,
1919
1958
  baseImage: this.baseImage,
1959
+ imageDigest: this.imageDigest,
1920
1960
  platform: this.platform,
1921
1961
  maxTtlSeconds: this.maxTtlSeconds,
1922
1962
  idleTtlSeconds: this.idleTtlSeconds,
@@ -1930,9 +1970,61 @@ var Sandbox = class Sandbox {
1930
1970
  checkpoint: this.checkpoint
1931
1971
  };
1932
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
+ }
1933
2025
  /** Run a process and wait for it to exit. */
1934
2026
  async exec(command, options = {}) {
1935
- return (await this.processes.start(command, options)).wait();
2027
+ return (await this.run(command, options)).wait();
1936
2028
  }
1937
2029
  /** Re-fetch this sandbox. */
1938
2030
  async refresh() {
@@ -2149,6 +2241,7 @@ var Sandboxes = class {
2149
2241
  vcpu_count: request.vcpuCount,
2150
2242
  mem_size_mib: request.memSizeMiB,
2151
2243
  base_image: request.baseImage,
2244
+ image_id: request.imageId,
2152
2245
  env: request.env,
2153
2246
  max_ttl_seconds: request.maxTtlSeconds,
2154
2247
  idle_ttl_seconds: request.idleTtlSeconds,
@@ -2173,16 +2266,16 @@ var Tokens = class {
2173
2266
  this._client = client;
2174
2267
  }
2175
2268
  async list(opts) {
2176
- return (await unwrap(this._client.GET("/api/tokens", { params: { query: {
2269
+ return (await unwrap(retryApiRequest(() => this._client.GET("/api/tokens", { params: { query: {
2177
2270
  limit: opts?.limit,
2178
2271
  cursor: opts?.cursor
2179
- } } }))).tokens ?? [];
2272
+ } } }), "transient"))).tokens ?? [];
2180
2273
  }
2181
2274
  async create(req) {
2182
- return await unwrap(this._client.POST("/api/tokens", { body: req }));
2275
+ return await unwrap(retryApiRequest(() => this._client.POST("/api/tokens", { body: req }), "connect"));
2183
2276
  }
2184
2277
  async delete(id) {
2185
- await unwrapEmpty(this._client.DELETE("/api/tokens/{tokenId}", { params: { path: { tokenId: id } } }));
2278
+ await unwrapEmpty(retryApiRequest(() => this._client.DELETE("/api/tokens/{tokenId}", { params: { path: { tokenId: id } } }), "connect"));
2186
2279
  }
2187
2280
  };
2188
2281
  //#endregion
@@ -2445,6 +2538,7 @@ function diskIdFromMount(m) {
2445
2538
  }
2446
2539
  var Archil = class {
2447
2540
  disks;
2541
+ images;
2448
2542
  sandboxes;
2449
2543
  tokens;
2450
2544
  /** @internal */
@@ -2464,6 +2558,7 @@ var Archil = class {
2464
2558
  const s3BaseUrl = opts.s3BaseUrl ?? envVar("ARCHIL_S3_BASE_URL") ?? deriveS3BaseUrl(controlBaseUrl);
2465
2559
  this._client = client;
2466
2560
  this.disks = new Disks(client, region, s3BaseUrl);
2561
+ this.images = new Images(client);
2467
2562
  this.sandboxes = new Sandboxes(client);
2468
2563
  this.tokens = new Tokens(client);
2469
2564
  }
@@ -2485,10 +2580,10 @@ var Archil = class {
2485
2580
  if (mount.checkoutPaths !== void 0) entry.checkoutPaths = mount.checkoutPaths;
2486
2581
  disks[relPath] = entry;
2487
2582
  } else disks[relPath] = diskIdFromMount(mount);
2488
- return unwrap(this._client.POST("/api/exec", { body: {
2583
+ return unwrap(retryApiRequest(() => this._client.POST("/api/exec", { body: {
2489
2584
  disks,
2490
2585
  command: opts.command
2491
- } }));
2586
+ } }), "connect"));
2492
2587
  }
2493
2588
  /**
2494
2589
  * Build an agent filesystem toolset spanning several disks at once. `mounts`
@@ -2556,4 +2651,4 @@ function workspace(mounts) {
2556
2651
  return archil().workspace(mounts);
2557
2652
  }
2558
2653
  //#endregion
2559
- 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 };