disk 0.8.23 → 0.9.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/README.md CHANGED
@@ -83,23 +83,38 @@ const client = new archil.Archil({
83
83
  apiKey: process.env.ARCHIL_API_KEY,
84
84
  region: "aws-us-east-1",
85
85
  });
86
- const sandbox = await client.sandboxes.create({ vcpuCount: 2, memSizeMiB: 4096 });
86
+ const sandbox = await client.sandboxes.create({
87
+ name: "prepared-environment",
88
+ vcpuCount: 4,
89
+ memSizeMiB: 8192,
90
+ });
87
91
 
88
92
  const result = await sandbox.exec("uname -a");
89
93
  console.log(result.stdout);
90
94
 
91
- await sandbox.stop();
92
95
  await sandbox.start();
93
- await sandbox.pause();
94
96
  await sandbox.resume();
95
97
 
98
+ // Return the initial state immediately instead of waiting for completion.
99
+ const runningExec = await sandbox.exec("sleep 60", { wait: false });
100
+
101
+ await sandbox.stop();
102
+ const fork = await sandbox.fork({ name: "agent-task" });
103
+ const connection = await fork.createConnection();
104
+ await fork.stop();
105
+ await fork.delete();
106
+
96
107
  const all = await client.sandboxes.list();
97
108
  const usingDisk = await client.sandboxes.list({ disk: "dsk-abc123" });
98
109
  ```
99
110
 
100
- `create`, `start`, `stop`, `pause`, `resume`, and `exec` wait up to 30 seconds by default.
101
- Set `timeoutMs` to change the limit. A `SandboxWaitTimeoutError` includes the latest
102
- resource state.
111
+ Sandboxes support 1–32 vCPUs and 256–65,536 MiB of memory. When omitted,
112
+ `vcpuCount` defaults to 1 and `memSizeMiB` defaults to 2,048 MiB.
113
+
114
+ `create`, `start`, `stop`, `pause`, `resume`, `fork`, and `exec` wait for
115
+ completion by default. The server handles the initial wait; if its wait budget
116
+ expires first, the SDK continues polling. Pass `{ wait: false }` to return as
117
+ soon as the operation is accepted.
103
118
 
104
119
  API keys live at the account level, so those helpers are top-level:
105
120
 
@@ -134,6 +149,49 @@ if (await d.objectExists("reports/2026-01/data.json")) { /* … */ }
134
149
  await d.deleteObject("reports/2026-01/data.json");
135
150
  ```
136
151
 
152
+ #### POSIX ownership and directories
153
+
154
+ Pass `uid`, `gid`, and `mode` when the files will be used by a non-root process:
155
+
156
+ ```ts
157
+ await d.putObject("path/a/b/file.txt", "hello", {
158
+ uid: 1000,
159
+ gid: 1001,
160
+ mode: 0o640,
161
+ });
162
+ ```
163
+
164
+ If `path/` already exists as `2000:2000 0700` and `a/` and `b/` are missing,
165
+ the resulting tree is:
166
+
167
+ | Path | Owner | Mode | Result |
168
+ | --- | --- | --- | --- |
169
+ | `path/` | `2000:2000` | `0700` | Existing directory; unchanged |
170
+ | `path/a/` | `1000:1001` | `0755` | Implicit parent created by the upload |
171
+ | `path/a/b/` | `1000:1001` | `0755` | Implicit parent created by the upload |
172
+ | `path/a/b/file.txt` | `1000:1001` | `0640` | Published file with the requested attributes |
173
+
174
+ The requested file mode never applies to implicit parents; they use `0755` so
175
+ they remain traversable. Existing directories are never re-owned or re-moded,
176
+ so in this example a FUSE process running as uid 1000 still cannot traverse the
177
+ pre-existing `path/` directory.
178
+
179
+ Create an explicit directory by putting an empty directory-marker key ending in
180
+ `/`:
181
+
182
+ ```ts
183
+ await d.putObject("path/a/private/", "", {
184
+ uid: 4000,
185
+ gid: 4001,
186
+ mode: 0o750,
187
+ });
188
+ ```
189
+
190
+ This creates `private/` as `4000:4001 0750`. If the marker already exists, its
191
+ attributes are unchanged. When attributes are omitted, files default to
192
+ `root:root 0644` and directories to `root:root 0755`. Automatic multipart
193
+ uploads and append-created files use the same directory rules.
194
+
137
195
  `listObjects` auto-paginates by default, returning every matching key. The first
138
196
  argument is a key prefix; a non-recursive listing (the default) returns the
139
197
  immediate level as `objects` plus subdirectory `commonPrefixes`:
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { D as ArchilApiError, a as deleteApiKey, l as listApiKeys, n as createApiKey, r as createDisk, s as getDisk, t as configure, u as listDisks } from "./src-DgL0HTS-.mjs";
2
+ import { E as ArchilApiError, a as deleteApiKey, l as listApiKeys, n as createApiKey, r as createDisk, s as getDisk, t as configure, u as listDisks } from "./src-CR3Ksi_s.mjs";
3
3
  import { createRequire } from "node:module";
4
4
  import { Command, Option } from "commander";
5
5
  //#region bin/cli.ts
@@ -80,7 +80,8 @@ function printDisk(d) {
80
80
  ["region", d.region],
81
81
  ["created", d.createdAt],
82
82
  ["last accessed", d.lastAccessed],
83
- ["data size", formatBytes(d.dataSize)],
83
+ ["active data", formatBytes(d.activeDataBytes)],
84
+ ["total data", formatBytes(d.totalDataBytes)],
84
85
  ["monthly usage", d.monthlyUsage]
85
86
  ].filter(([, v]) => v !== void 0 && v !== null && v !== "").map(([k, v]) => [k, String(v)]);
86
87
  console.log("");
@@ -308,11 +308,13 @@ interface DeleteObjectsResult {
308
308
  }
309
309
  /**
310
310
  * POSIX attributes to set on a newly created object, sent to the S3 gateway as
311
- * `x-archil-*` headers. All optional — anything omitted falls back to the
312
- * server-side defaults (currently `root:root`, mode `0644`).
311
+ * `x-archil-*` headers. Missing parent directories inherit `uid` / `gid` and
312
+ * use mode `0755`; existing directories are unchanged. All fields are optional
313
+ * — new files default to `root:root 0644`, while directory markers default to
314
+ * `root:root 0755`.
313
315
  */
314
316
  interface PosixCreateAttrs {
315
- /** POSIX mode bits for the created file, e.g. `0o644`. Sent in octal. */
317
+ /** POSIX mode bits for the created file or directory marker. Sent in octal. */
316
318
  mode?: number;
317
319
  /** Owning user id, e.g. `1000`. */
318
320
  uid?: number;
@@ -372,6 +374,9 @@ declare class Disk implements FileSystem {
372
374
  readonly createdAt: string;
373
375
  readonly fsHandlerStatus?: string;
374
376
  readonly lastAccessed?: string;
377
+ readonly activeDataBytes?: number;
378
+ readonly totalDataBytes?: number;
379
+ /** @deprecated Use {@link activeDataBytes}. */
375
380
  readonly dataSize?: number;
376
381
  readonly monthlyUsage?: string;
377
382
  readonly mounts?: MountResponse[];
@@ -487,7 +492,10 @@ declare class Disk implements FileSystem {
487
492
  *
488
493
  * Optional `mode` / `uid` / `gid` set the POSIX attributes of the published
489
494
  * file (e.g. `{ mode: 0o644, uid: 1000, gid: 1000 }` for a non-root agent
490
- * sandbox). Defaults are server-side (currently `root:root` mode `0644`).
495
+ * sandbox). Missing parent directories inherit `uid` / `gid` with mode
496
+ * `0755`; existing directories remain unchanged. A key ending in `/` creates
497
+ * an explicit directory marker whose leaf uses the requested attributes.
498
+ * Defaults are `root:root 0644` for files and `root:root 0755` for directories.
491
499
  *
492
500
  * @param key Path on the disk (e.g. "reports/2026-01/data.json")
493
501
  * @param body Contents as a string, Uint8Array/Buffer, or ArrayBuffer
@@ -520,7 +528,8 @@ declare class Disk implements FileSystem {
520
528
  *
521
529
  * When the object does not yet exist, optional `mode` / `uid` / `gid` set the
522
530
  * POSIX attributes of the newly created file (same headers as
523
- * {@link putObject}); they have no effect on an append to an existing object.
531
+ * {@link putObject}); missing parents inherit `uid` / `gid` with mode `0755`.
532
+ * Existing files and directories are unchanged.
524
533
  *
525
534
  * @param key Path on the disk (e.g. "logs/app.log")
526
535
  * @param body Bytes to append (string, Uint8Array/Buffer, or ArrayBuffer)
@@ -308,11 +308,13 @@ interface DeleteObjectsResult {
308
308
  }
309
309
  /**
310
310
  * POSIX attributes to set on a newly created object, sent to the S3 gateway as
311
- * `x-archil-*` headers. All optional — anything omitted falls back to the
312
- * server-side defaults (currently `root:root`, mode `0644`).
311
+ * `x-archil-*` headers. Missing parent directories inherit `uid` / `gid` and
312
+ * use mode `0755`; existing directories are unchanged. All fields are optional
313
+ * — new files default to `root:root 0644`, while directory markers default to
314
+ * `root:root 0755`.
313
315
  */
314
316
  interface PosixCreateAttrs {
315
- /** POSIX mode bits for the created file, e.g. `0o644`. Sent in octal. */
317
+ /** POSIX mode bits for the created file or directory marker. Sent in octal. */
316
318
  mode?: number;
317
319
  /** Owning user id, e.g. `1000`. */
318
320
  uid?: number;
@@ -372,6 +374,9 @@ declare class Disk implements FileSystem {
372
374
  readonly createdAt: string;
373
375
  readonly fsHandlerStatus?: string;
374
376
  readonly lastAccessed?: string;
377
+ readonly activeDataBytes?: number;
378
+ readonly totalDataBytes?: number;
379
+ /** @deprecated Use {@link activeDataBytes}. */
375
380
  readonly dataSize?: number;
376
381
  readonly monthlyUsage?: string;
377
382
  readonly mounts?: MountResponse[];
@@ -487,7 +492,10 @@ declare class Disk implements FileSystem {
487
492
  *
488
493
  * Optional `mode` / `uid` / `gid` set the POSIX attributes of the published
489
494
  * file (e.g. `{ mode: 0o644, uid: 1000, gid: 1000 }` for a non-root agent
490
- * sandbox). Defaults are server-side (currently `root:root` mode `0644`).
495
+ * sandbox). Missing parent directories inherit `uid` / `gid` with mode
496
+ * `0755`; existing directories remain unchanged. A key ending in `/` creates
497
+ * an explicit directory marker whose leaf uses the requested attributes.
498
+ * Defaults are `root:root 0644` for files and `root:root 0755` for directories.
491
499
  *
492
500
  * @param key Path on the disk (e.g. "reports/2026-01/data.json")
493
501
  * @param body Contents as a string, Uint8Array/Buffer, or ArrayBuffer
@@ -520,7 +528,8 @@ declare class Disk implements FileSystem {
520
528
  *
521
529
  * When the object does not yet exist, optional `mode` / `uid` / `gid` set the
522
530
  * POSIX attributes of the newly created file (same headers as
523
- * {@link putObject}); they have no effect on an append to an existing object.
531
+ * {@link putObject}); missing parents inherit `uid` / `gid` with mode `0755`.
532
+ * Existing files and directories are unchanged.
524
533
  *
525
534
  * @param key Path on the disk (e.g. "logs/app.log")
526
535
  * @param body Bytes to append (string, Uint8Array/Buffer, or ArrayBuffer)
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.9.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;
@@ -215,7 +219,9 @@ var Disk = class {
215
219
  this.createdAt = data.createdAt;
216
220
  this.fsHandlerStatus = data.fsHandlerStatus;
217
221
  this.lastAccessed = data.lastAccessed;
218
- this.dataSize = data.dataSize;
222
+ this.activeDataBytes = data.activeDataBytes;
223
+ this.totalDataBytes = data.totalDataBytes;
224
+ this.dataSize = data.activeDataBytes;
219
225
  this.monthlyUsage = data.monthlyUsage;
220
226
  this.mounts = data.mounts;
221
227
  this.metrics = data.metrics;
@@ -237,7 +243,8 @@ var Disk = class {
237
243
  createdAt: this.createdAt,
238
244
  fsHandlerStatus: this.fsHandlerStatus,
239
245
  lastAccessed: this.lastAccessed,
240
- dataSize: this.dataSize,
246
+ activeDataBytes: this.activeDataBytes,
247
+ totalDataBytes: this.totalDataBytes,
241
248
  monthlyUsage: this.monthlyUsage,
242
249
  mounts: this.mounts,
243
250
  metrics: this.metrics,
@@ -431,7 +438,10 @@ var Disk = class {
431
438
  *
432
439
  * Optional `mode` / `uid` / `gid` set the POSIX attributes of the published
433
440
  * 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`).
441
+ * sandbox). Missing parent directories inherit `uid` / `gid` with mode
442
+ * `0755`; existing directories remain unchanged. A key ending in `/` creates
443
+ * an explicit directory marker whose leaf uses the requested attributes.
444
+ * Defaults are `root:root 0644` for files and `root:root 0755` for directories.
435
445
  *
436
446
  * @param key Path on the disk (e.g. "reports/2026-01/data.json")
437
447
  * @param body Contents as a string, Uint8Array/Buffer, or ArrayBuffer
@@ -503,7 +513,8 @@ var Disk = class {
503
513
  *
504
514
  * When the object does not yet exist, optional `mode` / `uid` / `gid` set the
505
515
  * POSIX attributes of the newly created file (same headers as
506
- * {@link putObject}); they have no effect on an append to an existing object.
516
+ * {@link putObject}); missing parents inherit `uid` / `gid` with mode `0755`.
517
+ * Existing files and directories are unchanged.
507
518
  *
508
519
  * @param key Path on the disk (e.g. "logs/app.log")
509
520
  * @param body Bytes to append (string, Uint8Array/Buffer, or ArrayBuffer)
@@ -699,7 +710,7 @@ var Disk = class {
699
710
  ({error, response} = await call(path, init));
700
711
  } catch (transportError) {
701
712
  if (attempt < maxRetries) {
702
- await sleep(s3RetryDelayMs(attempt));
713
+ await sleep$1(s3RetryDelayMs(attempt));
703
714
  continue;
704
715
  }
705
716
  throw transportError;
@@ -707,7 +718,7 @@ var Disk = class {
707
718
  if (!response.ok) {
708
719
  if (isTransientS3Status(response.status) && attempt < maxRetries) {
709
720
  await response.body?.cancel().catch(() => {});
710
- await sleep(s3RetryDelayMs(attempt));
721
+ await sleep$1(s3RetryDelayMs(attempt));
711
722
  continue;
712
723
  }
713
724
  const message = typeof error === "string" ? error : error ? JSON.stringify(error) : "";
@@ -942,7 +953,7 @@ function s3RetryDelayMs(attempt) {
942
953
  const ceiling = Math.min(S3_RETRY_CAP_MS, S3_RETRY_BASE_MS * 2 ** attempt);
943
954
  return Math.random() * ceiling;
944
955
  }
945
- function sleep(ms) {
956
+ function sleep$1(ms) {
946
957
  return new Promise((resolve) => setTimeout(resolve, ms));
947
958
  }
948
959
  /** S3's minimum size for every multipart part but the last (5 MiB). */
@@ -1157,39 +1168,12 @@ var Disks = class {
1157
1168
  };
1158
1169
  }
1159
1170
  };
1171
+ //#endregion
1172
+ //#region src/sandbox.ts
1160
1173
  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");
1174
+ function sleep() {
1175
+ return new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
1164
1176
  }
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
1177
  var SandboxExec = class {
1194
1178
  sandboxId;
1195
1179
  id;
@@ -1256,11 +1240,75 @@ var SandboxExec = class {
1256
1240
  return this._apply(data);
1257
1241
  }
1258
1242
  };
1259
- var Sandbox = class {
1243
+ var SandboxPty = class SandboxPty {
1244
+ _socket;
1245
+ _completion;
1246
+ /** @internal */
1247
+ constructor(socket, onData) {
1248
+ this._socket = socket;
1249
+ this._completion = new Promise((resolve) => {
1250
+ socket.addEventListener("message", (event) => {
1251
+ if (typeof event.data === "string") onData?.(event.data);
1252
+ });
1253
+ socket.addEventListener("close", (event) => {
1254
+ const match = /^process exited with code (-?\d+)$/.exec(event.reason);
1255
+ resolve({ exitCode: match ? Number(match[1]) : void 0 });
1256
+ }, { once: true });
1257
+ });
1258
+ }
1259
+ /** @internal */
1260
+ static connect(url, command, options) {
1261
+ return new Promise((resolve, reject) => {
1262
+ const socket = new WebSocket(url);
1263
+ const handleError = () => reject(/* @__PURE__ */ new Error("Interactive exec connection failed"));
1264
+ socket.addEventListener("error", handleError, { once: true });
1265
+ socket.addEventListener("open", () => {
1266
+ socket.removeEventListener("error", handleError);
1267
+ const pty = new SandboxPty(socket, options.onData);
1268
+ pty._send({
1269
+ type: "resize",
1270
+ cols: options.cols ?? 80,
1271
+ rows: options.rows ?? 24
1272
+ });
1273
+ const quotedCommand = `'${command.replaceAll("'", `'"'"'`)}'`;
1274
+ pty._send({
1275
+ type: "input",
1276
+ data: `eval ${quotedCommand}; exit $?\n`
1277
+ });
1278
+ resolve(pty);
1279
+ }, { once: true });
1280
+ });
1281
+ }
1282
+ async sendInput(data) {
1283
+ this._send({
1284
+ type: "input",
1285
+ data
1286
+ });
1287
+ }
1288
+ async resize(size) {
1289
+ this._send({
1290
+ type: "resize",
1291
+ ...size
1292
+ });
1293
+ }
1294
+ wait() {
1295
+ return this._completion;
1296
+ }
1297
+ close() {
1298
+ this._socket.close();
1299
+ }
1300
+ _send(message) {
1301
+ this._socket.send(JSON.stringify(message));
1302
+ }
1303
+ };
1304
+ var Sandbox = class Sandbox {
1260
1305
  id;
1306
+ name;
1261
1307
  status;
1262
1308
  vcpuCount;
1263
1309
  memSizeMiB;
1310
+ baseImage;
1311
+ platform;
1264
1312
  maxTtlSeconds;
1265
1313
  maxConcurrentExecs;
1266
1314
  endpoints;
@@ -1280,9 +1328,12 @@ var Sandbox = class {
1280
1328
  /** @internal Overwrite this sandbox's fields in place from a fresh wire snapshot. */
1281
1329
  _apply(data) {
1282
1330
  this.id = data.sandbox_id;
1331
+ this.name = data.name;
1283
1332
  this.status = data.status;
1284
1333
  this.vcpuCount = data.vcpu_count;
1285
1334
  this.memSizeMiB = data.mem_size_mib;
1335
+ this.baseImage = data.base_image;
1336
+ this.platform = data.platform;
1286
1337
  this.maxTtlSeconds = data.max_ttl_seconds;
1287
1338
  this.maxConcurrentExecs = data.max_concurrent_execs;
1288
1339
  this.endpoints = data.endpoints?.map((endpoint) => ({ ...endpoint }));
@@ -1297,9 +1348,12 @@ var Sandbox = class {
1297
1348
  toJSON() {
1298
1349
  return {
1299
1350
  id: this.id,
1351
+ name: this.name,
1300
1352
  status: this.status,
1301
1353
  vcpuCount: this.vcpuCount,
1302
1354
  memSizeMiB: this.memSizeMiB,
1355
+ baseImage: this.baseImage,
1356
+ platform: this.platform,
1303
1357
  maxTtlSeconds: this.maxTtlSeconds,
1304
1358
  maxConcurrentExecs: this.maxConcurrentExecs,
1305
1359
  endpoints: this.endpoints?.map((endpoint) => ({ ...endpoint })),
@@ -1318,79 +1372,67 @@ var Sandbox = class {
1318
1372
  }
1319
1373
  /** Start this sandbox. */
1320
1374
  async start(options = {}) {
1321
- const timeoutMs = options.timeoutMs ?? 3e4;
1322
- validateTimeoutMs(timeoutMs);
1323
- const deadline = Date.now() + timeoutMs;
1324
1375
  const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/start", { params: {
1325
1376
  path: { sid: this.id },
1326
- query: { wait: false }
1377
+ query: { wait: options.wait ?? true }
1327
1378
  } }));
1328
1379
  this._apply(data);
1329
- return waitForSandboxStart(this, deadline, timeoutMs);
1380
+ return options.wait === false ? this : waitForSandboxStart(this);
1330
1381
  }
1331
1382
  /** Stop this sandbox. */
1332
1383
  async stop(options = {}) {
1333
- const timeoutMs = options.timeoutMs ?? 3e4;
1334
- validateTimeoutMs(timeoutMs);
1335
- const deadline = Date.now() + timeoutMs;
1336
1384
  const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/stop", { params: { path: { sid: this.id } } }));
1337
1385
  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
- }
1386
+ return options.wait === false ? this : waitWhileSandboxStatus(this, "stopping");
1350
1387
  }
1351
1388
  /** Pause this sandbox, preserving its CPU and memory state. */
1352
1389
  async pause(options = {}) {
1353
- const timeoutMs = options.timeoutMs ?? 3e4;
1354
- validateTimeoutMs(timeoutMs);
1355
- const deadline = Date.now() + timeoutMs;
1356
1390
  const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/pause", { params: { path: { sid: this.id } } }));
1357
1391
  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
- }
1392
+ return options.wait === false ? this : waitWhileSandboxStatus(this, "pausing");
1366
1393
  }
1367
1394
  /** Resume this sandbox from its preserved CPU and memory state. */
1368
1395
  async resume(options = {}) {
1369
- const timeoutMs = options.timeoutMs ?? 3e4;
1370
- validateTimeoutMs(timeoutMs);
1371
- const deadline = Date.now() + timeoutMs;
1372
1396
  const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/resume", { params: {
1373
1397
  path: { sid: this.id },
1374
- query: { wait: false }
1398
+ query: { wait: options.wait ?? true }
1375
1399
  } }));
1376
1400
  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
- }
1401
+ return options.wait === false ? this : waitForSandboxStart(this);
1402
+ }
1403
+ /** Create an isolated writable branch from this sandbox's current state. */
1404
+ async fork(options = {}) {
1405
+ const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/fork", {
1406
+ params: {
1407
+ path: { sid: this.id },
1408
+ query: { wait: options.wait ?? true }
1409
+ },
1410
+ body: options.name === void 0 ? void 0 : { name: options.name }
1411
+ }));
1412
+ const fork = new Sandbox(data, this._client);
1413
+ return options.wait === false ? fork : waitForSandboxStart(fork);
1414
+ }
1415
+ /** Create a short-lived signed WebSocket URL for an interactive shell. */
1416
+ async createConnection() {
1417
+ const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this.id } } }));
1418
+ return {
1419
+ url: data.url,
1420
+ expiresAt: new Date(data.expires_at)
1421
+ };
1422
+ }
1423
+ /** Delete this sandbox and its backing disk. */
1424
+ async delete() {
1425
+ await unwrapEmpty(this._client.DELETE("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }));
1385
1426
  }
1386
1427
  async exec(command, options = {}) {
1387
- const timeoutMs = options.timeoutMs ?? 3e4;
1388
- validateTimeoutMs(timeoutMs);
1389
- const deadline = Date.now() + timeoutMs;
1428
+ if ("pty" in options) {
1429
+ const connection = await this.createConnection();
1430
+ return SandboxPty.connect(connection.url, command, options);
1431
+ }
1390
1432
  const exec = new SandboxExec(await unwrap(this._client.POST("/api/sandboxes/{sid}/execs", {
1391
1433
  params: {
1392
1434
  path: { sid: this.id },
1393
- query: { wait: false }
1435
+ query: { wait: options.wait ?? true }
1394
1436
  },
1395
1437
  body: {
1396
1438
  command,
@@ -1399,14 +1441,12 @@ var Sandbox = class {
1399
1441
  timeout_seconds: options.timeoutSeconds
1400
1442
  }
1401
1443
  })), 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)));
1444
+ if (options.wait === false) return exec;
1445
+ while (exec.status === "running") {
1446
+ await sleep();
1407
1447
  await exec.refresh();
1408
- if (exec.status !== "running") return exec;
1409
1448
  }
1449
+ return exec;
1410
1450
  }
1411
1451
  async listExecs() {
1412
1452
  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 +1464,16 @@ var Sandbox = class {
1424
1464
  } } })), this._client);
1425
1465
  }
1426
1466
  };
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)));
1467
+ /** @internal Continue waiting if the server returned before startup completed. */
1468
+ async function waitForSandboxStart(sandbox) {
1469
+ return waitWhileSandboxStatus(sandbox, "pending");
1470
+ }
1471
+ async function waitWhileSandboxStatus(sandbox, status) {
1472
+ while (sandbox.status === status) {
1473
+ await sleep();
1435
1474
  await sandbox.refresh();
1436
1475
  }
1476
+ return sandbox;
1437
1477
  }
1438
1478
  //#endregion
1439
1479
  //#region src/sandboxes.ts
@@ -1453,10 +1493,8 @@ var Sandboxes = class {
1453
1493
  return new Sandbox(await unwrap(this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: id } } })), this._client);
1454
1494
  }
1455
1495
  async create(request = {}, options = {}) {
1456
- const timeoutMs = options.timeoutMs ?? 3e4;
1457
- validateTimeoutMs(timeoutMs);
1458
- const deadline = Date.now() + timeoutMs;
1459
1496
  const body = {
1497
+ name: request.name,
1460
1498
  vcpu_count: request.vcpuCount,
1461
1499
  mem_size_mib: request.memSizeMiB,
1462
1500
  base_image: request.baseImage,
@@ -1464,10 +1502,11 @@ var Sandboxes = class {
1464
1502
  max_ttl_seconds: request.maxTtlSeconds,
1465
1503
  max_concurrent_execs: request.maxConcurrentExecs
1466
1504
  };
1467
- return waitForSandboxStart(new Sandbox(await unwrap(this._client.POST("/api/sandboxes", {
1468
- params: { query: { wait: false } },
1505
+ const sandbox = new Sandbox(await unwrap(this._client.POST("/api/sandboxes", {
1506
+ params: { query: { wait: options.wait ?? true } },
1469
1507
  body
1470
- })), this._client), deadline, timeoutMs);
1508
+ })), this._client);
1509
+ return options.wait === false ? sandbox : waitForSandboxStart(sandbox);
1471
1510
  }
1472
1511
  };
1473
1512
  //#endregion
@@ -1871,8 +1910,7 @@ exports.DiskMultipart = DiskMultipart;
1871
1910
  exports.Disks = Disks;
1872
1911
  exports.Sandbox = Sandbox;
1873
1912
  exports.SandboxExec = SandboxExec;
1874
- exports.SandboxStartError = SandboxStartError;
1875
- exports.SandboxWaitTimeoutError = SandboxWaitTimeoutError;
1913
+ exports.SandboxPty = SandboxPty;
1876
1914
  exports.Sandboxes = Sandboxes;
1877
1915
  exports.Tokens = Tokens;
1878
1916
  exports.USER_AGENT = USER_AGENT;