disk 0.10.0 → 1.0.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.
@@ -39,6 +39,17 @@ var ArchilApiError = class extends ArchilError {
39
39
  this.name = "ArchilApiError";
40
40
  }
41
41
  };
42
+ var SandboxFileTransferError = class extends ArchilError {
43
+ operation;
44
+ path;
45
+ constructor(operation, path, cause) {
46
+ super(`Sandbox file ${operation} failed for ${path}: ${cause.message}`, 500, "SANDBOX_FILE_TRANSFER_FAILED");
47
+ this.name = "SandboxFileTransferError";
48
+ this.operation = operation;
49
+ this.path = path;
50
+ this.cause = cause;
51
+ }
52
+ };
42
53
  /**
43
54
  * Error from the S3-compatible object API (getObject/putObject/deleteObject/
44
55
  * headObject/listObjects). The gateway returns an S3-style XML `<Error>` body;
@@ -111,7 +122,7 @@ function deriveS3BaseUrl(controlBaseUrl) {
111
122
  }
112
123
  //#endregion
113
124
  //#region src/version.ts
114
- const VERSION = "0.10.0";
125
+ const VERSION = "1.0.0";
115
126
  const USER_AGENT = `archil-js/${VERSION}`;
116
127
  //#endregion
117
128
  //#region src/client.ts
@@ -1155,138 +1166,501 @@ var Disks = class {
1155
1166
  }
1156
1167
  };
1157
1168
  //#endregion
1158
- //#region src/sandbox.ts
1159
- const POLL_INTERVAL_MS = 500;
1160
- function sleep() {
1161
- return new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
1162
- }
1163
- var SandboxExec = class {
1164
- sandboxId;
1165
- id;
1166
- command;
1167
- status;
1168
- exitCode;
1169
- stdout;
1170
- stderr;
1171
- exitReason;
1172
- executeTimeMs;
1173
- startedAt;
1174
- finishedAt;
1175
- /** @internal */
1169
+ //#region src/sandbox-process.ts
1170
+ const PROCESS_STDIN_CHUNK_BYTES = 1024 * 1024;
1171
+ var SandboxProcesses = class {
1172
+ _sandboxId;
1176
1173
  _client;
1177
1174
  /** @internal */
1178
- constructor(data, client) {
1175
+ constructor(sandboxId, client) {
1176
+ this._sandboxId = sandboxId;
1179
1177
  this._client = client;
1180
- this._apply(data);
1181
1178
  }
1182
- /** @internal Overwrite this exec's fields in place from a fresh wire snapshot. */
1183
- _apply(data) {
1184
- this.sandboxId = data.sandbox_id;
1185
- this.id = data.exec_id;
1186
- this.command = data.command;
1187
- this.status = data.status;
1188
- this.exitCode = data.exit_code;
1189
- this.stdout = data.stdout;
1190
- this.stderr = data.stderr;
1191
- this.exitReason = data.exit_reason;
1192
- this.executeTimeMs = data.execute_time_ms;
1193
- this.startedAt = new Date(data.started_at);
1194
- this.finishedAt = data.finished_at ? new Date(data.finished_at) : void 0;
1195
- return this;
1196
- }
1197
- toJSON() {
1198
- return {
1199
- sandboxId: this.sandboxId,
1200
- id: this.id,
1201
- command: this.command,
1202
- status: this.status,
1203
- exitCode: this.exitCode,
1204
- stdout: this.stdout,
1205
- stderr: this.stderr,
1206
- exitReason: this.exitReason,
1207
- executeTimeMs: this.executeTimeMs,
1208
- startedAt: this.startedAt,
1209
- finishedAt: this.finishedAt
1210
- };
1211
- }
1212
- /** Re-fetch this exec and update it in place, returning the same object. */
1213
- async refresh() {
1214
- const data = await unwrap(this._client.GET("/api/sandboxes/{sid}/execs/{eid}", { params: { path: {
1215
- sid: this.sandboxId,
1216
- eid: this.id
1217
- } } }));
1218
- return this._apply(data);
1219
- }
1220
- /** Cancel this exec and update it in place, returning the same object. */
1221
- async cancel() {
1222
- const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/execs/{eid}/cancel", { params: { path: {
1223
- sid: this.sandboxId,
1224
- eid: this.id
1225
- } } }));
1226
- return this._apply(data);
1179
+ async start(command, options = {}) {
1180
+ const process = new SandboxProcess("", 0, options.onOutput, options.collectOutput ?? true, () => this._connectionUrl(), (request) => this._control(request));
1181
+ const terminal = typeof options.terminal === "object" ? {
1182
+ cols: options.terminal.cols ?? 80,
1183
+ rows: options.terminal.rows ?? 24
1184
+ } : options.terminal;
1185
+ await process._connect({
1186
+ type: "start",
1187
+ command,
1188
+ terminal,
1189
+ env: options.env ?? {},
1190
+ timeout_seconds: options.timeoutSeconds
1191
+ });
1192
+ return process;
1193
+ }
1194
+ async connect(processId, options = {}) {
1195
+ const offset = options.offset ?? 0;
1196
+ const process = new SandboxProcess(processId, offset, options.onOutput, options.collectOutput ?? true, () => this._connectionUrl(), (request) => this._control(request));
1197
+ await process._connect({
1198
+ type: "attach",
1199
+ process_id: processId,
1200
+ offset
1201
+ });
1202
+ return process;
1203
+ }
1204
+ async _connectionUrl() {
1205
+ return (await unwrap(this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this._sandboxId } } }))).url;
1206
+ }
1207
+ async _control(request) {
1208
+ const socket = new WebSocket(await this._connectionUrl());
1209
+ const expected = request.type === "kill" ? "killed" : "resized";
1210
+ await new Promise((resolve, reject) => {
1211
+ socket.addEventListener("open", () => socket.send(JSON.stringify(request)), { once: true });
1212
+ socket.addEventListener("message", (message) => {
1213
+ try {
1214
+ const event = JSON.parse(message.data);
1215
+ if (event.type === "error") reject(/* @__PURE__ */ new Error(`${event.error}: ${event.message}`));
1216
+ else if (event.type !== expected) reject(/* @__PURE__ */ new Error(`Expected ${expected}, received ${event.type}`));
1217
+ else resolve();
1218
+ } catch (error) {
1219
+ reject(error);
1220
+ } finally {
1221
+ socket.close();
1222
+ }
1223
+ }, { once: true });
1224
+ socket.addEventListener("error", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} request failed`)));
1225
+ socket.addEventListener("close", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} connection closed before confirmation`)));
1226
+ });
1227
1227
  }
1228
1228
  };
1229
- var SandboxPty = class SandboxPty {
1229
+ var SandboxProcess = class {
1230
+ status = "running";
1231
+ stdout = "";
1232
+ stderr = "";
1233
+ _id;
1234
+ _cursor;
1235
+ _onOutput;
1236
+ _collectOutput;
1237
+ _connectionUrl;
1238
+ _controlProcess;
1239
+ _stdoutDecoder = new TextDecoder();
1240
+ _stderrDecoder = new TextDecoder();
1241
+ _terminal;
1242
+ _resolveTerminal;
1243
+ _result;
1230
1244
  _socket;
1231
- _completion;
1245
+ _connectionClosed;
1246
+ _connectionError;
1247
+ _stdinClosed = false;
1232
1248
  /** @internal */
1233
- constructor(socket, onData) {
1234
- this._socket = socket;
1235
- this._completion = new Promise((resolve) => {
1236
- socket.addEventListener("message", (event) => {
1237
- if (typeof event.data === "string") onData?.(event.data);
1238
- });
1239
- socket.addEventListener("close", (event) => {
1240
- const match = /^process exited with code (-?\d+)$/.exec(event.reason);
1241
- resolve({ exitCode: match ? Number(match[1]) : void 0 });
1242
- }, { once: true });
1249
+ constructor(processId, cursor, onOutput, collectOutput, connectionUrl, controlProcess) {
1250
+ this._id = processId;
1251
+ this._cursor = cursor;
1252
+ this._onOutput = onOutput;
1253
+ this._collectOutput = collectOutput;
1254
+ this._connectionUrl = connectionUrl;
1255
+ this._controlProcess = controlProcess;
1256
+ this._terminal = new Promise((resolve) => {
1257
+ this._resolveTerminal = resolve;
1243
1258
  });
1244
1259
  }
1245
- /** @internal */
1246
- static connect(url, command, options) {
1247
- return new Promise((resolve, reject) => {
1248
- const socket = new WebSocket(url);
1249
- const handleError = () => reject(/* @__PURE__ */ new Error("Interactive exec connection failed"));
1250
- socket.addEventListener("error", handleError, { once: true });
1251
- socket.addEventListener("open", () => {
1252
- socket.removeEventListener("error", handleError);
1253
- const pty = new SandboxPty(socket, options.onData);
1254
- pty._send({
1255
- type: "resize",
1256
- cols: options.cols ?? 80,
1257
- rows: options.rows ?? 24
1258
- });
1259
- const quotedCommand = `'${command.replaceAll("'", `'"'"'`)}'`;
1260
- pty._send({
1261
- type: "input",
1262
- data: `eval ${quotedCommand}; exit $?\n`
1263
- });
1264
- resolve(pty);
1265
- }, { once: true });
1266
- });
1260
+ get id() {
1261
+ return this._id;
1262
+ }
1263
+ get cursor() {
1264
+ return this._cursor;
1265
+ }
1266
+ get connected() {
1267
+ return this._socket?.readyState === WebSocket.OPEN;
1267
1268
  }
1268
1269
  async sendInput(data) {
1269
- this._send({
1270
- type: "input",
1271
- data
1272
- });
1270
+ if (this._stdinClosed) throw new Error("Process stdin is closed");
1271
+ const bytes = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
1272
+ this._sendInput(bytes);
1273
1273
  }
1274
1274
  async resize(size) {
1275
- this._send({
1275
+ if (this.status !== "running") throw new Error("Process has exited");
1276
+ await this._controlProcess({
1276
1277
  type: "resize",
1278
+ process_id: this._id,
1277
1279
  ...size
1278
1280
  });
1279
1281
  }
1280
- wait() {
1281
- return this._completion;
1282
+ /** Close stdin. Piped processes only. */
1283
+ async closeStdin() {
1284
+ if (this._stdinClosed) return;
1285
+ this._sendControl({ type: "close_stdin" });
1286
+ this._stdinClosed = true;
1287
+ }
1288
+ /** Close this client connection without terminating the process. */
1289
+ async disconnect() {
1290
+ const socket = this._socket;
1291
+ const closed = this._connectionClosed;
1292
+ if (!socket) return;
1293
+ this._socket = void 0;
1294
+ socket.close();
1295
+ await closed;
1296
+ }
1297
+ async wait() {
1298
+ if (this._result) return this._result;
1299
+ const closed = this._connectionClosed;
1300
+ if (!closed) throw new Error("Process is disconnected");
1301
+ await Promise.race([this._terminal, closed]);
1302
+ if (this._result) return this._result;
1303
+ if (this._connectionError) throw this._connectionError;
1304
+ throw new Error("Process connection closed before exit");
1305
+ }
1306
+ async kill() {
1307
+ if (this._result) return;
1308
+ await this._controlProcess({
1309
+ type: "kill",
1310
+ process_id: this._id
1311
+ });
1282
1312
  }
1283
- close() {
1284
- this._socket.close();
1313
+ /** @internal */
1314
+ async _connect(request) {
1315
+ const url = await this._connectionUrl();
1316
+ const socket = new WebSocket(url);
1317
+ socket.binaryType = "arraybuffer";
1318
+ this._socket = socket;
1319
+ let resolveClosed;
1320
+ this._connectionClosed = new Promise((resolve) => {
1321
+ resolveClosed = resolve;
1322
+ });
1323
+ let resolveReady;
1324
+ let rejectReady;
1325
+ let readySettled = false;
1326
+ const ready = new Promise((resolve, reject) => {
1327
+ resolveReady = () => {
1328
+ readySettled = true;
1329
+ resolve();
1330
+ };
1331
+ rejectReady = (error) => {
1332
+ readySettled = true;
1333
+ reject(error);
1334
+ };
1335
+ });
1336
+ const expectedReady = request.type === "start" ? "started" : "attached";
1337
+ const fail = (error) => {
1338
+ if (!readySettled) rejectReady(error instanceof Error ? error : new Error(String(error)));
1339
+ };
1340
+ socket.addEventListener("message", (message) => {
1341
+ let output;
1342
+ try {
1343
+ output = this._handleMessage(message.data, expectedReady, resolveReady);
1344
+ } catch (error) {
1345
+ const connectionError = error instanceof Error ? error : new Error(String(error));
1346
+ this._connectionError = connectionError;
1347
+ fail(connectionError);
1348
+ socket.close();
1349
+ return;
1350
+ }
1351
+ if (output) this._onOutput?.(output);
1352
+ });
1353
+ socket.addEventListener("open", () => socket.send(JSON.stringify(request)), { once: true });
1354
+ socket.addEventListener("error", () => {
1355
+ const error = /* @__PURE__ */ new Error("Process connection failed");
1356
+ this._connectionError = error;
1357
+ fail(error);
1358
+ });
1359
+ socket.addEventListener("close", () => {
1360
+ if (this._socket === socket) this._socket = void 0;
1361
+ if (!readySettled) rejectReady(/* @__PURE__ */ new Error("Process connection closed before ready"));
1362
+ resolveClosed();
1363
+ }, { once: true });
1364
+ await ready;
1365
+ }
1366
+ _openSocket() {
1367
+ if (this.status !== "running") throw new Error("Process has exited");
1368
+ if (!this._socket || this._socket.readyState !== WebSocket.OPEN) throw new Error("Process is disconnected");
1369
+ return this._socket;
1370
+ }
1371
+ _sendControl(message) {
1372
+ this._openSocket().send(JSON.stringify(message));
1373
+ }
1374
+ _sendInput(data) {
1375
+ const socket = this._openSocket();
1376
+ for (let offset = 0; offset < data.byteLength; offset += PROCESS_STDIN_CHUNK_BYTES) {
1377
+ const chunk = new Uint8Array(Math.min(PROCESS_STDIN_CHUNK_BYTES, data.byteLength - offset));
1378
+ chunk.set(data.subarray(offset, offset + chunk.byteLength));
1379
+ socket.send(chunk);
1380
+ }
1285
1381
  }
1286
- _send(message) {
1287
- this._socket.send(JSON.stringify(message));
1382
+ _handleMessage(data, expectedReady, ready) {
1383
+ if (typeof data !== "string") return this._handleOutput(data);
1384
+ const event = JSON.parse(data);
1385
+ switch (event.type) {
1386
+ case "started":
1387
+ case "attached":
1388
+ if (event.type !== expectedReady) throw new Error(`Expected ${expectedReady}, received ${event.type}`);
1389
+ if (this._id && this._id !== event.process_id) throw new Error("Runtime returned a different process ID");
1390
+ this._id = event.process_id;
1391
+ ready();
1392
+ return;
1393
+ case "exit":
1394
+ this._finish(event);
1395
+ return;
1396
+ case "error": throw /* @__PURE__ */ new Error(`${event.error}: ${event.message}`);
1397
+ }
1398
+ }
1399
+ _handleOutput(data) {
1400
+ const bytes = new Uint8Array(data);
1401
+ if (bytes.byteLength < 9 || bytes[0] !== 1 && bytes[0] !== 2) throw new Error("Invalid process output frame");
1402
+ const offset = Number(new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getBigUint64(1));
1403
+ const payload = bytes.subarray(9);
1404
+ const end = offset + payload.byteLength;
1405
+ if (end <= this._cursor) return;
1406
+ if (offset > this._cursor) {
1407
+ this._flushDecoders();
1408
+ this._cursor = offset;
1409
+ }
1410
+ const skip = Math.max(0, this._cursor - offset);
1411
+ const unread = payload.subarray(skip);
1412
+ const unreadOffset = offset + skip;
1413
+ this._cursor = end;
1414
+ const stream = bytes[0] === 1 ? "stdout" : "stderr";
1415
+ if (this._collectOutput) this._appendText(stream, (stream === "stdout" ? this._stdoutDecoder : this._stderrDecoder).decode(unread, { stream: true }));
1416
+ return {
1417
+ stream,
1418
+ offset: unreadOffset,
1419
+ data: unread
1420
+ };
1421
+ }
1422
+ _appendText(stream, data) {
1423
+ if (stream === "stdout") this.stdout += data;
1424
+ else this.stderr += data;
1425
+ }
1426
+ _flushDecoders() {
1427
+ if (!this._collectOutput) return;
1428
+ this._appendText("stdout", this._stdoutDecoder.decode());
1429
+ this._appendText("stderr", this._stderrDecoder.decode());
1430
+ }
1431
+ _finish(event) {
1432
+ if (this._result) return;
1433
+ this.status = event.status;
1434
+ this._stdinClosed = true;
1435
+ this._flushDecoders();
1436
+ this._cursor = Math.max(this._cursor, event.cursor);
1437
+ this._result = {
1438
+ status: event.status,
1439
+ exitCode: event.exit_code ?? void 0,
1440
+ exitReason: event.exit_reason ?? void 0,
1441
+ stdout: this.stdout,
1442
+ stderr: this.stderr
1443
+ };
1444
+ this._resolveTerminal(this._result);
1445
+ }
1446
+ };
1447
+ //#endregion
1448
+ //#region src/sandbox-files.ts
1449
+ const DOWNLOAD_CHUNK_BYTES = 512 * 1024;
1450
+ const UPLOAD_COMMAND = `set -eu
1451
+ mkdir -p "$ARCHIL_FILE_PARENT"
1452
+ trap 'rm -f "$ARCHIL_FILE_TEMP"' EXIT HUP INT TERM
1453
+ : > "$ARCHIL_FILE_TEMP"
1454
+ cat > "$ARCHIL_FILE_TEMP"
1455
+ chmod "$ARCHIL_FILE_MODE" "$ARCHIL_FILE_TEMP"
1456
+ mv -f "$ARCHIL_FILE_TEMP" "$ARCHIL_FILE_TARGET"
1457
+ trap - EXIT HUP INT TERM`;
1458
+ const DOWNLOAD_COMMAND = `set -eu
1459
+ trap 'rm -f "$ARCHIL_FILE_TEMP"' EXIT HUP INT TERM
1460
+ exec 3< "$ARCHIL_FILE_PATH"
1461
+ while IFS= read -r count; do
1462
+ dd bs="$count" count=1 <&3 > "$ARCHIL_FILE_TEMP" 2>/dev/null
1463
+ size=$(wc -c < "$ARCHIL_FILE_TEMP")
1464
+ printf '%s\n' "$size"
1465
+ cat "$ARCHIL_FILE_TEMP"
1466
+ [ "$size" -eq "$count" ] || break
1467
+ done`;
1468
+ var ProcessOutputReader = class {
1469
+ onOutput = (output) => {
1470
+ if (output.offset !== this._cursor) {
1471
+ this._push(/* @__PURE__ */ new Error(`Sandbox process output gap: expected offset ${this._cursor}, received ${output.offset}`));
1472
+ return;
1473
+ }
1474
+ this._cursor += output.data.byteLength;
1475
+ if (output.stream === "stdout") this._push(output.data);
1476
+ else this._stderr += this._stderrDecoder.decode(output.data, { stream: true });
1477
+ };
1478
+ _buffer = /* @__PURE__ */ new Uint8Array();
1479
+ _cursor = 0;
1480
+ _chunks = [];
1481
+ _stderrDecoder = new TextDecoder();
1482
+ _stderr = "";
1483
+ _waiting;
1484
+ _exit;
1485
+ attach(process) {
1486
+ this._exit = process.wait();
1487
+ this._exit.then((result) => {
1488
+ try {
1489
+ assertSuccessful(result, this._stderrText());
1490
+ this._push(/* @__PURE__ */ new Error("Sandbox process exited before file transfer completed"));
1491
+ } catch (error) {
1492
+ this._push(toError(error));
1493
+ }
1494
+ }, (error) => this._push(toError(error)));
1495
+ }
1496
+ async readLine() {
1497
+ while (true) {
1498
+ const newline = this._buffer.indexOf(10);
1499
+ if (newline >= 0) {
1500
+ const line = this._buffer.slice(0, newline);
1501
+ this._buffer = this._buffer.slice(newline + 1);
1502
+ return line;
1503
+ }
1504
+ this._buffer = concat(this._buffer, await this._nextChunk());
1505
+ }
1506
+ }
1507
+ async read(size) {
1508
+ while (this._buffer.byteLength < size) this._buffer = concat(this._buffer, await this._nextChunk());
1509
+ const data = this._buffer.slice(0, size);
1510
+ this._buffer = this._buffer.slice(size);
1511
+ return data;
1512
+ }
1513
+ async wait() {
1514
+ if (!this._exit) throw new Error("File transfer process has not started");
1515
+ assertSuccessful(await this._exit, this._stderrText());
1516
+ }
1517
+ _stderrText() {
1518
+ this._stderr += this._stderrDecoder.decode();
1519
+ return this._stderr;
1520
+ }
1521
+ _push(value) {
1522
+ const waiting = this._waiting;
1523
+ if (waiting) {
1524
+ this._waiting = void 0;
1525
+ waiting(value);
1526
+ } else this._chunks.push(value);
1527
+ }
1528
+ async _nextChunk() {
1529
+ const value = this._chunks.shift() ?? await new Promise((resolve) => {
1530
+ this._waiting = resolve;
1531
+ });
1532
+ if (value instanceof Error) throw value;
1533
+ return value;
1288
1534
  }
1289
1535
  };
1536
+ var SandboxFiles = class {
1537
+ _processes;
1538
+ /** @internal */
1539
+ constructor(processes) {
1540
+ this._processes = processes;
1541
+ }
1542
+ async uploadFile(source, remotePath, options = {}) {
1543
+ const { path, parent } = remoteFilePath(remotePath);
1544
+ const mode = options.mode ?? 420;
1545
+ if (!Number.isInteger(mode) || mode < 0 || mode > 4095) throw new RangeError("mode must be between 0 and 0o7777");
1546
+ let process;
1547
+ try {
1548
+ process = await this._processes.start(UPLOAD_COMMAND, { env: {
1549
+ ARCHIL_FILE_PARENT: parent,
1550
+ ARCHIL_FILE_TARGET: path,
1551
+ ARCHIL_FILE_TEMP: `${parent}/.archil-upload-${transferId()}`,
1552
+ ARCHIL_FILE_MODE: mode.toString(8)
1553
+ } });
1554
+ for await (const chunk of fileChunks(source)) await process.sendInput(chunk);
1555
+ await process.closeStdin();
1556
+ assertSuccessful(await process.wait());
1557
+ } catch (error) {
1558
+ if (process) await abort(process);
1559
+ if (error instanceof RangeError || error instanceof TypeError) throw error;
1560
+ throw new SandboxFileTransferError("upload", path, toError(error));
1561
+ } finally {
1562
+ await process?.disconnect();
1563
+ }
1564
+ }
1565
+ async downloadFile(remotePath, write) {
1566
+ const { path } = remoteFilePath(remotePath);
1567
+ const reader = new ProcessOutputReader();
1568
+ let process;
1569
+ try {
1570
+ process = await this._processes.start(DOWNLOAD_COMMAND, {
1571
+ env: {
1572
+ ARCHIL_FILE_PATH: path,
1573
+ ARCHIL_FILE_TEMP: `/tmp/.archil-download-${transferId()}`
1574
+ },
1575
+ onOutput: reader.onOutput,
1576
+ collectOutput: false
1577
+ });
1578
+ reader.attach(process);
1579
+ while (true) {
1580
+ await process.sendInput(`${DOWNLOAD_CHUNK_BYTES}\n`);
1581
+ const sizeText = new TextDecoder().decode(await reader.readLine()).trim();
1582
+ const size = Number(sizeText);
1583
+ if (!Number.isSafeInteger(size) || size < 0 || size > DOWNLOAD_CHUNK_BYTES) throw new Error(`Sandbox returned an invalid chunk size: ${JSON.stringify(sizeText)}`);
1584
+ if (size === 0) break;
1585
+ await write(await reader.read(size));
1586
+ if (size < DOWNLOAD_CHUNK_BYTES) break;
1587
+ }
1588
+ await reader.wait();
1589
+ } catch (error) {
1590
+ if (process) await abort(process);
1591
+ if (error instanceof RangeError || error instanceof TypeError) throw error;
1592
+ throw new SandboxFileTransferError("download", path, toError(error));
1593
+ } finally {
1594
+ await process?.disconnect();
1595
+ }
1596
+ }
1597
+ };
1598
+ async function* fileChunks(source) {
1599
+ if (source instanceof Uint8Array) {
1600
+ yield source;
1601
+ return;
1602
+ }
1603
+ if (source instanceof ArrayBuffer) {
1604
+ yield new Uint8Array(source);
1605
+ return;
1606
+ }
1607
+ if (source instanceof Blob) {
1608
+ yield* readableChunks(source.stream());
1609
+ return;
1610
+ }
1611
+ if (Symbol.asyncIterator in source) {
1612
+ for await (const chunk of source) yield new Uint8Array(chunk);
1613
+ return;
1614
+ }
1615
+ yield* readableChunks(source);
1616
+ }
1617
+ async function* readableChunks(source) {
1618
+ const reader = source.getReader();
1619
+ try {
1620
+ while (true) {
1621
+ const { done, value } = await reader.read();
1622
+ if (done) return;
1623
+ yield value;
1624
+ }
1625
+ } finally {
1626
+ reader.releaseLock();
1627
+ }
1628
+ }
1629
+ function remoteFilePath(path) {
1630
+ if (path.includes("\0")) throw new TypeError("remote path cannot contain NUL");
1631
+ if (!path.startsWith("/") || path.endsWith("/")) throw new TypeError("remote path must be an absolute file path");
1632
+ return {
1633
+ path,
1634
+ parent: path.slice(0, path.lastIndexOf("/")) || "/"
1635
+ };
1636
+ }
1637
+ function assertSuccessful(result, stderr = result.stderr) {
1638
+ if (result.status === "completed" && result.exitCode === 0) return;
1639
+ throw new Error(stderr.trim() || result.exitReason || `exit code ${String(result.exitCode)}`);
1640
+ }
1641
+ async function abort(process) {
1642
+ try {
1643
+ await process.kill();
1644
+ } catch {}
1645
+ }
1646
+ function transferId() {
1647
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
1648
+ }
1649
+ function concat(left, right) {
1650
+ const result = new Uint8Array(left.byteLength + right.byteLength);
1651
+ result.set(left);
1652
+ result.set(right, left.byteLength);
1653
+ return result;
1654
+ }
1655
+ function toError(error) {
1656
+ return error instanceof Error ? error : new Error(String(error));
1657
+ }
1658
+ //#endregion
1659
+ //#region src/sandbox.ts
1660
+ const POLL_INTERVAL_MS = 500;
1661
+ function sleep() {
1662
+ return new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
1663
+ }
1290
1664
  var Sandbox = class Sandbox {
1291
1665
  id;
1292
1666
  name;
@@ -1304,12 +1678,16 @@ var Sandbox = class Sandbox {
1304
1678
  lastActiveAt;
1305
1679
  expiresAt;
1306
1680
  exitReason;
1681
+ processes;
1682
+ files;
1307
1683
  /** @internal */
1308
1684
  _client;
1309
1685
  /** @internal */
1310
1686
  constructor(data, client) {
1311
1687
  this._client = client;
1312
1688
  this._apply(data);
1689
+ this.processes = new SandboxProcesses(this.id, client);
1690
+ this.files = new SandboxFiles(this.processes);
1313
1691
  }
1314
1692
  /** @internal Overwrite this sandbox's fields in place from a fresh wire snapshot. */
1315
1693
  _apply(data) {
@@ -1351,6 +1729,10 @@ var Sandbox = class Sandbox {
1351
1729
  exitReason: this.exitReason
1352
1730
  };
1353
1731
  }
1732
+ /** Run a process and wait for it to exit. */
1733
+ async exec(command, options = {}) {
1734
+ return (await this.processes.start(command, options)).wait();
1735
+ }
1354
1736
  /** Re-fetch this sandbox. */
1355
1737
  async refresh() {
1356
1738
  const data = await unwrap(this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }));
@@ -1398,57 +1780,10 @@ var Sandbox = class Sandbox {
1398
1780
  const fork = new Sandbox(data, this._client);
1399
1781
  return options.wait === false ? fork : waitForSandboxStart(fork);
1400
1782
  }
1401
- /** Create a short-lived signed WebSocket URL for an interactive shell. */
1402
- async createConnection() {
1403
- const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this.id } } }));
1404
- return {
1405
- url: data.url,
1406
- expiresAt: new Date(data.expires_at)
1407
- };
1408
- }
1409
1783
  /** Delete this sandbox and its backing disk. */
1410
1784
  async delete() {
1411
1785
  await unwrapEmpty(this._client.DELETE("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }));
1412
1786
  }
1413
- async exec(command, options = {}) {
1414
- if ("pty" in options) {
1415
- const connection = await this.createConnection();
1416
- return SandboxPty.connect(connection.url, command, options);
1417
- }
1418
- const exec = new SandboxExec(await unwrap(this._client.POST("/api/sandboxes/{sid}/execs", {
1419
- params: {
1420
- path: { sid: this.id },
1421
- query: { wait: options.wait ?? true }
1422
- },
1423
- body: {
1424
- command,
1425
- command_tty: options.commandTty,
1426
- env: options.env,
1427
- timeout_seconds: options.timeoutSeconds
1428
- }
1429
- })), this._client);
1430
- if (options.wait === false) return exec;
1431
- while (exec.status === "running") {
1432
- await sleep();
1433
- await exec.refresh();
1434
- }
1435
- return exec;
1436
- }
1437
- async listExecs() {
1438
- return ((await unwrap(this._client.GET("/api/sandboxes/{sid}/execs", { params: { path: { sid: this.id } } })))?.execs ?? []).map((exec) => new SandboxExec(exec, this._client));
1439
- }
1440
- async getExec(execId) {
1441
- return new SandboxExec(await unwrap(this._client.GET("/api/sandboxes/{sid}/execs/{eid}", { params: { path: {
1442
- sid: this.id,
1443
- eid: execId
1444
- } } })), this._client);
1445
- }
1446
- async cancelExec(execId) {
1447
- return new SandboxExec(await unwrap(this._client.POST("/api/sandboxes/{sid}/execs/{eid}/cancel", { params: { path: {
1448
- sid: this.id,
1449
- eid: execId
1450
- } } })), this._client);
1451
- }
1452
1787
  };
1453
1788
  /** @internal Continue waiting if the server returned before startup completed. */
1454
1789
  async function waitForSandboxStart(sandbox) {
@@ -1887,4 +2222,4 @@ function workspace(mounts) {
1887
2222
  return archil().workspace(mounts);
1888
2223
  }
1889
2224
  //#endregion
1890
- export { effectiveUploadPartSize as C, ArchilError as D, ArchilApiError as E, ArchilS3Error as O, DiskMultipart as S, VERSION as T, Sandbox as _, deleteApiKey as a, Disks as b, getSandbox as c, listSandboxes as d, workspace as f, Sandboxes as g, Tokens as h, createSandbox as i, 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, SandboxExec as v, USER_AGENT as w, Disk as x, SandboxPty as y };
2225
+ export { ArchilS3Error as A, DiskMultipart as C, REGION_URLS as D, VERSION as E, 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 };