disk 0.8.23 → 0.10.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
@@ -134,7 +134,7 @@ function deriveS3BaseUrl(controlBaseUrl) {
134
134
  }
135
135
  //#endregion
136
136
  //#region src/version.ts
137
- const VERSION = "0.8.23";
137
+ const VERSION = "0.10.0";
138
138
  const USER_AGENT = `archil-js/${VERSION}`;
139
139
  //#endregion
140
140
  //#region src/client.ts
@@ -174,6 +174,7 @@ async function unwrapPage(promise) {
174
174
  */
175
175
  async function unwrapEmpty(promise) {
176
176
  const { data: body, error, response } = await promise;
177
+ if (!error && response.status === 204) return;
177
178
  if (error || !body) throw new ArchilApiError(error?.error ?? `API request failed with status ${response.status}`, response.status);
178
179
  if (!body.success) throw new ArchilApiError(body.error ?? "Unknown API error", response.status);
179
180
  }
@@ -189,6 +190,9 @@ var Disk = class {
189
190
  createdAt;
190
191
  fsHandlerStatus;
191
192
  lastAccessed;
193
+ activeDataBytes;
194
+ totalDataBytes;
195
+ /** @deprecated Use {@link activeDataBytes}. */
192
196
  dataSize;
193
197
  monthlyUsage;
194
198
  mounts;
@@ -196,6 +200,8 @@ var Disk = class {
196
200
  connectedClients;
197
201
  authorizedUsers;
198
202
  allowedIps;
203
+ /** Root-directory POSIX attributes recorded at creation, if any. */
204
+ rootAttrs;
199
205
  /** @internal */
200
206
  _client;
201
207
  /** @internal */
@@ -215,13 +221,16 @@ var Disk = class {
215
221
  this.createdAt = data.createdAt;
216
222
  this.fsHandlerStatus = data.fsHandlerStatus;
217
223
  this.lastAccessed = data.lastAccessed;
218
- this.dataSize = data.dataSize;
224
+ this.activeDataBytes = data.activeDataBytes;
225
+ this.totalDataBytes = data.totalDataBytes;
226
+ this.dataSize = data.activeDataBytes;
219
227
  this.monthlyUsage = data.monthlyUsage;
220
228
  this.mounts = data.mounts;
221
229
  this.metrics = data.metrics;
222
230
  this.connectedClients = data.connectedClients;
223
231
  this.authorizedUsers = data.authorizedUsers;
224
232
  this.allowedIps = data.allowedIps;
233
+ this.rootAttrs = data.rootAttrs;
225
234
  this._client = client;
226
235
  this._archilRegion = archilRegion;
227
236
  this._s3BaseUrl = s3BaseUrl ?? "";
@@ -237,13 +246,15 @@ var Disk = class {
237
246
  createdAt: this.createdAt,
238
247
  fsHandlerStatus: this.fsHandlerStatus,
239
248
  lastAccessed: this.lastAccessed,
240
- dataSize: this.dataSize,
249
+ activeDataBytes: this.activeDataBytes,
250
+ totalDataBytes: this.totalDataBytes,
241
251
  monthlyUsage: this.monthlyUsage,
242
252
  mounts: this.mounts,
243
253
  metrics: this.metrics,
244
254
  connectedClients: this.connectedClients,
245
255
  authorizedUsers: this.authorizedUsers,
246
- allowedIps: this.allowedIps
256
+ allowedIps: this.allowedIps,
257
+ rootAttrs: this.rootAttrs
247
258
  };
248
259
  }
249
260
  async addUser(user) {
@@ -431,7 +442,10 @@ var Disk = class {
431
442
  *
432
443
  * Optional `mode` / `uid` / `gid` set the POSIX attributes of the published
433
444
  * file (e.g. `{ mode: 0o644, uid: 1000, gid: 1000 }` for a non-root agent
434
- * sandbox). Defaults are server-side (currently `root:root` mode `0644`).
445
+ * sandbox). Missing parent directories inherit `uid` / `gid` with mode
446
+ * `0755`; existing directories remain unchanged. A key ending in `/` creates
447
+ * an explicit directory marker whose leaf uses the requested attributes.
448
+ * Defaults are `root:root 0644` for files and `root:root 0755` for directories.
435
449
  *
436
450
  * @param key Path on the disk (e.g. "reports/2026-01/data.json")
437
451
  * @param body Contents as a string, Uint8Array/Buffer, or ArrayBuffer
@@ -503,7 +517,8 @@ var Disk = class {
503
517
  *
504
518
  * When the object does not yet exist, optional `mode` / `uid` / `gid` set the
505
519
  * POSIX attributes of the newly created file (same headers as
506
- * {@link putObject}); they have no effect on an append to an existing object.
520
+ * {@link putObject}); missing parents inherit `uid` / `gid` with mode `0755`.
521
+ * Existing files and directories are unchanged.
507
522
  *
508
523
  * @param key Path on the disk (e.g. "logs/app.log")
509
524
  * @param body Bytes to append (string, Uint8Array/Buffer, or ArrayBuffer)
@@ -699,7 +714,7 @@ var Disk = class {
699
714
  ({error, response} = await call(path, init));
700
715
  } catch (transportError) {
701
716
  if (attempt < maxRetries) {
702
- await sleep(s3RetryDelayMs(attempt));
717
+ await sleep$1(s3RetryDelayMs(attempt));
703
718
  continue;
704
719
  }
705
720
  throw transportError;
@@ -707,7 +722,7 @@ var Disk = class {
707
722
  if (!response.ok) {
708
723
  if (isTransientS3Status(response.status) && attempt < maxRetries) {
709
724
  await response.body?.cancel().catch(() => {});
710
- await sleep(s3RetryDelayMs(attempt));
725
+ await sleep$1(s3RetryDelayMs(attempt));
711
726
  continue;
712
727
  }
713
728
  const message = typeof error === "string" ? error : error ? JSON.stringify(error) : "";
@@ -942,7 +957,7 @@ function s3RetryDelayMs(attempt) {
942
957
  const ceiling = Math.min(S3_RETRY_CAP_MS, S3_RETRY_BASE_MS * 2 ** attempt);
943
958
  return Math.random() * ceiling;
944
959
  }
945
- function sleep(ms) {
960
+ function sleep$1(ms) {
946
961
  return new Promise((resolve) => setTimeout(resolve, ms));
947
962
  }
948
963
  /** S3's minimum size for every multipart part but the last (5 MiB). */
@@ -1143,6 +1158,11 @@ var Disks = class {
1143
1158
  *
1144
1159
  * Returns the Disk, the one-time token (save it — it cannot be retrieved
1145
1160
  * again), and the token identifier for later management.
1161
+ *
1162
+ * `rootAttrs` sets the POSIX owner and mode of the disk's root directory
1163
+ * (e.g. `{ uid: 1000, gid: 1000, mode: 0o755 }` so an unprivileged process
1164
+ * can create entries under the mount root without a post-mount `chown`).
1165
+ * Creation-time only.
1146
1166
  */
1147
1167
  async create(req) {
1148
1168
  const resp = await unwrap(this._client.POST("/api/disks", { body: req }));
@@ -1157,39 +1177,12 @@ var Disks = class {
1157
1177
  };
1158
1178
  }
1159
1179
  };
1180
+ //#endregion
1181
+ //#region src/sandbox.ts
1160
1182
  const POLL_INTERVAL_MS = 500;
1161
- /** @internal */
1162
- function validateTimeoutMs(timeoutMs) {
1163
- if (!Number.isFinite(timeoutMs) || timeoutMs < 0) throw new RangeError("timeoutMs must be a finite, non-negative number");
1183
+ function sleep() {
1184
+ return new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
1164
1185
  }
1165
- /**
1166
- * The requested SDK-side wait expired. The remote sandbox operation continues;
1167
- * `latest` is the same `Sandbox`/`SandboxExec` the operation was called on,
1168
- * updated in place to the last state observed before the deadline.
1169
- */
1170
- var SandboxWaitTimeoutError = class extends ArchilError {
1171
- operation;
1172
- timeoutMs;
1173
- latest;
1174
- constructor(operation, timeoutMs, latest) {
1175
- const subject = operation === "exec" ? "sandbox exec to complete" : `sandbox to ${operation}`;
1176
- super(`Timed out after ${timeoutMs}ms waiting for ${subject}`, 408, "SANDBOX_WAIT_TIMEOUT");
1177
- this.name = "SandboxWaitTimeoutError";
1178
- this.operation = operation;
1179
- this.timeoutMs = timeoutMs;
1180
- this.latest = latest;
1181
- }
1182
- };
1183
- /** The sandbox entered an inactive state before startup completed. */
1184
- var SandboxStartError = class extends ArchilError {
1185
- latest;
1186
- constructor(sandbox) {
1187
- const detail = sandbox.exitReason ? `: ${sandbox.exitReason}` : "";
1188
- super(`Sandbox entered ${sandbox.status} before it started${detail}`, 409, "SANDBOX_START_FAILED");
1189
- this.name = "SandboxStartError";
1190
- this.latest = sandbox;
1191
- }
1192
- };
1193
1186
  var SandboxExec = class {
1194
1187
  sandboxId;
1195
1188
  id;
@@ -1256,11 +1249,75 @@ var SandboxExec = class {
1256
1249
  return this._apply(data);
1257
1250
  }
1258
1251
  };
1259
- var Sandbox = class {
1252
+ var SandboxPty = class SandboxPty {
1253
+ _socket;
1254
+ _completion;
1255
+ /** @internal */
1256
+ constructor(socket, onData) {
1257
+ this._socket = socket;
1258
+ this._completion = new Promise((resolve) => {
1259
+ socket.addEventListener("message", (event) => {
1260
+ if (typeof event.data === "string") onData?.(event.data);
1261
+ });
1262
+ socket.addEventListener("close", (event) => {
1263
+ const match = /^process exited with code (-?\d+)$/.exec(event.reason);
1264
+ resolve({ exitCode: match ? Number(match[1]) : void 0 });
1265
+ }, { once: true });
1266
+ });
1267
+ }
1268
+ /** @internal */
1269
+ static connect(url, command, options) {
1270
+ return new Promise((resolve, reject) => {
1271
+ const socket = new WebSocket(url);
1272
+ const handleError = () => reject(/* @__PURE__ */ new Error("Interactive exec connection failed"));
1273
+ socket.addEventListener("error", handleError, { once: true });
1274
+ socket.addEventListener("open", () => {
1275
+ socket.removeEventListener("error", handleError);
1276
+ const pty = new SandboxPty(socket, options.onData);
1277
+ pty._send({
1278
+ type: "resize",
1279
+ cols: options.cols ?? 80,
1280
+ rows: options.rows ?? 24
1281
+ });
1282
+ const quotedCommand = `'${command.replaceAll("'", `'"'"'`)}'`;
1283
+ pty._send({
1284
+ type: "input",
1285
+ data: `eval ${quotedCommand}; exit $?\n`
1286
+ });
1287
+ resolve(pty);
1288
+ }, { once: true });
1289
+ });
1290
+ }
1291
+ async sendInput(data) {
1292
+ this._send({
1293
+ type: "input",
1294
+ data
1295
+ });
1296
+ }
1297
+ async resize(size) {
1298
+ this._send({
1299
+ type: "resize",
1300
+ ...size
1301
+ });
1302
+ }
1303
+ wait() {
1304
+ return this._completion;
1305
+ }
1306
+ close() {
1307
+ this._socket.close();
1308
+ }
1309
+ _send(message) {
1310
+ this._socket.send(JSON.stringify(message));
1311
+ }
1312
+ };
1313
+ var Sandbox = class Sandbox {
1260
1314
  id;
1315
+ name;
1261
1316
  status;
1262
1317
  vcpuCount;
1263
1318
  memSizeMiB;
1319
+ baseImage;
1320
+ platform;
1264
1321
  maxTtlSeconds;
1265
1322
  maxConcurrentExecs;
1266
1323
  endpoints;
@@ -1280,9 +1337,12 @@ var Sandbox = class {
1280
1337
  /** @internal Overwrite this sandbox's fields in place from a fresh wire snapshot. */
1281
1338
  _apply(data) {
1282
1339
  this.id = data.sandbox_id;
1340
+ this.name = data.name;
1283
1341
  this.status = data.status;
1284
1342
  this.vcpuCount = data.vcpu_count;
1285
1343
  this.memSizeMiB = data.mem_size_mib;
1344
+ this.baseImage = data.base_image;
1345
+ this.platform = data.platform;
1286
1346
  this.maxTtlSeconds = data.max_ttl_seconds;
1287
1347
  this.maxConcurrentExecs = data.max_concurrent_execs;
1288
1348
  this.endpoints = data.endpoints?.map((endpoint) => ({ ...endpoint }));
@@ -1297,9 +1357,12 @@ var Sandbox = class {
1297
1357
  toJSON() {
1298
1358
  return {
1299
1359
  id: this.id,
1360
+ name: this.name,
1300
1361
  status: this.status,
1301
1362
  vcpuCount: this.vcpuCount,
1302
1363
  memSizeMiB: this.memSizeMiB,
1364
+ baseImage: this.baseImage,
1365
+ platform: this.platform,
1303
1366
  maxTtlSeconds: this.maxTtlSeconds,
1304
1367
  maxConcurrentExecs: this.maxConcurrentExecs,
1305
1368
  endpoints: this.endpoints?.map((endpoint) => ({ ...endpoint })),
@@ -1318,79 +1381,67 @@ var Sandbox = class {
1318
1381
  }
1319
1382
  /** Start this sandbox. */
1320
1383
  async start(options = {}) {
1321
- const timeoutMs = options.timeoutMs ?? 3e4;
1322
- validateTimeoutMs(timeoutMs);
1323
- const deadline = Date.now() + timeoutMs;
1324
1384
  const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/start", { params: {
1325
1385
  path: { sid: this.id },
1326
- query: { wait: false }
1386
+ query: { wait: options.wait ?? true }
1327
1387
  } }));
1328
1388
  this._apply(data);
1329
- return waitForSandboxStart(this, deadline, timeoutMs);
1389
+ return options.wait === false ? this : waitForSandboxStart(this);
1330
1390
  }
1331
1391
  /** Stop this sandbox. */
1332
1392
  async stop(options = {}) {
1333
- const timeoutMs = options.timeoutMs ?? 3e4;
1334
- validateTimeoutMs(timeoutMs);
1335
- const deadline = Date.now() + timeoutMs;
1336
1393
  const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/stop", { params: { path: { sid: this.id } } }));
1337
1394
  this._apply(data);
1338
- for (;;) {
1339
- if ([
1340
- "stopped",
1341
- "exited",
1342
- "failed"
1343
- ].includes(this.status)) return this;
1344
- if (this.status !== "stopping") throw new ArchilError(`Sandbox entered ${this.status} before it stopped`, 409, "SANDBOX_STOP_FAILED");
1345
- const remaining = deadline - Date.now();
1346
- if (remaining <= 0) throw new SandboxWaitTimeoutError("stop", timeoutMs, this);
1347
- await new Promise((resolve) => setTimeout(resolve, Math.min(POLL_INTERVAL_MS, remaining)));
1348
- await this.refresh();
1349
- }
1395
+ return options.wait === false ? this : waitWhileSandboxStatus(this, "stopping");
1350
1396
  }
1351
1397
  /** Pause this sandbox, preserving its CPU and memory state. */
1352
1398
  async pause(options = {}) {
1353
- const timeoutMs = options.timeoutMs ?? 3e4;
1354
- validateTimeoutMs(timeoutMs);
1355
- const deadline = Date.now() + timeoutMs;
1356
1399
  const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/pause", { params: { path: { sid: this.id } } }));
1357
1400
  this._apply(data);
1358
- for (;;) {
1359
- if (this.status === "paused") return this;
1360
- if (this.status !== "pausing") throw new ArchilError(`Sandbox entered ${this.status} before it paused`, 409, "SANDBOX_PAUSE_FAILED");
1361
- const remaining = deadline - Date.now();
1362
- if (remaining <= 0) throw new SandboxWaitTimeoutError("pause", timeoutMs, this);
1363
- await new Promise((resolve) => setTimeout(resolve, Math.min(POLL_INTERVAL_MS, remaining)));
1364
- await this.refresh();
1365
- }
1401
+ return options.wait === false ? this : waitWhileSandboxStatus(this, "pausing");
1366
1402
  }
1367
1403
  /** Resume this sandbox from its preserved CPU and memory state. */
1368
1404
  async resume(options = {}) {
1369
- const timeoutMs = options.timeoutMs ?? 3e4;
1370
- validateTimeoutMs(timeoutMs);
1371
- const deadline = Date.now() + timeoutMs;
1372
1405
  const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/resume", { params: {
1373
1406
  path: { sid: this.id },
1374
- query: { wait: false }
1407
+ query: { wait: options.wait ?? true }
1375
1408
  } }));
1376
1409
  this._apply(data);
1377
- for (;;) {
1378
- if (this.status === "running") return this;
1379
- if (this.status !== "pending") throw new ArchilError(`Sandbox entered ${this.status} before it resumed`, 409, "SANDBOX_RESUME_FAILED");
1380
- const remaining = deadline - Date.now();
1381
- if (remaining <= 0) throw new SandboxWaitTimeoutError("resume", timeoutMs, this);
1382
- await new Promise((resolve) => setTimeout(resolve, Math.min(POLL_INTERVAL_MS, remaining)));
1383
- await this.refresh();
1384
- }
1410
+ return options.wait === false ? this : waitForSandboxStart(this);
1411
+ }
1412
+ /** Create an isolated writable branch from this sandbox's current state. */
1413
+ async fork(options = {}) {
1414
+ const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/fork", {
1415
+ params: {
1416
+ path: { sid: this.id },
1417
+ query: { wait: options.wait ?? true }
1418
+ },
1419
+ body: options.name === void 0 ? void 0 : { name: options.name }
1420
+ }));
1421
+ const fork = new Sandbox(data, this._client);
1422
+ return options.wait === false ? fork : waitForSandboxStart(fork);
1423
+ }
1424
+ /** Create a short-lived signed WebSocket URL for an interactive shell. */
1425
+ async createConnection() {
1426
+ const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this.id } } }));
1427
+ return {
1428
+ url: data.url,
1429
+ expiresAt: new Date(data.expires_at)
1430
+ };
1431
+ }
1432
+ /** Delete this sandbox and its backing disk. */
1433
+ async delete() {
1434
+ await unwrapEmpty(this._client.DELETE("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }));
1385
1435
  }
1386
1436
  async exec(command, options = {}) {
1387
- const timeoutMs = options.timeoutMs ?? 3e4;
1388
- validateTimeoutMs(timeoutMs);
1389
- const deadline = Date.now() + timeoutMs;
1437
+ if ("pty" in options) {
1438
+ const connection = await this.createConnection();
1439
+ return SandboxPty.connect(connection.url, command, options);
1440
+ }
1390
1441
  const exec = new SandboxExec(await unwrap(this._client.POST("/api/sandboxes/{sid}/execs", {
1391
1442
  params: {
1392
1443
  path: { sid: this.id },
1393
- query: { wait: false }
1444
+ query: { wait: options.wait ?? true }
1394
1445
  },
1395
1446
  body: {
1396
1447
  command,
@@ -1399,14 +1450,12 @@ var Sandbox = class {
1399
1450
  timeout_seconds: options.timeoutSeconds
1400
1451
  }
1401
1452
  })), this._client);
1402
- if (exec.status !== "running") return exec;
1403
- for (;;) {
1404
- const remaining = deadline - Date.now();
1405
- if (remaining <= 0) throw new SandboxWaitTimeoutError("exec", timeoutMs, exec);
1406
- await new Promise((resolve) => setTimeout(resolve, Math.min(POLL_INTERVAL_MS, remaining)));
1453
+ if (options.wait === false) return exec;
1454
+ while (exec.status === "running") {
1455
+ await sleep();
1407
1456
  await exec.refresh();
1408
- if (exec.status !== "running") return exec;
1409
1457
  }
1458
+ return exec;
1410
1459
  }
1411
1460
  async listExecs() {
1412
1461
  return ((await unwrap(this._client.GET("/api/sandboxes/{sid}/execs", { params: { path: { sid: this.id } } })))?.execs ?? []).map((exec) => new SandboxExec(exec, this._client));
@@ -1424,16 +1473,16 @@ var Sandbox = class {
1424
1473
  } } })), this._client);
1425
1474
  }
1426
1475
  };
1427
- /** @internal Poll `sandbox` in place until it is running (or the deadline passes). */
1428
- async function waitForSandboxStart(sandbox, deadline, timeoutMs) {
1429
- for (;;) {
1430
- if (sandbox.status === "running") return sandbox;
1431
- if (sandbox.status !== "pending") throw new SandboxStartError(sandbox);
1432
- const remaining = deadline - Date.now();
1433
- if (remaining <= 0) throw new SandboxWaitTimeoutError("start", timeoutMs, sandbox);
1434
- await new Promise((resolve) => setTimeout(resolve, Math.min(POLL_INTERVAL_MS, remaining)));
1476
+ /** @internal Continue waiting if the server returned before startup completed. */
1477
+ async function waitForSandboxStart(sandbox) {
1478
+ return waitWhileSandboxStatus(sandbox, "pending");
1479
+ }
1480
+ async function waitWhileSandboxStatus(sandbox, status) {
1481
+ while (sandbox.status === status) {
1482
+ await sleep();
1435
1483
  await sandbox.refresh();
1436
1484
  }
1485
+ return sandbox;
1437
1486
  }
1438
1487
  //#endregion
1439
1488
  //#region src/sandboxes.ts
@@ -1453,10 +1502,8 @@ var Sandboxes = class {
1453
1502
  return new Sandbox(await unwrap(this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: id } } })), this._client);
1454
1503
  }
1455
1504
  async create(request = {}, options = {}) {
1456
- const timeoutMs = options.timeoutMs ?? 3e4;
1457
- validateTimeoutMs(timeoutMs);
1458
- const deadline = Date.now() + timeoutMs;
1459
1505
  const body = {
1506
+ name: request.name,
1460
1507
  vcpu_count: request.vcpuCount,
1461
1508
  mem_size_mib: request.memSizeMiB,
1462
1509
  base_image: request.baseImage,
@@ -1464,10 +1511,11 @@ var Sandboxes = class {
1464
1511
  max_ttl_seconds: request.maxTtlSeconds,
1465
1512
  max_concurrent_execs: request.maxConcurrentExecs
1466
1513
  };
1467
- return waitForSandboxStart(new Sandbox(await unwrap(this._client.POST("/api/sandboxes", {
1468
- params: { query: { wait: false } },
1514
+ const sandbox = new Sandbox(await unwrap(this._client.POST("/api/sandboxes", {
1515
+ params: { query: { wait: options.wait ?? true } },
1469
1516
  body
1470
- })), this._client), deadline, timeoutMs);
1517
+ })), this._client);
1518
+ return options.wait === false ? sandbox : waitForSandboxStart(sandbox);
1471
1519
  }
1472
1520
  };
1473
1521
  //#endregion
@@ -1871,8 +1919,7 @@ exports.DiskMultipart = DiskMultipart;
1871
1919
  exports.Disks = Disks;
1872
1920
  exports.Sandbox = Sandbox;
1873
1921
  exports.SandboxExec = SandboxExec;
1874
- exports.SandboxStartError = SandboxStartError;
1875
- exports.SandboxWaitTimeoutError = SandboxWaitTimeoutError;
1922
+ exports.SandboxPty = SandboxPty;
1876
1923
  exports.Sandboxes = Sandboxes;
1877
1924
  exports.Tokens = Tokens;
1878
1925
  exports.USER_AGENT = USER_AGENT;