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