disk 1.12.1 → 1.14.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.
@@ -0,0 +1,3462 @@
1
+ import { t as toSegments } from "./paths-Br9snUhy.mjs";
2
+ import { create, fromBinary, toBinary } from "@bufbuild/protobuf";
3
+ import { ClientFrameSchema, Exit_Status, Limits, ServerFrameSchema, WindowUpdateSchema } from "@archildata/api-types/process";
4
+ //#region src/api-fetch.ts
5
+ function buildPath(template, params = {}) {
6
+ return template.replace(/\{([^}]+)\}/g, (_, name) => {
7
+ const value = params[name];
8
+ if (value === void 0) throw new Error(`Missing path parameter '${name}' for ${template}`);
9
+ return encodeURIComponent(String(value));
10
+ });
11
+ }
12
+ /** Serialize a query object; undefined/null values are omitted and arrays repeat the key. */
13
+ function buildQuery(query = {}) {
14
+ const parts = [];
15
+ for (const [name, value] of Object.entries(query)) for (const item of Array.isArray(value) ? value : [value]) {
16
+ if (item === void 0 || item === null) continue;
17
+ parts.push(`${encodeURIComponent(name)}=${encodeURIComponent(String(item))}`);
18
+ }
19
+ return parts.length > 0 ? `?${parts.join("&")}` : "";
20
+ }
21
+ function createClient(config) {
22
+ const baseUrl = config.baseUrl.replace(/\/+$/, "");
23
+ const send = (request) => (config.fetch ?? globalThis.fetch)(request);
24
+ const headersFor = (extra = {}) => {
25
+ const headers = new Headers(config.headers);
26
+ for (const [name, value] of Object.entries(extra)) if (value !== void 0) headers.set(name, value);
27
+ return headers;
28
+ };
29
+ const call = async (method, path, init = {}) => {
30
+ const url = baseUrl + buildPath(path, init.params?.path) + buildQuery(init.params?.query);
31
+ const headers = headersFor(init.params?.header);
32
+ let body;
33
+ if (init.body !== void 0) {
34
+ body = JSON.stringify(init.body);
35
+ if (!headers.has("Content-Type")) headers.set("Content-Type", "application/json");
36
+ }
37
+ const response = await send(new Request(url, {
38
+ method,
39
+ headers,
40
+ body
41
+ }));
42
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
43
+ await response.body?.cancel().catch(() => {});
44
+ return response.ok ? {
45
+ data: void 0,
46
+ response
47
+ } : {
48
+ error: void 0,
49
+ response
50
+ };
51
+ }
52
+ if (response.ok) return {
53
+ data: await response.json(),
54
+ response
55
+ };
56
+ const text = await response.text();
57
+ let error = text;
58
+ try {
59
+ error = JSON.parse(text);
60
+ } catch {}
61
+ return {
62
+ error,
63
+ response
64
+ };
65
+ };
66
+ const method = (name) => ((path, init) => call(name, path, init));
67
+ return {
68
+ GET: method("GET"),
69
+ PUT: method("PUT"),
70
+ POST: method("POST"),
71
+ DELETE: method("DELETE"),
72
+ PATCH: method("PATCH"),
73
+ raw: (methodName, url, init = {}) => send(new Request(url, {
74
+ method: methodName,
75
+ headers: headersFor(init.headers),
76
+ body: init.body
77
+ }))
78
+ };
79
+ }
80
+ //#endregion
81
+ //#region src/s3xml.ts
82
+ const ALWAYS_ARRAY = /* @__PURE__ */ new Set(["Contents", "CommonPrefixes"]);
83
+ const NAMED_ENTITIES = {
84
+ amp: "&",
85
+ lt: "<",
86
+ gt: ">",
87
+ quot: "\"",
88
+ apos: "'"
89
+ };
90
+ function decodeEntities(text) {
91
+ if (!text.includes("&")) return text;
92
+ return text.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);/g, (match, ref) => {
93
+ if (ref[0] === "#") {
94
+ const code = ref[1] === "x" || ref[1] === "X" ? parseInt(ref.slice(2), 16) : parseInt(ref.slice(1), 10);
95
+ return code > 1114111 ? match : String.fromCodePoint(code);
96
+ }
97
+ return Object.hasOwn(NAMED_ENTITIES, ref) ? NAMED_ENTITIES[ref] : match;
98
+ });
99
+ }
100
+ function setOwn(target, name, value) {
101
+ Object.defineProperty(target, name, {
102
+ value,
103
+ enumerable: true,
104
+ writable: true,
105
+ configurable: true
106
+ });
107
+ }
108
+ function addChild(parent, name, value) {
109
+ parent.hasChildren = true;
110
+ const existing = Object.hasOwn(parent.children, name) ? parent.children[name] : void 0;
111
+ if (existing === void 0) setOwn(parent.children, name, ALWAYS_ARRAY.has(name) ? [value] : value);
112
+ else if (Array.isArray(existing)) existing.push(value);
113
+ else setOwn(parent.children, name, [existing, value]);
114
+ }
115
+ /** Index just past `terminator`, searching from `from`; throws if it never appears. */
116
+ function skipPast(xml, terminator, from) {
117
+ const end = xml.indexOf(terminator, from);
118
+ if (end === -1) throw new Error(`Malformed XML: missing '${terminator}'`);
119
+ return end + terminator.length;
120
+ }
121
+ /** Parse an XML document into a plain object. Returns {} for empty/blank input. */
122
+ function parseXml(xml) {
123
+ const root = {
124
+ name: "",
125
+ children: {},
126
+ hasChildren: false,
127
+ text: ""
128
+ };
129
+ const stack = [root];
130
+ let position = 0;
131
+ while (position < xml.length) {
132
+ const current = stack[stack.length - 1];
133
+ const open = xml.indexOf("<", position);
134
+ current.text += decodeEntities(xml.slice(position, open === -1 ? xml.length : open));
135
+ if (open === -1) break;
136
+ if (xml.startsWith("<!--", open)) position = skipPast(xml, "-->", open + 4);
137
+ else if (xml.startsWith("<![CDATA[", open)) {
138
+ position = skipPast(xml, "]]>", open + 9);
139
+ current.text += xml.slice(open + 9, position - 3);
140
+ } else if (xml.startsWith("<?", open)) position = skipPast(xml, "?>", open + 2);
141
+ else if (xml.startsWith("<!", open)) throw new Error("Malformed XML: DOCTYPE and other declarations are not supported");
142
+ else {
143
+ position = skipPast(xml, ">", open + 1);
144
+ const tag = xml.slice(open + 1, position - 1);
145
+ const closing = tag.startsWith("/");
146
+ const selfClosing = !closing && tag.endsWith("/");
147
+ const name = /^[^\s/]+/.exec(closing ? tag.slice(1) : tag)?.[0];
148
+ if (!name) throw new Error(`Malformed XML: invalid tag <${tag}>`);
149
+ if (closing) {
150
+ if (current.name !== name || stack.length === 1) throw new Error(`Malformed XML: unexpected </${name}>`);
151
+ stack.pop();
152
+ addChild(stack[stack.length - 1], name, current.hasChildren ? current.children : current.text);
153
+ } else if (selfClosing) addChild(current, name, "");
154
+ else stack.push({
155
+ name,
156
+ children: {},
157
+ hasChildren: false,
158
+ text: ""
159
+ });
160
+ }
161
+ }
162
+ if (stack.length !== 1) throw new Error(`Malformed XML: unclosed <${stack[stack.length - 1].name}>`);
163
+ return root.children;
164
+ }
165
+ //#endregion
166
+ //#region src/errors.ts
167
+ /**
168
+ * Base class for every error the SDK throws. Catch with `instanceof ArchilError`
169
+ * to handle control-plane and S3 failures uniformly; `status` is the HTTP status
170
+ * code and `code` a machine-readable error code when the server provided one.
171
+ */
172
+ var ArchilError = class extends Error {
173
+ /** HTTP status code associated with the failure. */
174
+ status;
175
+ /** Machine-readable error code (e.g. an S3 code like "NoSuchKey"), if known. */
176
+ code;
177
+ constructor(message, status, code) {
178
+ super(message);
179
+ this.name = "ArchilError";
180
+ this.status = status;
181
+ this.code = code;
182
+ }
183
+ };
184
+ /** Error from the control-plane REST API. */
185
+ var ArchilApiError = class extends ArchilError {
186
+ constructor(message, status, code) {
187
+ super(message, status, code);
188
+ this.name = "ArchilApiError";
189
+ }
190
+ };
191
+ var SandboxPauseError = class extends ArchilError {
192
+ latest;
193
+ constructor(latest) {
194
+ super(`Sandbox entered ${latest.status} before it paused${latest.exitReason ? `: ${latest.exitReason}` : ""}`, 409, "SANDBOX_PAUSE_FAILED");
195
+ this.latest = latest;
196
+ this.name = "SandboxPauseError";
197
+ }
198
+ };
199
+ var ImageBuildError = class extends ArchilError {
200
+ latest;
201
+ reason;
202
+ constructor(latest) {
203
+ super(`Image ${latest.imageId} build failed: ${latest.failureReason}`, 409, "IMAGE_BUILD_FAILED");
204
+ this.latest = latest;
205
+ this.name = "ImageBuildError";
206
+ this.reason = latest.failureReason;
207
+ }
208
+ };
209
+ var SandboxFileTransferError = class extends ArchilError {
210
+ operation;
211
+ path;
212
+ constructor(operation, path, cause) {
213
+ super(`Sandbox file ${operation} failed for ${path}: ${cause.message}`, 500, "SANDBOX_FILE_TRANSFER_FAILED");
214
+ this.name = "SandboxFileTransferError";
215
+ this.operation = operation;
216
+ this.path = path;
217
+ this.cause = cause;
218
+ }
219
+ };
220
+ /**
221
+ * Error from the S3-compatible object API (getObject/putObject/deleteObject/
222
+ * headObject/listObjects). The gateway returns an S3-style XML `<Error>` body;
223
+ * this surfaces its parts as structured fields (`status`, `code`, `requestId`)
224
+ * rather than a raw blob, while keeping the full body on `raw` for debugging.
225
+ */
226
+ var ArchilS3Error = class extends ArchilError {
227
+ /** S3 request id, if the gateway returned one. */
228
+ requestId;
229
+ /** Raw response body (the XML document), for debugging. */
230
+ raw;
231
+ constructor(opts) {
232
+ const detail = opts.message ?? opts.statusText ?? "";
233
+ const codePart = opts.code ? ` ${opts.code}` : "";
234
+ super(`S3 ${opts.operation} failed: ${opts.statusCode}${codePart}${detail ? ` — ${detail}` : ""}`, opts.statusCode, opts.code);
235
+ this.name = "ArchilS3Error";
236
+ this.requestId = opts.requestId;
237
+ this.raw = opts.raw;
238
+ }
239
+ };
240
+ function tagString(obj, tag) {
241
+ const value = obj[tag];
242
+ return value === void 0 || value === null ? void 0 : String(value);
243
+ }
244
+ /** Build an ArchilS3Error from a failed S3 response, parsing the XML body. */
245
+ function parseS3Error(operation, statusCode, statusText, body) {
246
+ let err = {};
247
+ try {
248
+ err = parseXml(body).Error ?? {};
249
+ } catch {
250
+ err = {};
251
+ }
252
+ return new ArchilS3Error({
253
+ operation,
254
+ statusCode,
255
+ statusText,
256
+ code: tagString(err, "Code"),
257
+ message: tagString(err, "Message"),
258
+ requestId: tagString(err, "RequestId"),
259
+ raw: body
260
+ });
261
+ }
262
+ //#endregion
263
+ //#region src/regions.ts
264
+ const REGION_URLS = {
265
+ "aws-us-east-1": "https://control.green.us-east-1.aws.prod.archil.com",
266
+ "aws-us-west-2": "https://control.green.us-west-2.aws.prod.archil.com",
267
+ "aws-eu-west-1": "https://control.green.eu-west-1.aws.prod.archil.com",
268
+ "gcp-us-central1": "https://control.blue.us-central1.gcp.prod.archil.com"
269
+ };
270
+ function resolveBaseUrl(region) {
271
+ const url = REGION_URLS[region];
272
+ if (!url) throw new Error(`Unknown region "${region}". Valid regions: ${Object.keys(REGION_URLS).join(", ")}`);
273
+ return url;
274
+ }
275
+ /**
276
+ * Derive the S3-compatible endpoint from a control-plane base URL by swapping a
277
+ * leading `control.` hostname segment for `s3.` (e.g.
278
+ * `control.green.us-east-1.…` → `s3.green.us-east-1.…`). Returns undefined if the
279
+ * URL can't be parsed. A host without a `control.` prefix is returned unchanged.
280
+ */
281
+ function deriveS3BaseUrl(controlBaseUrl) {
282
+ try {
283
+ const u = new URL(controlBaseUrl);
284
+ u.hostname = u.hostname.replace(/^control\./, "s3.");
285
+ return u.toString().replace(/\/$/, "");
286
+ } catch {
287
+ return;
288
+ }
289
+ }
290
+ //#endregion
291
+ //#region src/version.ts
292
+ const VERSION = "1.14.0";
293
+ const USER_AGENT = `archil-js/${VERSION}`;
294
+ //#endregion
295
+ //#region src/client.ts
296
+ function isNodeRuntime() {
297
+ return typeof process !== "undefined" && typeof process.versions?.node === "string";
298
+ }
299
+ const isBun = isNodeRuntime() && process.versions.bun !== void 0;
300
+ const undiciModule = isNodeRuntime() ? isBun ? import("undici/index.js") : import("undici") : void 0;
301
+ const CONTROL_PLANE_CONNECTIONS = 1;
302
+ const IDLE_SESSION_TIMEOUT_MS = 3e4;
303
+ function isAsyncIterableBody(body) {
304
+ return body != null && typeof body === "object" && Symbol.asyncIterator in body;
305
+ }
306
+ async function bufferBody(body) {
307
+ const chunks = [];
308
+ for await (const chunk of body) chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
309
+ return Buffer.concat(chunks);
310
+ }
311
+ const bufferRequestBodies = (dispatch) => (options, handler) => {
312
+ if (!isAsyncIterableBody(options.body)) return dispatch(options, handler);
313
+ bufferBody(options.body).then((body) => dispatch({
314
+ ...options,
315
+ body
316
+ }, handler), (error) => handler.onResponseError?.({
317
+ aborted: false,
318
+ paused: false,
319
+ reason: null,
320
+ abort() {},
321
+ pause() {},
322
+ resume() {}
323
+ }, error instanceof Error ? error : new Error(String(error))));
324
+ return true;
325
+ };
326
+ const sharedTransports = /* @__PURE__ */ new Map();
327
+ function dispatcherKey(baseUrl, authorization, ca) {
328
+ return JSON.stringify([
329
+ new URL(baseUrl).origin,
330
+ authorization,
331
+ ca?.map((cert) => cert.toString("base64"))
332
+ ]);
333
+ }
334
+ function getSharedTransport(key, ca) {
335
+ const existing = sharedTransports.get(key);
336
+ if (existing) return existing;
337
+ const transport = (async () => {
338
+ if (!undiciModule) throw new Error("The pooled control-plane transport requires Node.js");
339
+ const { Agent, fetch } = await undiciModule;
340
+ return {
341
+ fetch,
342
+ dispatcher: new Agent({
343
+ allowH2: true,
344
+ connections: CONTROL_PLANE_CONNECTIONS,
345
+ keepAliveTimeout: IDLE_SESSION_TIMEOUT_MS,
346
+ ...ca === void 0 ? {} : { connect: { ca } }
347
+ }).compose(bufferRequestBodies)
348
+ };
349
+ })();
350
+ sharedTransports.set(key, transport);
351
+ transport.catch(() => {
352
+ if (sharedTransports.get(key) === transport) sharedTransports.delete(key);
353
+ });
354
+ return transport;
355
+ }
356
+ function createPooledFetch(baseUrl, authorization, tls) {
357
+ if (!isNodeRuntime()) {
358
+ if (tls?.ca !== void 0) throw new Error("Custom TLS CAs require Node.js");
359
+ return;
360
+ }
361
+ const ca = tls?.ca === void 0 ? void 0 : (Array.isArray(tls.ca) ? tls.ca : [tls.ca]).map((cert) => Buffer.from(cert));
362
+ const key = dispatcherKey(baseUrl, authorization, ca);
363
+ return async (request) => {
364
+ const { fetch, dispatcher } = await getSharedTransport(key, ca);
365
+ const body = request.body === null ? null : new Uint8Array(await request.arrayBuffer());
366
+ return await fetch(request.url, {
367
+ method: request.method,
368
+ headers: [...request.headers],
369
+ body,
370
+ redirect: request.redirect,
371
+ signal: request.signal,
372
+ dispatcher
373
+ });
374
+ };
375
+ }
376
+ /**
377
+ * The `Authorization` value for an API key: the key exactly as given, as a
378
+ * bearer token. Credential-injecting proxies substitute a placeholder only when
379
+ * it is the whole token, so the SDK must not add a prefix to it. The control
380
+ * plane accepts the key with or without its `key-` prefix after `Bearer`.
381
+ */
382
+ function apiKeyAuthorization(apiKey) {
383
+ return `Bearer ${apiKey}`;
384
+ }
385
+ function createApiClient(opts) {
386
+ const baseUrl = opts.baseUrl ?? resolveBaseUrl(opts.region);
387
+ const authorization = apiKeyAuthorization(opts.apiKey);
388
+ return createClient({
389
+ baseUrl,
390
+ fetch: createPooledFetch(baseUrl, authorization, opts.tls),
391
+ headers: {
392
+ Authorization: authorization,
393
+ "User-Agent": USER_AGENT
394
+ }
395
+ });
396
+ }
397
+ /**
398
+ * Unwrap the API envelope: return data on success, throw ArchilApiError on failure.
399
+ */
400
+ async function unwrap(promise) {
401
+ return (await unwrapPage(promise)).data;
402
+ }
403
+ /**
404
+ * Unwrap a paginated list envelope: like {@link unwrap}, but also surface the
405
+ * envelope's `nextCursor` (undefined on the last page or from a server that
406
+ * doesn't paginate).
407
+ */
408
+ async function unwrapPage(promise) {
409
+ const { data: body, error, response } = await promise;
410
+ if (error || !body) {
411
+ const errBody = error;
412
+ throw new ArchilApiError(errBody?.error ?? `API request failed with status ${response.status}`, response.status, errBody?.code);
413
+ }
414
+ if (!body.success) throw new ArchilApiError(body.error ?? "Unknown API error", response.status, body.code);
415
+ return {
416
+ data: body.data,
417
+ nextCursor: body.nextCursor
418
+ };
419
+ }
420
+ /**
421
+ * Unwrap an API response that has no data payload (e.g., delete operations).
422
+ */
423
+ async function unwrapEmpty(promise) {
424
+ const { data: body, error, response } = await promise;
425
+ if (!error && response.status === 204) return;
426
+ if (error || !body) {
427
+ const errBody = error;
428
+ throw new ArchilApiError(errBody?.error ?? `API request failed with status ${response.status}`, response.status, errBody?.code);
429
+ }
430
+ if (!body.success) throw new ArchilApiError(body.error ?? "Unknown API error", response.status, body.code);
431
+ }
432
+ //#endregion
433
+ //#region src/exec-options.ts
434
+ /**
435
+ * @internal Copies only the known option keys into a request body. Every key
436
+ * is required here, so an option added to the API fails to compile until it is
437
+ * copied.
438
+ */
439
+ function execVmBody(options) {
440
+ return {
441
+ baseImage: options?.baseImage,
442
+ imageId: options?.imageId,
443
+ vcpuCount: options?.vcpuCount,
444
+ memSizeMib: options?.memSizeMib,
445
+ network: options?.network
446
+ };
447
+ }
448
+ const RETRY_BASE_MS = 100;
449
+ const RETRY_CAP_MS = 2e3;
450
+ const TRANSIENT_STATUSES = /* @__PURE__ */ new Set([
451
+ 429,
452
+ 500,
453
+ 502,
454
+ 503,
455
+ 504
456
+ ]);
457
+ const CONNECT_ERROR_CODES = /* @__PURE__ */ new Set([
458
+ "CERT_HAS_EXPIRED",
459
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
460
+ "EAI_AGAIN",
461
+ "ECONNREFUSED",
462
+ "EHOSTUNREACH",
463
+ "ENETUNREACH",
464
+ "ENOTFOUND",
465
+ "ETIMEDOUT",
466
+ "ERR_TLS_CERT_ALTNAME_INVALID",
467
+ "SELF_SIGNED_CERT_IN_CHAIN",
468
+ "UNABLE_TO_GET_ISSUER_CERT",
469
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
470
+ "UND_ERR_CONNECT_TIMEOUT"
471
+ ]);
472
+ function isTransientStatus(status) {
473
+ return TRANSIENT_STATUSES.has(status);
474
+ }
475
+ function retryDelayMs(attempt) {
476
+ const ceiling = Math.min(RETRY_CAP_MS, RETRY_BASE_MS * 2 ** attempt);
477
+ return Math.random() * ceiling;
478
+ }
479
+ function retrySleep(attempt) {
480
+ return new Promise((resolve) => setTimeout(resolve, retryDelayMs(attempt)));
481
+ }
482
+ function isConnectionEstablishmentError(error) {
483
+ const seen = /* @__PURE__ */ new Set();
484
+ const pending = [error];
485
+ while (pending.length > 0) {
486
+ const current = pending.pop();
487
+ if (!current || seen.has(current)) continue;
488
+ seen.add(current);
489
+ if (typeof current !== "object") continue;
490
+ const value = current;
491
+ const code = typeof value.code === "string" ? value.code : "";
492
+ if (CONNECT_ERROR_CODES.has(code) || code.startsWith("ERR_SSL_") || code.startsWith("ERR_TLS_")) return true;
493
+ if (typeof value.message === "string" && value.message.includes("before secure TLS connection was established")) return true;
494
+ if (value.cause) pending.push(value.cause);
495
+ if (Array.isArray(value.errors)) pending.push(...value.errors);
496
+ }
497
+ return false;
498
+ }
499
+ async function retryApiRequest(request, mode) {
500
+ for (let attempt = 0;; attempt++) {
501
+ try {
502
+ const result = await request();
503
+ if (mode !== "transient" || !isTransientStatus(result.response.status) || attempt >= 3) return result;
504
+ } catch (error) {
505
+ if (!(mode === "transient" || mode === "connect" && isConnectionEstablishmentError(error)) || attempt >= 3) throw error;
506
+ }
507
+ await retrySleep(attempt);
508
+ }
509
+ }
510
+ //#endregion
511
+ //#region src/disk.ts
512
+ var Disk = class {
513
+ id;
514
+ name;
515
+ organization;
516
+ status;
517
+ provider;
518
+ region;
519
+ createdAt;
520
+ fsHandlerStatus;
521
+ lastAccessed;
522
+ activeDataBytes;
523
+ totalDataBytes;
524
+ /** @deprecated Use {@link activeDataBytes}. */
525
+ dataSize;
526
+ monthlyUsage;
527
+ mounts;
528
+ metrics;
529
+ connectedClients;
530
+ authorizedUsers;
531
+ allowedIps;
532
+ /** Root-directory POSIX attributes recorded at creation, if any. */
533
+ rootAttrs;
534
+ /** @internal */
535
+ _client;
536
+ /** @internal */
537
+ _archilRegion;
538
+ /** Base URL for the S3-compatible API (port 9000 ingress). Empty if unset. */
539
+ _s3BaseUrl;
540
+ /** Lazily-constructed multipart namespace (see {@link multipart}). @internal */
541
+ _multipart;
542
+ /** @internal */
543
+ constructor(data, client, archilRegion, s3BaseUrl) {
544
+ this.id = data.id;
545
+ this.name = data.name;
546
+ this.organization = data.organization;
547
+ this.status = data.status;
548
+ this.provider = data.provider;
549
+ this.region = data.region;
550
+ this.createdAt = data.createdAt;
551
+ this.fsHandlerStatus = data.fsHandlerStatus;
552
+ this.lastAccessed = data.lastAccessed;
553
+ this.activeDataBytes = data.activeDataBytes;
554
+ this.totalDataBytes = data.totalDataBytes;
555
+ this.dataSize = data.activeDataBytes;
556
+ this.monthlyUsage = data.monthlyUsage;
557
+ this.mounts = data.mounts;
558
+ this.metrics = data.metrics;
559
+ this.connectedClients = data.connectedClients;
560
+ this.authorizedUsers = data.authorizedUsers;
561
+ this.allowedIps = data.allowedIps;
562
+ this.rootAttrs = data.rootAttrs;
563
+ this._client = client;
564
+ this._archilRegion = archilRegion;
565
+ this._s3BaseUrl = s3BaseUrl ?? "";
566
+ }
567
+ toJSON() {
568
+ return {
569
+ id: this.id,
570
+ name: this.name,
571
+ organization: this.organization,
572
+ status: this.status,
573
+ provider: this.provider,
574
+ region: this.region,
575
+ createdAt: this.createdAt,
576
+ fsHandlerStatus: this.fsHandlerStatus,
577
+ lastAccessed: this.lastAccessed,
578
+ activeDataBytes: this.activeDataBytes,
579
+ totalDataBytes: this.totalDataBytes,
580
+ monthlyUsage: this.monthlyUsage,
581
+ mounts: this.mounts,
582
+ metrics: this.metrics,
583
+ connectedClients: this.connectedClients,
584
+ authorizedUsers: this.authorizedUsers,
585
+ allowedIps: this.allowedIps,
586
+ rootAttrs: this.rootAttrs
587
+ };
588
+ }
589
+ async addUser(user) {
590
+ return unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/users", {
591
+ params: { path: { id: this.id } },
592
+ body: user
593
+ }), "connect"));
594
+ }
595
+ async removeUser(userType, identifier) {
596
+ await unwrapEmpty(retryApiRequest(() => this._client.DELETE("/api/disks/{id}/users/{userType}", { params: {
597
+ path: {
598
+ id: this.id,
599
+ userType
600
+ },
601
+ query: { identifier }
602
+ } }), "connect"));
603
+ }
604
+ async createToken(nickname) {
605
+ const user = await unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/users", {
606
+ params: { path: { id: this.id } },
607
+ body: {
608
+ type: "token",
609
+ nickname
610
+ }
611
+ }), "connect"));
612
+ if (!user.token || !user.identifier) throw new Error("Server did not return a generated token");
613
+ return user;
614
+ }
615
+ async removeTokenUser(identifier) {
616
+ await this.removeUser("token", identifier);
617
+ }
618
+ /**
619
+ * Create an S3 access key pair for this disk's S3 API. The secret key is
620
+ * returned only here. The keys reach the whole disk, read-write unless
621
+ * `readOnly` is set, so keep them server-side and give browsers presigned
622
+ * URLs instead.
623
+ */
624
+ async createS3Credentials(options = {}) {
625
+ const user = await this.addUser({
626
+ ...options,
627
+ type: "s3"
628
+ });
629
+ if (!user.s3AccessKeyId || !user.s3SecretKey || !user.identifier) throw new Error("Server did not return generated S3 credentials");
630
+ return user;
631
+ }
632
+ async removeS3Credentials(accessKeyId) {
633
+ await this.removeUser("s3", accessKeyId);
634
+ }
635
+ /**
636
+ * List all delegations currently held on this disk. A delegation grants a
637
+ * client exclusive write access to an inode; it has no ID of its own and is
638
+ * identified by the (clientId, inodeId) pair — pass those to
639
+ * `revokeDelegation` to release one. Entries with `isOrphaned: true` are
640
+ * held by clients no longer connected to the disk (disconnected without
641
+ * checking in). `path` is resolved best-effort by the server and may be
642
+ * absent.
643
+ */
644
+ async listDelegations() {
645
+ return (await unwrap(retryApiRequest(() => this._client.GET("/api/disks/{id}/delegations", { params: { path: { id: this.id } } }), "transient"))).delegations;
646
+ }
647
+ /**
648
+ * Forcibly revoke a delegation, reclaiming write access from a client that
649
+ * is unreachable or crashed without checking its delegations in.
650
+ *
651
+ * Takes the `(clientId, inodeId)` pair identifying the delegation — pass an
652
+ * entry from `listDelegations` directly:
653
+ *
654
+ * ```ts
655
+ * for (const d of await disk.listDelegations()) {
656
+ * if (d.isOrphaned) await disk.revokeDelegation(d);
657
+ * }
658
+ * ```
659
+ */
660
+ async revokeDelegation(delegation) {
661
+ const { clientId, inodeId } = delegation;
662
+ await unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/revoke-delegation", {
663
+ params: { path: { id: this.id } },
664
+ body: {
665
+ clientId,
666
+ inodeId
667
+ }
668
+ }), "connect"));
669
+ }
670
+ /**
671
+ * Create a branch: an independent, writable fork of this disk that starts
672
+ * from a committed checkpoint. Writes on the branch don't affect its source.
673
+ *
674
+ * Fails with a 409 if a branch with this name already exists or the
675
+ * checkpoint is not yet committed, and a 404 if the checkpoint or
676
+ * `fromBranch` doesn't exist.
677
+ */
678
+ async createBranch(options) {
679
+ const idempotencyKey = options.idempotencyKey ?? globalThis.crypto.randomUUID();
680
+ return unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/branches", {
681
+ params: {
682
+ path: { id: this.id },
683
+ header: { "Idempotency-Key": idempotencyKey }
684
+ },
685
+ body: {
686
+ branch_name: options.name,
687
+ from_checkpoint_name: options.fromCheckpoint,
688
+ from_branch: options.fromBranch
689
+ }
690
+ }), "transient"));
691
+ }
692
+ /** List every branch of this disk, including branches of branches, in no particular order. */
693
+ async listBranches() {
694
+ return unwrap(retryApiRequest(() => this._client.GET("/api/disks/{id}/branches", { params: { path: { id: this.id } } }), "transient"));
695
+ }
696
+ async getBranch(name) {
697
+ return unwrap(retryApiRequest(() => this._client.GET("/api/disks/{id}/branches/{name}", { params: { path: {
698
+ id: this.id,
699
+ name
700
+ } } }), "transient"));
701
+ }
702
+ async getAllowedIPs() {
703
+ return (await unwrap(retryApiRequest(() => this._client.GET("/api/disks/{id}/allowed-ips", { params: { path: { id: this.id } } }), "transient"))).allowedIps;
704
+ }
705
+ async setAllowedIPs(allowedIps) {
706
+ return (await unwrap(retryApiRequest(() => this._client.PUT("/api/disks/{id}/allowed-ips", {
707
+ params: { path: { id: this.id } },
708
+ body: { allowedIps }
709
+ }), "transient"))).allowedIps;
710
+ }
711
+ async addAllowedIP(ip) {
712
+ const current = await this.getAllowedIPs();
713
+ if (current.includes(ip)) return current;
714
+ return this.setAllowedIPs([...current, ip]);
715
+ }
716
+ async removeAllowedIP(ip) {
717
+ const current = await this.getAllowedIPs();
718
+ return this.setAllowedIPs(current.filter((i) => i !== ip));
719
+ }
720
+ async delete() {
721
+ await unwrapEmpty(retryApiRequest(() => this._client.DELETE("/api/disks/{id}", { params: { path: { id: this.id } } }), "connect"));
722
+ }
723
+ /**
724
+ * Execute a command in a container with this disk mounted.
725
+ * Blocks until the command completes and returns stdout, stderr, and exit code.
726
+ */
727
+ async exec(command, options) {
728
+ return unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/exec", {
729
+ params: { path: { id: this.id } },
730
+ body: {
731
+ ...execVmBody(options),
732
+ command
733
+ }
734
+ }), "connect"));
735
+ }
736
+ /**
737
+ * Constant-time parallel grep across files on this disk. Listing and
738
+ * matching are fanned out across ephemeral exec containers; the request
739
+ * finishes within the supplied time budget regardless of dataset size.
740
+ *
741
+ * The returned `stoppedReason` says whether the search ran to completion
742
+ * or short-circuited on `maxResults` / `maxDurationSeconds`. When
743
+ * stopping early, the matches returned are a sample (whichever workers
744
+ * reported first), not the lexicographically first N.
745
+ */
746
+ async grep(opts) {
747
+ return unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/grep", {
748
+ params: { path: { id: this.id } },
749
+ body: {
750
+ directory: opts.directory,
751
+ pattern: opts.pattern,
752
+ recursive: opts.recursive ?? false,
753
+ maxDurationSeconds: opts.maxDurationSeconds ?? 30,
754
+ concurrency: opts.concurrency ?? 50,
755
+ maxResults: opts.maxResults ?? 1e3,
756
+ ignoreCase: opts.ignoreCase,
757
+ multiline: opts.multiline,
758
+ globs: opts.globs,
759
+ types: opts.types,
760
+ typesNot: opts.typesNot,
761
+ contextBefore: opts.contextBefore ?? 0,
762
+ contextAfter: opts.contextAfter ?? 0
763
+ }
764
+ }), "transient"));
765
+ }
766
+ /**
767
+ * Create a signed, time-limited URL that lets anyone download a single file
768
+ * from this disk without authentication. The returned URL embeds a
769
+ * cryptographically signed token carrying the disk, the file's key, and an
770
+ * expiry — share it directly; no API key is needed to redeem it.
771
+ *
772
+ * @param key Path to the file on the disk (e.g. "reports/2026-01/data.pdf").
773
+ * @param opts `expiresIn` sets the URL lifetime in seconds (any positive
774
+ * integer, max 604800 = 7 days). Defaults to 24h.
775
+ */
776
+ async share(key, opts = {}) {
777
+ const body = { key };
778
+ if (opts.expiresIn !== void 0) body.expiresIn = opts.expiresIn;
779
+ const call = this._client.POST;
780
+ return unwrap(retryApiRequest(() => call(`/api/disks/${this.id}/share`, { body }), "connect"));
781
+ }
782
+ /**
783
+ * Read an object from the disk via the S3-compatible GetObject API and return
784
+ * its full contents as bytes. Throws `ArchilS3Error` if the object does not
785
+ * exist (status 404, code "NoSuchKey") or the request is rejected; use
786
+ * `headObject`/`objectExists` to check existence without throwing.
787
+ *
788
+ * @param key Path on the disk (e.g. "reports/2026-01/data.json")
789
+ */
790
+ async getObject(key) {
791
+ const resp = await this._s3Request("GET", key);
792
+ if (!resp.ok) throw parseS3Error("GetObject", resp.status, resp.statusText, decodeText(resp.body));
793
+ return resp.body;
794
+ }
795
+ /**
796
+ * Fetch an object's metadata (size, etag, content type, last-modified) without
797
+ * downloading its contents, via the S3-compatible HeadObject API. Returns
798
+ * `null` if the object does not exist.
799
+ *
800
+ * @param key Path on the disk (e.g. "reports/2026-01/data.json")
801
+ */
802
+ async headObject(key) {
803
+ const resp = await this._s3Request("HEAD", key);
804
+ if (resp.status === 404) return null;
805
+ if (!resp.ok) throw parseS3Error("HeadObject", resp.status, resp.statusText, decodeText(resp.body));
806
+ const lastModified = resp.headers.get("last-modified");
807
+ return {
808
+ size: Number(resp.headers.get("content-length") ?? 0),
809
+ etag: resp.headers.get("etag") ?? void 0,
810
+ contentType: resp.headers.get("content-type") ?? void 0,
811
+ lastModified: lastModified ? new Date(lastModified) : void 0
812
+ };
813
+ }
814
+ /** Whether an object exists on the disk (a HeadObject that maps 404 → false). */
815
+ async objectExists(key) {
816
+ return await this.headObject(key) !== null;
817
+ }
818
+ /**
819
+ * Write an object to the disk via the S3-compatible API. Handles any size:
820
+ * bodies at or below `multipartThreshold` (defaults to `partSize`, i.e.
821
+ * 16 MiB) go through a single PutObject request; larger bodies are uploaded as
822
+ * a multipart upload — split into `partSize` parts, uploaded with bounded
823
+ * `concurrency` (default 4), and assembled. A failed part aborts the upload so
824
+ * nothing is left half-staged. For manual control over the multipart
825
+ * lifecycle, use the {@link multipart} namespace.
826
+ *
827
+ * Faster than exec for large files — no container overhead, no command-length
828
+ * limits. Returns the entity tag the server assigned (a multipart upload's tag
829
+ * is S3's `md5(concat(partMd5s))-N` form rather than a plain MD5).
830
+ *
831
+ * Optional `mode` / `uid` / `gid` set the POSIX attributes of the published
832
+ * file (e.g. `{ mode: 0o644, uid: 1000, gid: 1000 }` for a non-root agent
833
+ * sandbox). Missing parent directories inherit `uid` / `gid` with mode
834
+ * `0755`; existing directories remain unchanged. A key ending in `/` creates
835
+ * an explicit directory marker whose leaf uses the requested attributes.
836
+ * Defaults are `root:root 0644` for files and `root:root 0755` for directories.
837
+ *
838
+ * @param key Path on the disk (e.g. "reports/2026-01/data.json")
839
+ * @param body Contents as a string, Uint8Array/Buffer, or ArrayBuffer
840
+ * @param options Either a content-type string, or {@link PutObjectOptions}
841
+ * (`contentType`, `multipartThreshold`, `partSize`,
842
+ * `concurrency`, `mode`, `uid`, `gid`). Content type defaults
843
+ * to "application/octet-stream".
844
+ */
845
+ async putObject(key, body, options) {
846
+ const opts = typeof options === "string" ? { contentType: options } : options ?? {};
847
+ const contentType = opts.contentType ?? "application/octet-stream";
848
+ const partSize = Math.max(opts.partSize ?? DEFAULT_PART_SIZE, MIN_PART_SIZE);
849
+ const threshold = opts.multipartThreshold ?? partSize;
850
+ const bytes = toBytes(body);
851
+ if (bytes.length <= threshold) {
852
+ const resp = await this._s3Request("PUT", key, {
853
+ body,
854
+ contentType,
855
+ extraHeaders: posixCreateHeaders(opts)
856
+ });
857
+ if (!resp.ok) throw parseS3Error("PutObject", resp.status, resp.statusText, decodeText(resp.body));
858
+ return { etag: resp.headers.get("etag") ?? void 0 };
859
+ }
860
+ return this._putMultipart(key, bytes, contentType, partSize, Math.max(1, opts.concurrency ?? DEFAULT_UPLOAD_CONCURRENCY), opts);
861
+ }
862
+ /**
863
+ * Upload a large body through the multipart lifecycle: split into `partSize`
864
+ * parts, upload them with bounded concurrency, then complete — aborting the
865
+ * upload if any part fails so nothing is left half-staged. @internal
866
+ */
867
+ async _putMultipart(key, bytes, contentType, partSize, concurrency, attrs = {}) {
868
+ const effectivePartSize = effectiveUploadPartSize(bytes.length, partSize);
869
+ const mp = this.multipart;
870
+ const upload = await mp.create(key, contentType, attrs);
871
+ try {
872
+ const partCount = Math.ceil(bytes.length / effectivePartSize);
873
+ const parts = new Array(partCount);
874
+ let next = 0;
875
+ const worker = async () => {
876
+ for (;;) {
877
+ const index = next++;
878
+ if (index >= partCount) return;
879
+ const start = index * effectivePartSize;
880
+ const slice = bytes.subarray(start, Math.min(start + effectivePartSize, bytes.length));
881
+ parts[index] = await mp.uploadPart(key, upload.uploadId, index + 1, slice);
882
+ }
883
+ };
884
+ await Promise.all(Array.from({ length: Math.min(concurrency, partCount) }, worker));
885
+ return { etag: (await mp.complete(key, upload.uploadId, parts)).etag };
886
+ } catch (err) {
887
+ await mp.abort(key, upload.uploadId).catch(() => {});
888
+ throw err;
889
+ }
890
+ }
891
+ /**
892
+ * Append bytes to an object via the S3-compatible PutObject append extension
893
+ * (`?append=true`). If the object already exists the bytes are appended to it;
894
+ * if it doesn't, it is created. Returns the entity tag of the full object
895
+ * after the append.
896
+ *
897
+ * Each call may append at most 1 MiB — the server rejects a larger body with
898
+ * `EntityTooLarge`. To grow an object past that, append in chunks (or use
899
+ * {@link putObject} for a one-shot large write).
900
+ *
901
+ * Unlike most operations this is NOT auto-retried on a transient error:
902
+ * append isn't idempotent, so retrying a succeeded-but-unacknowledged append
903
+ * would duplicate the bytes. On a transient failure, re-append yourself only
904
+ * after confirming the object's size.
905
+ *
906
+ * When the object does not yet exist, optional `mode` / `uid` / `gid` set the
907
+ * POSIX attributes of the newly created file (same headers as
908
+ * {@link putObject}); missing parents inherit `uid` / `gid` with mode `0755`.
909
+ * Existing files and directories are unchanged.
910
+ *
911
+ * @param key Path on the disk (e.g. "logs/app.log")
912
+ * @param body Bytes to append (string, Uint8Array/Buffer, or ArrayBuffer)
913
+ * @param options Either a content-type string, or {@link AppendObjectOptions}
914
+ * (`contentType`, `mode`, `uid`, `gid`). Content type defaults
915
+ * to "application/octet-stream" and applies only when the
916
+ * object is newly created.
917
+ */
918
+ async appendObject(key, body, options) {
919
+ const opts = typeof options === "string" ? { contentType: options } : options ?? {};
920
+ const resp = await this._s3Request("PUT", key, {
921
+ body,
922
+ contentType: opts.contentType ?? "application/octet-stream",
923
+ query: { append: "true" },
924
+ retry: false,
925
+ extraHeaders: posixCreateHeaders(opts)
926
+ });
927
+ if (!resp.ok) throw parseS3Error("AppendObject", resp.status, resp.statusText, decodeText(resp.body));
928
+ return { etag: resp.headers.get("etag") ?? void 0 };
929
+ }
930
+ /**
931
+ * Delete an object from the disk via the S3-compatible DeleteObject API.
932
+ * Idempotent: deleting a key that doesn't exist resolves successfully, per
933
+ * S3 semantics.
934
+ *
935
+ * @param key Path on the disk (e.g. "project/dist/server.cjs")
936
+ */
937
+ async deleteObject(key) {
938
+ const resp = await this._s3Request("DELETE", key);
939
+ if (!resp.ok && resp.status !== 404) throw parseS3Error("DeleteObject", resp.status, resp.statusText, decodeText(resp.body));
940
+ }
941
+ /**
942
+ * List objects on the disk via the S3-compatible ListObjectsV2 API. By
943
+ * default this follows continuation tokens until the listing is exhausted and
944
+ * returns every matching key. Use `limit` to cap the total, `singlePage` for a
945
+ * single request, or {@link listObjectsPages} to stream pages without loading
946
+ * everything into memory.
947
+ *
948
+ * @param prefix Only return keys beginning with this prefix (omit for all).
949
+ * @param opts Listing and pagination options.
950
+ */
951
+ async listObjects(prefix, opts = {}) {
952
+ if (opts.singlePage) return this._listObjectsPage(prefix, opts);
953
+ const objects = [];
954
+ const commonPrefixes = [];
955
+ const seenPrefixes = /* @__PURE__ */ new Set();
956
+ let echoedPrefix;
957
+ let truncated = false;
958
+ outer: for await (const page of this.listObjectsPages(prefix, opts)) {
959
+ echoedPrefix = page.prefix;
960
+ for (const cp of page.commonPrefixes) if (!seenPrefixes.has(cp)) {
961
+ seenPrefixes.add(cp);
962
+ commonPrefixes.push(cp);
963
+ }
964
+ for (const obj of page.objects) {
965
+ if (opts.limit !== void 0 && objects.length >= opts.limit) {
966
+ truncated = true;
967
+ break outer;
968
+ }
969
+ objects.push(obj);
970
+ }
971
+ }
972
+ return {
973
+ objects,
974
+ commonPrefixes,
975
+ isTruncated: truncated,
976
+ keyCount: objects.length,
977
+ prefix: echoedPrefix
978
+ };
979
+ }
980
+ /**
981
+ * Yield ListObjectsV2 pages lazily, following continuation tokens. A
982
+ * memory-friendly way to process a large listing without materializing it:
983
+ *
984
+ * ```ts
985
+ * for await (const page of disk.listObjectsPages("logs/")) {
986
+ * for (const obj of page.objects) process(obj);
987
+ * }
988
+ * ```
989
+ *
990
+ * @param prefix Only return keys beginning with this prefix (omit for all).
991
+ * @param opts Listing options (`limit` / `singlePage` are ignored here —
992
+ * control your own loop).
993
+ */
994
+ async *listObjectsPages(prefix, opts = {}) {
995
+ const seenTokens = /* @__PURE__ */ new Set();
996
+ let continuationToken = opts.continuationToken;
997
+ for (;;) {
998
+ const page = await this._listObjectsPage(prefix, {
999
+ ...opts,
1000
+ continuationToken
1001
+ });
1002
+ yield page;
1003
+ const next = page.isTruncated ? page.nextContinuationToken : void 0;
1004
+ if (!next || seenTokens.has(next)) break;
1005
+ seenTokens.add(next);
1006
+ continuationToken = next;
1007
+ }
1008
+ }
1009
+ /** Fetch a single ListObjectsV2 page. @internal */
1010
+ async _listObjectsPage(prefix, opts) {
1011
+ const query = { "list-type": 2 };
1012
+ if (prefix !== void 0) query.prefix = prefix;
1013
+ if (!opts.recursive) query.delimiter = "/";
1014
+ if (opts.continuationToken !== void 0) query["continuation-token"] = opts.continuationToken;
1015
+ if (opts.startAfter !== void 0) query["start-after"] = opts.startAfter;
1016
+ const resp = await this._s3Request("GET", "", { query });
1017
+ if (!resp.ok) throw parseS3Error("ListObjectsV2", resp.status, resp.statusText, decodeText(resp.body));
1018
+ return parseListObjectsResult(decodeText(resp.body));
1019
+ }
1020
+ /**
1021
+ * Delete up to many objects in a single S3-compatible DeleteObjects request.
1022
+ * Unlike {@link deleteObject}, failures are reported per key rather than
1023
+ * thrown: the result's `deleted` lists the keys that were removed and
1024
+ * `errors` lists the ones that weren't (with the server's code/message). A
1025
+ * key that didn't exist still counts as deleted, per S3 semantics.
1026
+ *
1027
+ * The server caps a single request at 1000 keys; this method transparently
1028
+ * splits larger inputs into 1000-key batches and merges the results.
1029
+ *
1030
+ * @param keys Object keys to delete.
1031
+ * @param opts `quiet` suppresses the per-key success list server-side.
1032
+ */
1033
+ async deleteObjects(keys, opts = {}) {
1034
+ const deleted = [];
1035
+ const errors = [];
1036
+ for (let i = 0; i < keys.length; i += MAX_DELETE_OBJECTS_PER_REQUEST) {
1037
+ const xml = buildDeleteObjectsXml(keys.slice(i, i + MAX_DELETE_OBJECTS_PER_REQUEST), opts.quiet ?? false);
1038
+ const resp = await this._s3Request("POST", "", {
1039
+ query: { delete: "" },
1040
+ body: xml,
1041
+ contentType: "application/xml"
1042
+ });
1043
+ if (!resp.ok) throw parseS3Error("DeleteObjects", resp.status, resp.statusText, decodeText(resp.body));
1044
+ const parsed = parseDeleteObjectsResult(decodeText(resp.body));
1045
+ deleted.push(...parsed.deleted);
1046
+ errors.push(...parsed.errors);
1047
+ }
1048
+ return {
1049
+ deleted,
1050
+ errors
1051
+ };
1052
+ }
1053
+ /**
1054
+ * The advanced, opt-in multipart-upload API. Drive the raw lifecycle
1055
+ * yourself — `create` → `uploadPart` → `complete` (or `abort`), plus
1056
+ * `listParts` / `listUploads`. Most callers don't need this: {@link putObject}
1057
+ * runs the whole lifecycle automatically for large bodies. Reach for it only
1058
+ * when you need manual control (e.g. uploading parts from separate processes),
1059
+ * and note you then own part-size, memory, and concurrency management.
1060
+ */
1061
+ get multipart() {
1062
+ return this._multipart ??= new DiskMultipart(this.id, this._s3Request.bind(this));
1063
+ }
1064
+ /**
1065
+ * Send a single request to the disk's S3-compatible endpoint. This reuses the
1066
+ * control-plane client purely for its credential and transport — the same
1067
+ * `Authorization` header is sent and verified by the same code server-side —
1068
+ * pointed at the S3 host. Returns the response status and fully-buffered body
1069
+ * so callers can inspect both regardless of the verb used.
1070
+ *
1071
+ * The S3 routes (`/{diskId}/{key}` for objects, `/{diskId}` for the bucket)
1072
+ * are not part of the typed control-plane API, so the path and per-request
1073
+ * options are passed untyped. An empty `key` targets the bucket itself (used
1074
+ * by listObjects).
1075
+ *
1076
+ * @internal
1077
+ */
1078
+ async _s3Request(method, key, opts = {}) {
1079
+ if (!this._s3BaseUrl) throw new Error("S3 base URL not configured. Pass s3BaseUrl to new Archil({...}) or set ARCHIL_S3_BASE_URL.");
1080
+ const encodedKey = key.replace(/^\//, "").split("/").map(encodeURIComponent).join("/");
1081
+ const path = encodedKey ? `/${this.id}/${encodedKey}` : `/${this.id}`;
1082
+ const url = `${this._s3BaseUrl.replace(/\/+$/, "")}${path}${buildQuery(opts.query)}`;
1083
+ const init = {
1084
+ body: opts.body,
1085
+ headers: {
1086
+ ...opts.contentType ? { "Content-Type": opts.contentType } : {},
1087
+ ...opts.extraHeaders
1088
+ }
1089
+ };
1090
+ const hasBody = method === "GET" || method === "POST";
1091
+ const maxRetries = opts.retry === false ? 0 : 3;
1092
+ for (let attempt = 0;; attempt++) {
1093
+ let response;
1094
+ try {
1095
+ response = await this._client.raw(method, url, init);
1096
+ } catch (transportError) {
1097
+ if (attempt < maxRetries) {
1098
+ await retrySleep(attempt);
1099
+ continue;
1100
+ }
1101
+ throw transportError;
1102
+ }
1103
+ if (!response.ok) {
1104
+ if (isTransientStatus(response.status) && attempt < maxRetries) {
1105
+ await response.body?.cancel().catch(() => {});
1106
+ await retrySleep(attempt);
1107
+ continue;
1108
+ }
1109
+ return {
1110
+ ok: false,
1111
+ status: response.status,
1112
+ statusText: response.statusText,
1113
+ headers: response.headers,
1114
+ body: new Uint8Array(await response.arrayBuffer())
1115
+ };
1116
+ }
1117
+ if (!hasBody) await response.body?.cancel().catch(() => {});
1118
+ const bytes = hasBody ? new Uint8Array(await response.arrayBuffer()) : /* @__PURE__ */ new Uint8Array(0);
1119
+ return {
1120
+ ok: true,
1121
+ status: response.status,
1122
+ statusText: response.statusText,
1123
+ headers: response.headers,
1124
+ body: bytes
1125
+ };
1126
+ }
1127
+ }
1128
+ /**
1129
+ * Connect to this disk's data plane via the native ArchilClient.
1130
+ *
1131
+ * Requires the native module to be available (platform-specific .node binary).
1132
+ */
1133
+ async mount(opts) {
1134
+ let ArchilClient;
1135
+ try {
1136
+ const native = await import("@archildata/native");
1137
+ ArchilClient = native.ArchilClient ?? native.default?.ArchilClient;
1138
+ if (!ArchilClient) throw new Error("@archildata/native did not export ArchilClient");
1139
+ } catch {
1140
+ throw new Error("Native client not available. Install @archildata/native (platform-specific binary) or use ArchilClient.connect() directly. mount() is not supported in browsers.");
1141
+ }
1142
+ return ArchilClient.connect({
1143
+ region: this._archilRegion,
1144
+ diskName: `${this.organization}/${this.name}`,
1145
+ authToken: opts?.authToken,
1146
+ logLevel: opts?.logLevel,
1147
+ serverAddress: opts?.serverAddress,
1148
+ insecure: opts?.insecure
1149
+ });
1150
+ }
1151
+ };
1152
+ /**
1153
+ * The advanced, opt-in multipart-upload namespace, reached via {@link Disk.multipart}.
1154
+ * Drives the raw S3 multipart lifecycle — `create` → `uploadPart` → `complete`
1155
+ * (or `abort`), plus `listParts` / `listUploads`. Prefer {@link Disk.putObject},
1156
+ * which runs this lifecycle automatically for large bodies; use this only when
1157
+ * you need manual control, in which case you own part-size, memory, and
1158
+ * concurrency management.
1159
+ */
1160
+ var DiskMultipart = class {
1161
+ diskId;
1162
+ s3Request;
1163
+ /** @internal */
1164
+ constructor(diskId, s3Request) {
1165
+ this.diskId = diskId;
1166
+ this.s3Request = s3Request;
1167
+ }
1168
+ /**
1169
+ * Start a multipart upload (CreateMultipartUpload) and return its `uploadId`.
1170
+ *
1171
+ * @param key Path on the disk the finished object will live at.
1172
+ * @param contentType MIME type to store the object with.
1173
+ * @param attrs Optional POSIX `mode` / `uid` / `gid` for the completed
1174
+ * object (see {@link PosixCreateAttrs}).
1175
+ */
1176
+ async create(key, contentType, attrs = {}) {
1177
+ const resp = await this.s3Request("POST", key, {
1178
+ query: { uploads: "" },
1179
+ contentType,
1180
+ extraHeaders: posixCreateHeaders(attrs)
1181
+ });
1182
+ if (!resp.ok) throw parseS3Error("CreateMultipartUpload", resp.status, resp.statusText, decodeText(resp.body));
1183
+ const root = parseXml(decodeText(resp.body)).InitiateMultipartUploadResult ?? {};
1184
+ const uploadId = optionalString(root.UploadId);
1185
+ if (!uploadId) throw new ArchilS3Error({
1186
+ operation: "CreateMultipartUpload",
1187
+ statusCode: resp.status,
1188
+ message: "response did not contain an UploadId",
1189
+ raw: decodeText(resp.body)
1190
+ });
1191
+ return {
1192
+ uploadId,
1193
+ key: optionalString(root.Key) ?? key,
1194
+ bucket: optionalString(root.Bucket) ?? this.diskId
1195
+ };
1196
+ }
1197
+ /**
1198
+ * Upload one part (UploadPart) and return its entity tag, which you must
1199
+ * collect (with its part number) and pass to {@link complete}. Every part
1200
+ * except the last must be at least 5 MiB.
1201
+ *
1202
+ * @param key The upload's object key.
1203
+ * @param uploadId The id from {@link create}.
1204
+ * @param partNumber 1-based part number (1..=10000).
1205
+ * @param body Part contents as a string, Uint8Array/Buffer, or ArrayBuffer.
1206
+ */
1207
+ async uploadPart(key, uploadId, partNumber, body) {
1208
+ const resp = await this.s3Request("PUT", key, {
1209
+ query: {
1210
+ uploadId,
1211
+ partNumber
1212
+ },
1213
+ body
1214
+ });
1215
+ if (!resp.ok) throw parseS3Error("UploadPart", resp.status, resp.statusText, decodeText(resp.body));
1216
+ return {
1217
+ partNumber,
1218
+ etag: resp.headers.get("etag") ?? ""
1219
+ };
1220
+ }
1221
+ /**
1222
+ * Finish a multipart upload (CompleteMultipartUpload), assembling the listed
1223
+ * parts into one object. Parts are sorted by part number before submission
1224
+ * (the server requires strictly-increasing order).
1225
+ *
1226
+ * Unlike the other operations this is NOT auto-retried on a transient error:
1227
+ * the gateway isn't idempotent for completion, so a retry after a
1228
+ * successful-but-unacknowledged complete would return a spurious NoSuchUpload.
1229
+ * On a transient failure, re-drive completion yourself only after confirming
1230
+ * the object isn't already present.
1231
+ *
1232
+ * @param key The upload's object key.
1233
+ * @param uploadId The id from {@link create}.
1234
+ * @param parts The `{ partNumber, etag }` pairs from {@link uploadPart}.
1235
+ */
1236
+ async complete(key, uploadId, parts) {
1237
+ const xml = buildCompleteMultipartUploadXml([...parts].sort((a, b) => a.partNumber - b.partNumber));
1238
+ const resp = await this.s3Request("POST", key, {
1239
+ query: { uploadId },
1240
+ body: xml,
1241
+ contentType: "application/xml",
1242
+ retry: false
1243
+ });
1244
+ if (!resp.ok) throw parseS3Error("CompleteMultipartUpload", resp.status, resp.statusText, decodeText(resp.body));
1245
+ const root = parseXml(decodeText(resp.body)).CompleteMultipartUploadResult ?? {};
1246
+ return {
1247
+ etag: optionalString(root.ETag),
1248
+ location: optionalString(root.Location),
1249
+ bucket: optionalString(root.Bucket),
1250
+ key: optionalString(root.Key)
1251
+ };
1252
+ }
1253
+ /**
1254
+ * Abort a multipart upload (AbortMultipartUpload), discarding every staged
1255
+ * part. Idempotent against an upload that's already gone (404 / NoSuchUpload
1256
+ * resolves successfully).
1257
+ *
1258
+ * @param key The upload's object key.
1259
+ * @param uploadId The id from {@link create}.
1260
+ */
1261
+ async abort(key, uploadId) {
1262
+ const resp = await this.s3Request("DELETE", key, { query: { uploadId } });
1263
+ if (!resp.ok && resp.status !== 404) throw parseS3Error("AbortMultipartUpload", resp.status, resp.statusText, decodeText(resp.body));
1264
+ }
1265
+ /**
1266
+ * List the parts already uploaded for an in-progress upload (ListParts).
1267
+ * Returns a single page; follow `nextPartNumberMarker` (when `isTruncated`)
1268
+ * to page through the rest.
1269
+ *
1270
+ * @param key The upload's object key.
1271
+ * @param uploadId The id from {@link create}.
1272
+ * @param opts `maxParts` / `partNumberMarker` pagination controls.
1273
+ */
1274
+ async listParts(key, uploadId, opts = {}) {
1275
+ const query = { uploadId };
1276
+ if (opts.maxParts !== void 0) query["max-parts"] = opts.maxParts;
1277
+ if (opts.partNumberMarker !== void 0) query["part-number-marker"] = opts.partNumberMarker;
1278
+ const resp = await this.s3Request("GET", key, { query });
1279
+ if (!resp.ok) throw parseS3Error("ListParts", resp.status, resp.statusText, decodeText(resp.body));
1280
+ return parseListPartsResult(decodeText(resp.body));
1281
+ }
1282
+ /**
1283
+ * List in-progress multipart uploads on the disk (ListMultipartUploads).
1284
+ * Returns a single page; follow `nextKeyMarker` / `nextUploadIdMarker` (when
1285
+ * `isTruncated`) for the rest.
1286
+ *
1287
+ * @param opts Prefix/delimiter filter and pagination markers.
1288
+ */
1289
+ async listUploads(opts = {}) {
1290
+ const query = { uploads: "" };
1291
+ if (opts.prefix !== void 0) query.prefix = opts.prefix;
1292
+ if (opts.delimiter !== void 0) query.delimiter = opts.delimiter;
1293
+ if (opts.keyMarker !== void 0) query["key-marker"] = opts.keyMarker;
1294
+ if (opts.uploadIdMarker !== void 0) query["upload-id-marker"] = opts.uploadIdMarker;
1295
+ if (opts.maxUploads !== void 0) query["max-uploads"] = opts.maxUploads;
1296
+ const resp = await this.s3Request("GET", "", { query });
1297
+ if (!resp.ok) throw parseS3Error("ListMultipartUploads", resp.status, resp.statusText, decodeText(resp.body));
1298
+ return parseListMultipartUploadsResult(decodeText(resp.body));
1299
+ }
1300
+ };
1301
+ /**
1302
+ * Headers the S3 gateway accepts to set POSIX mode/owner on newly created
1303
+ * objects (see fshandler `x-archil-*` PutObject attrs).
1304
+ */
1305
+ const ARCHIL_MODE_HEADER = "x-archil-mode";
1306
+ const ARCHIL_UID_HEADER = "x-archil-uid";
1307
+ const ARCHIL_GID_HEADER = "x-archil-gid";
1308
+ /**
1309
+ * Build the `x-archil-*` headers for {@link PosixCreateAttrs}. `mode` is sent
1310
+ * in octal (`0o640` → "640"), matching the gateway's parser and the Python SDK.
1311
+ * Returns undefined when no attribute is set, so no headers are added.
1312
+ */
1313
+ function posixCreateHeaders(attrs) {
1314
+ const headers = {};
1315
+ if (attrs.mode !== void 0) headers[ARCHIL_MODE_HEADER] = attrs.mode.toString(8);
1316
+ if (attrs.uid !== void 0) headers[ARCHIL_UID_HEADER] = String(attrs.uid);
1317
+ if (attrs.gid !== void 0) headers[ARCHIL_GID_HEADER] = String(attrs.gid);
1318
+ return Object.keys(headers).length > 0 ? headers : void 0;
1319
+ }
1320
+ /** S3's per-request cap on DeleteObjects keys; larger inputs are batched. */
1321
+ const MAX_DELETE_OBJECTS_PER_REQUEST = 1e3;
1322
+ /** S3's minimum size for every multipart part but the last (5 MiB). */
1323
+ const MIN_PART_SIZE = 5 * 1024 * 1024;
1324
+ /** Default part size {@link Disk.putObject} uses on the multipart path (16 MiB). */
1325
+ const DEFAULT_PART_SIZE = 16 * 1024 * 1024;
1326
+ /** Default number of parts {@link Disk.putObject} uploads in parallel. */
1327
+ const DEFAULT_UPLOAD_CONCURRENCY = 4;
1328
+ /** The server's cap on parts in a single multipart upload (MAX_PARTS_PER_UPLOAD). */
1329
+ const MAX_PARTS_PER_UPLOAD = 1e4;
1330
+ /**
1331
+ * Choose the part size for a `totalBytes` multipart upload. Returns
1332
+ * `requestedPartSize` unless splitting at that size would exceed the server's
1333
+ * 10,000-part cap, in which case it grows the part size (rounded up to a whole
1334
+ * MiB) so the body fits in ≤ 10,000 parts — mirroring boto3's chunk-size
1335
+ * adjustment. Parts only ever get larger, so they stay above the 5 MiB floor.
1336
+ */
1337
+ function effectiveUploadPartSize(totalBytes, requestedPartSize) {
1338
+ if (Math.ceil(totalBytes / requestedPartSize) <= MAX_PARTS_PER_UPLOAD) return requestedPartSize;
1339
+ const MiB = 1024 * 1024;
1340
+ const needed = Math.ceil(totalBytes / MAX_PARTS_PER_UPLOAD);
1341
+ return Math.ceil(needed / MiB) * MiB;
1342
+ }
1343
+ /** Normalize an upload body to bytes so it can be sized and sliced into parts. */
1344
+ function toBytes(body) {
1345
+ if (typeof body === "string") return new TextEncoder().encode(body);
1346
+ if (body instanceof Uint8Array) return body;
1347
+ return new Uint8Array(body);
1348
+ }
1349
+ /** Escape text for safe inclusion in XML element content. */
1350
+ function escapeXml(value) {
1351
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1352
+ }
1353
+ /** Build a `<Delete>` request body for the DeleteObjects API. */
1354
+ function buildDeleteObjectsXml(keys, quiet) {
1355
+ return `<?xml version="1.0" encoding="UTF-8"?><Delete>${keys.map((k) => `<Object><Key>${escapeXml(k)}</Key></Object>`).join("")}${quiet ? "<Quiet>true</Quiet>" : ""}</Delete>`;
1356
+ }
1357
+ /** Build a `<CompleteMultipartUpload>` request body from the uploaded parts. */
1358
+ function buildCompleteMultipartUploadXml(parts) {
1359
+ return `<?xml version="1.0" encoding="UTF-8"?><CompleteMultipartUpload>${parts.map((p) => `<Part><PartNumber>${p.partNumber}</PartNumber><ETag>${escapeXml(p.etag)}</ETag></Part>`).join("")}</CompleteMultipartUpload>`;
1360
+ }
1361
+ /** Coerce a parser value that may be a single object or an array into an array. */
1362
+ function asArray(value) {
1363
+ if (value === void 0 || value === null) return [];
1364
+ return Array.isArray(value) ? value : [value];
1365
+ }
1366
+ function optionalNumber(value) {
1367
+ return value === void 0 || value === null ? void 0 : Number(value);
1368
+ }
1369
+ function optionalString(value) {
1370
+ return value === void 0 || value === null ? void 0 : String(value);
1371
+ }
1372
+ function optionalDate(value) {
1373
+ return value === void 0 || value === null ? void 0 : new Date(String(value));
1374
+ }
1375
+ /** Decode response bytes to a UTF-8 string (used for XML error/result bodies). */
1376
+ function decodeText(bytes) {
1377
+ return new TextDecoder().decode(bytes);
1378
+ }
1379
+ /** Parse an S3 ListObjectsV2 `<ListBucketResult>` XML document. */
1380
+ function parseListObjectsResult(xml) {
1381
+ const root = parseXml(xml).ListBucketResult ?? {};
1382
+ const objects = (root.Contents ?? []).map((c) => ({
1383
+ key: String(c.Key ?? ""),
1384
+ size: Number(c.Size ?? 0),
1385
+ etag: optionalString(c.ETag),
1386
+ lastModified: optionalDate(c.LastModified)
1387
+ }));
1388
+ return {
1389
+ objects,
1390
+ commonPrefixes: (root.CommonPrefixes ?? []).map((cp) => optionalString(cp.Prefix)).filter((p) => p !== void 0),
1391
+ isTruncated: root.IsTruncated === "true" || root.IsTruncated === true,
1392
+ nextContinuationToken: optionalString(root.NextContinuationToken),
1393
+ keyCount: root.KeyCount !== void 0 ? Number(root.KeyCount) : objects.length,
1394
+ prefix: optionalString(root.Prefix)
1395
+ };
1396
+ }
1397
+ function xmlIsTruncated(value) {
1398
+ return value === "true" || value === true;
1399
+ }
1400
+ /** Parse an S3 DeleteObjects `<DeleteResult>` XML document. */
1401
+ function parseDeleteObjectsResult(xml) {
1402
+ const root = parseXml(xml).DeleteResult ?? {};
1403
+ return {
1404
+ deleted: asArray(root.Deleted).map((d) => optionalString(d.Key)).filter((k) => k !== void 0),
1405
+ errors: asArray(root.Error).map((e) => ({
1406
+ key: String(e.Key ?? ""),
1407
+ code: optionalString(e.Code),
1408
+ message: optionalString(e.Message)
1409
+ }))
1410
+ };
1411
+ }
1412
+ /** Parse an S3 `<ListPartsResult>` XML document. */
1413
+ function parseListPartsResult(xml) {
1414
+ const root = parseXml(xml).ListPartsResult ?? {};
1415
+ const parts = asArray(root.Part).map((p) => ({
1416
+ partNumber: Number(p.PartNumber ?? 0),
1417
+ etag: optionalString(p.ETag),
1418
+ size: Number(p.Size ?? 0),
1419
+ lastModified: optionalDate(p.LastModified)
1420
+ }));
1421
+ return {
1422
+ bucket: optionalString(root.Bucket),
1423
+ key: optionalString(root.Key),
1424
+ uploadId: optionalString(root.UploadId),
1425
+ parts,
1426
+ isTruncated: xmlIsTruncated(root.IsTruncated),
1427
+ partNumberMarker: Number(root.PartNumberMarker ?? 0),
1428
+ nextPartNumberMarker: optionalNumber(root.NextPartNumberMarker),
1429
+ maxParts: Number(root.MaxParts ?? parts.length)
1430
+ };
1431
+ }
1432
+ /** Parse an S3 `<ListMultipartUploadsResult>` XML document. */
1433
+ function parseListMultipartUploadsResult(xml) {
1434
+ const root = parseXml(xml).ListMultipartUploadsResult ?? {};
1435
+ const uploads = asArray(root.Upload).map((u) => ({
1436
+ key: String(u.Key ?? ""),
1437
+ uploadId: String(u.UploadId ?? ""),
1438
+ initiated: optionalDate(u.Initiated)
1439
+ }));
1440
+ const commonPrefixes = asArray(root.CommonPrefixes).map((cp) => optionalString(cp.Prefix)).filter((p) => p !== void 0);
1441
+ return {
1442
+ bucket: optionalString(root.Bucket),
1443
+ uploads,
1444
+ commonPrefixes,
1445
+ isTruncated: xmlIsTruncated(root.IsTruncated),
1446
+ keyMarker: optionalString(root.KeyMarker),
1447
+ uploadIdMarker: optionalString(root.UploadIdMarker),
1448
+ nextKeyMarker: optionalString(root.NextKeyMarker),
1449
+ nextUploadIdMarker: optionalString(root.NextUploadIdMarker),
1450
+ prefix: optionalString(root.Prefix),
1451
+ delimiter: optionalString(root.Delimiter),
1452
+ maxUploads: optionalNumber(root.MaxUploads)
1453
+ };
1454
+ }
1455
+ //#endregion
1456
+ //#region src/disks.ts
1457
+ /** Server-side maximum page size for GET /api/disks. */
1458
+ const DISK_PAGE_LIMIT = 100;
1459
+ var Disks = class {
1460
+ /** @internal */
1461
+ _client;
1462
+ /** @internal */
1463
+ _region;
1464
+ /** @internal */
1465
+ _s3BaseUrl;
1466
+ /** @internal */
1467
+ constructor(client, region, s3BaseUrl) {
1468
+ this._client = client;
1469
+ this._region = region;
1470
+ this._s3BaseUrl = s3BaseUrl;
1471
+ }
1472
+ /**
1473
+ * List the account's disks. Fetches in cursor-driven pages (bounded server
1474
+ * work per request) and follows `nextCursor` until exhausted, so the result
1475
+ * is complete even for very large accounts. Use `limit` to cap the total, or
1476
+ * {@link listPage} to walk pages yourself.
1477
+ */
1478
+ async list(opts) {
1479
+ if (opts?.name !== void 0) return (await this.listPage(opts)).disks;
1480
+ const limit = opts?.limit;
1481
+ let cursor = opts?.cursor;
1482
+ const disks = [];
1483
+ for (;;) {
1484
+ const remaining = limit === void 0 ? void 0 : limit - disks.length;
1485
+ if (remaining !== void 0 && remaining <= 0) return disks;
1486
+ const pageLimit = remaining === void 0 ? DISK_PAGE_LIMIT : Math.min(remaining, DISK_PAGE_LIMIT);
1487
+ const page = await this.listPage({
1488
+ limit: pageLimit,
1489
+ cursor
1490
+ });
1491
+ disks.push(...remaining === void 0 ? page.disks : page.disks.slice(0, remaining));
1492
+ if (!page.nextCursor || page.nextCursor === cursor) return disks;
1493
+ cursor = page.nextCursor;
1494
+ }
1495
+ }
1496
+ /**
1497
+ * Fetch a single page of disks. `nextCursor` on the result resumes the
1498
+ * listing (it can also be persisted, e.g. across requests of a paginated UI).
1499
+ */
1500
+ async listPage(opts) {
1501
+ const { data, nextCursor } = await unwrapPage(retryApiRequest(() => this._client.GET("/api/disks", { params: { query: {
1502
+ limit: opts?.limit,
1503
+ cursor: opts?.cursor,
1504
+ name: opts?.name
1505
+ } } }), "transient"));
1506
+ const disks = (data ?? []).map((d) => new Disk(d, this._client, this._region, this._s3BaseUrl));
1507
+ return nextCursor ? {
1508
+ disks,
1509
+ nextCursor
1510
+ } : { disks };
1511
+ }
1512
+ async get(id) {
1513
+ return new Disk(await unwrap(retryApiRequest(() => this._client.GET("/api/disks/{id}", { params: { path: { id } } }), "transient")), this._client, this._region, this._s3BaseUrl);
1514
+ }
1515
+ /**
1516
+ * Create a new disk with an auto-generated mount token.
1517
+ *
1518
+ * Returns the Disk, the one-time token (save it — it cannot be retrieved
1519
+ * again), and the token identifier for later management.
1520
+ *
1521
+ * `rootAttrs` sets the POSIX owner and mode of the disk's root directory
1522
+ * (e.g. `{ uid: 1000, gid: 1000, mode: 0o755 }` so an unprivileged process
1523
+ * can create entries under the mount root without a post-mount `chown`).
1524
+ * Creation-time only.
1525
+ */
1526
+ async create(req) {
1527
+ const resp = await unwrap(retryApiRequest(() => this._client.POST("/api/disks", { body: req }), "connect"));
1528
+ if (!resp.diskId) throw new Error("API returned success but no diskId");
1529
+ const authorizedUsers = resp.authorizedUsers ?? [];
1530
+ const tokenUser = authorizedUsers.find((u) => u.token);
1531
+ return {
1532
+ disk: await this.get(resp.diskId),
1533
+ token: tokenUser?.token ?? null,
1534
+ tokenIdentifier: tokenUser?.identifier ?? null,
1535
+ authorizedUsers
1536
+ };
1537
+ }
1538
+ /**
1539
+ * Execute a command on a disk that is already known to exist. Accepts the
1540
+ * disk ID directly so callers that do not need its metadata can execute
1541
+ * without fetching the disk first.
1542
+ */
1543
+ async exec(id, command, options) {
1544
+ return unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/exec", {
1545
+ params: { path: { id } },
1546
+ body: {
1547
+ ...execVmBody(options),
1548
+ command
1549
+ }
1550
+ }), "connect"));
1551
+ }
1552
+ };
1553
+ //#endregion
1554
+ //#region src/images.ts
1555
+ const DEFAULT_BUILD_TIMEOUT_SECONDS = 1800;
1556
+ const MAX_INTERRUPTED_RETRIES = 3;
1557
+ const REQUEST_AGAIN_MS = 2 * 6e4;
1558
+ const FIRST_POLL_MS = 1e3;
1559
+ const MAX_POLL_MS = 5e3;
1560
+ function imageFromWire(data) {
1561
+ return {
1562
+ imageId: data.image_id,
1563
+ source: data.source,
1564
+ private: data.private,
1565
+ status: data.status,
1566
+ digest: data.digest,
1567
+ canonicalSource: data.canonical_source,
1568
+ failureReason: data.failure_reason,
1569
+ vcpuCount: data.vcpu_count,
1570
+ memSizeMiB: data.mem_size_mib,
1571
+ createdAt: new Date(data.created_at),
1572
+ updatedAt: new Date(data.updated_at)
1573
+ };
1574
+ }
1575
+ var Images = class {
1576
+ /** @internal */
1577
+ _client;
1578
+ /** @internal */
1579
+ constructor(client) {
1580
+ this._client = client;
1581
+ }
1582
+ async get(imageId) {
1583
+ return imageFromWire(await unwrap(retryApiRequest(() => this._client.GET("/api/images/{image_id}", { params: { path: { image_id: imageId } } }), "transient")));
1584
+ }
1585
+ /**
1586
+ * Build a sandbox image from an OCI reference and wait until it is ready.
1587
+ * Returns at once when the image is already built from a digest reference
1588
+ * and joins a build that is already running. A tag is rebuilt on each call
1589
+ * in case it moved, so call this once and reuse `imageId`. Interrupted
1590
+ * builds are requested again up to three times; other failures throw
1591
+ * {@link ImageBuildError}.
1592
+ */
1593
+ async build(request, options = {}) {
1594
+ const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_BUILD_TIMEOUT_SECONDS;
1595
+ const deadline = Date.now() + timeoutSeconds * 1e3;
1596
+ let image = await this._request(request);
1597
+ let lastRequest = Date.now();
1598
+ let retries = 0;
1599
+ let pollMs = FIRST_POLL_MS;
1600
+ for (;;) {
1601
+ if (image.status === "ready") return image;
1602
+ if (image.status === "failed") {
1603
+ if (image.failureReason !== "interrupted" || retries >= MAX_INTERRUPTED_RETRIES) throw new ImageBuildError(image);
1604
+ retries++;
1605
+ image = await this._request(request);
1606
+ lastRequest = Date.now();
1607
+ continue;
1608
+ }
1609
+ if (Date.now() >= deadline) throw new ArchilError(`Image ${image.imageId} was not ready after ${timeoutSeconds} seconds`, 408, "IMAGE_BUILD_TIMEOUT");
1610
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
1611
+ pollMs = Math.min(pollMs * 2, MAX_POLL_MS);
1612
+ image = await this.get(image.imageId);
1613
+ if (image.status === "building" && Date.now() - lastRequest >= REQUEST_AGAIN_MS) {
1614
+ image = await this._request(request);
1615
+ lastRequest = Date.now();
1616
+ }
1617
+ }
1618
+ }
1619
+ async _request(request) {
1620
+ return imageFromWire(await unwrap(retryApiRequest(() => this._client.POST("/api/images", { body: {
1621
+ source: request.source,
1622
+ registry_auth: request.registryAuth,
1623
+ vcpu_count: request.vcpuCount,
1624
+ mem_size_mib: request.memSizeMiB
1625
+ } }), "transient")));
1626
+ }
1627
+ };
1628
+ //#endregion
1629
+ //#region src/process-output-buffer.ts
1630
+ /**
1631
+ * Output each process has received but its iterator has not taken yet.
1632
+ * Flow control bounds it to one channel window per process, so it never
1633
+ * needs to refuse output. Output a handle never reads goes with the handle.
1634
+ */
1635
+ var ProcessOutputBuffer = class {
1636
+ queues = /* @__PURE__ */ new WeakMap();
1637
+ has(subscription) {
1638
+ return !!this.queues.get(subscription)?.length;
1639
+ }
1640
+ push(subscription, output) {
1641
+ const queue = this.queues.get(subscription) ?? [];
1642
+ queue.push(output);
1643
+ this.queues.set(subscription, queue);
1644
+ }
1645
+ take(subscription) {
1646
+ const queue = this.queues.get(subscription);
1647
+ const output = queue?.shift();
1648
+ if (queue && !queue.length) this.queues.delete(subscription);
1649
+ return output;
1650
+ }
1651
+ discard(subscription) {
1652
+ this.queues.delete(subscription);
1653
+ }
1654
+ };
1655
+ //#endregion
1656
+ //#region src/process-connection.ts
1657
+ async function waitForSocketOpen(socket) {
1658
+ if (socket.readyState === WebSocket.OPEN) return;
1659
+ await new Promise((resolve, reject) => {
1660
+ const cleanup = () => {
1661
+ socket.removeEventListener("open", opened);
1662
+ socket.removeEventListener("error", failed);
1663
+ socket.removeEventListener("close", closed);
1664
+ };
1665
+ const opened = () => {
1666
+ cleanup();
1667
+ resolve();
1668
+ };
1669
+ const failed = () => {
1670
+ cleanup();
1671
+ reject(/* @__PURE__ */ new Error("Process connection failed"));
1672
+ };
1673
+ const closed = () => {
1674
+ cleanup();
1675
+ reject(/* @__PURE__ */ new Error("Process connection closed before opening"));
1676
+ };
1677
+ socket.addEventListener("open", opened, { once: true });
1678
+ socket.addEventListener("error", failed, { once: true });
1679
+ socket.addEventListener("close", closed, { once: true });
1680
+ });
1681
+ }
1682
+ async function openProcessSocket(connectionEndpoint) {
1683
+ for (let attempt = 0;; attempt++) {
1684
+ const endpoint = await connectionEndpoint();
1685
+ let socket;
1686
+ try {
1687
+ socket = new WebSocket(endpoint.url, [PROTOCOL, `${TOKEN_PROTOCOL_PREFIX}${endpoint.token}`]);
1688
+ socket.binaryType = "arraybuffer";
1689
+ await waitForSocketOpen(socket);
1690
+ return socket;
1691
+ } catch (error) {
1692
+ try {
1693
+ socket?.close();
1694
+ } catch {}
1695
+ if (attempt >= 3) throw new Error(`Process connection failed after ${attempt + 1} attempts`, { cause: error });
1696
+ }
1697
+ await retrySleep(attempt);
1698
+ }
1699
+ }
1700
+ /** Bound queued socket writes across all channels of a connection. */
1701
+ async function waitForProcessWrite(socket) {
1702
+ while (socket.bufferedAmount > 256 * 1024) {
1703
+ if (socket.readyState !== WebSocket.OPEN) throw new Error("Process is disconnected");
1704
+ await new Promise((resolve) => setTimeout(resolve, 0));
1705
+ }
1706
+ }
1707
+ const PROTOCOL = "archil.connect.v2";
1708
+ const TOKEN_PROTOCOL_PREFIX = "archil.token.";
1709
+ const MAX_DATA = Limits.MAX_DATA_BYTES;
1710
+ const INITIAL_WINDOW = Limits.INITIAL_WINDOW;
1711
+ const MIN_DATA_COST = Limits.MIN_DATA_COST;
1712
+ const dataCost = (length) => Math.max(length, MIN_DATA_COST);
1713
+ const MAX_CHANNELS = 128;
1714
+ const IDLE_MS = 5e3;
1715
+ /** Owns only the client connection. A disconnected transport never retries START. */
1716
+ var ProcessConnection = class {
1717
+ endpoint;
1718
+ opening;
1719
+ binary;
1720
+ /** Every open connection, including ones a drain or full channel table left behind. */
1721
+ live = /* @__PURE__ */ new Set();
1722
+ generation = 0;
1723
+ constructor(endpoint) {
1724
+ this.endpoint = endpoint;
1725
+ }
1726
+ async open() {
1727
+ for (;;) {
1728
+ if (this.binary?.canOpen) return this.binary.channel();
1729
+ if (!this.opening) {
1730
+ const opening = this.connect().finally(() => {
1731
+ if (this.opening === opening) this.opening = void 0;
1732
+ });
1733
+ this.opening = opening;
1734
+ }
1735
+ const binary = await this.opening;
1736
+ if (binary.canOpen) return binary.channel();
1737
+ }
1738
+ }
1739
+ async connect() {
1740
+ const generation = this.generation;
1741
+ const socket = await openProcessSocket(this.endpoint);
1742
+ if (generation !== this.generation) {
1743
+ socket.close();
1744
+ throw new Error("Process connection opening cancelled");
1745
+ }
1746
+ if (socket.protocol !== PROTOCOL) {
1747
+ socket.close();
1748
+ throw new Error(`Sandbox runtime does not support the ${PROTOCOL} process protocol`);
1749
+ }
1750
+ const binary = new BinaryConnection(socket, () => this.live.delete(binary));
1751
+ this.live.add(binary);
1752
+ this.binary = binary;
1753
+ return binary;
1754
+ }
1755
+ disconnect() {
1756
+ this.generation++;
1757
+ this.opening = void 0;
1758
+ for (const binary of [...this.live]) binary.close();
1759
+ this.binary = void 0;
1760
+ }
1761
+ };
1762
+ var BinaryConnection = class {
1763
+ socket;
1764
+ onClosed;
1765
+ channels = /* @__PURE__ */ new Map();
1766
+ next = 1;
1767
+ draining = false;
1768
+ idle;
1769
+ get canOpen() {
1770
+ return !this.draining && this.socket.readyState === WebSocket.OPEN && this.next < 4294967295 && this.channels.size < MAX_CHANNELS;
1771
+ }
1772
+ constructor(socket, onClosed) {
1773
+ this.socket = socket;
1774
+ this.onClosed = onClosed;
1775
+ socket.addEventListener("message", (message) => {
1776
+ try {
1777
+ const frame = fromBinary(ServerFrameSchema, new Uint8Array(message.data));
1778
+ if (frame.channelId === 0) {
1779
+ if (frame.body.case !== "drain") return;
1780
+ this.draining = true;
1781
+ if (!this.channels.size) this.close();
1782
+ } else this.channels.get(frame.channelId)?.receive(frame);
1783
+ } catch (error) {
1784
+ this.close(error);
1785
+ }
1786
+ });
1787
+ socket.addEventListener("close", () => this.close(/* @__PURE__ */ new Error("Process connection closed before exit")), { once: true });
1788
+ socket.addEventListener("error", () => this.close(/* @__PURE__ */ new Error("Process connection failed")), { once: true });
1789
+ }
1790
+ channel() {
1791
+ if (!this.canOpen) throw new Error("Process connection is draining or full");
1792
+ clearTimeout(this.idle);
1793
+ const channel = new BinaryChannel(this, this.next++);
1794
+ this.channels.set(channel.id, channel);
1795
+ return channel;
1796
+ }
1797
+ send(id, body) {
1798
+ this.socket.send(toBinary(ClientFrameSchema, create(ClientFrameSchema, {
1799
+ channelId: id,
1800
+ body
1801
+ })));
1802
+ }
1803
+ async writable() {
1804
+ await waitForProcessWrite(this.socket);
1805
+ }
1806
+ remove(id) {
1807
+ this.channels.delete(id);
1808
+ if (!this.channels.size) if (this.draining) this.close();
1809
+ else this.idle = setTimeout(() => this.close(), IDLE_MS);
1810
+ }
1811
+ close(reason) {
1812
+ this.draining = true;
1813
+ this.onClosed();
1814
+ clearTimeout(this.idle);
1815
+ for (const channel of [...this.channels.values()]) channel.finish(reason);
1816
+ if (this.socket.readyState < WebSocket.CLOSING) this.socket.close();
1817
+ }
1818
+ };
1819
+ /** @internal WebSocket-shaped channel; generated protobuf owns all wire encoding. */
1820
+ var BinaryChannel = class {
1821
+ connection;
1822
+ id;
1823
+ readyState = WebSocket.OPEN;
1824
+ binaryType = "arraybuffer";
1825
+ events = new EventTarget();
1826
+ addEventListener = this.events.addEventListener.bind(this.events);
1827
+ sending = Promise.resolve();
1828
+ /** Stdin the runtime will accept. */
1829
+ sendCredit = INITIAL_WINDOW;
1830
+ /** Output the runtime may still send. */
1831
+ receiveCredit = INITIAL_WINDOW;
1832
+ /** Output consumed since credit was last returned. */
1833
+ consumed = 0;
1834
+ creditChanged;
1835
+ constructor(connection, id) {
1836
+ this.connection = connection;
1837
+ this.id = id;
1838
+ }
1839
+ sendRequest(request) {
1840
+ switch (request.type) {
1841
+ case "start": {
1842
+ const terminal = request.terminal === true ? {
1843
+ rows: 24,
1844
+ cols: 80
1845
+ } : request.terminal || void 0;
1846
+ this.connection.send(this.id, create(ClientFrameSchema, { body: {
1847
+ case: "start",
1848
+ value: {
1849
+ command: request.command,
1850
+ cwd: request.cwd,
1851
+ terminal,
1852
+ env: request.env,
1853
+ timeoutSeconds: request.timeout_seconds === void 0 ? void 0 : BigInt(request.timeout_seconds)
1854
+ }
1855
+ } }).body);
1856
+ break;
1857
+ }
1858
+ case "attach":
1859
+ this.connection.send(this.id, create(ClientFrameSchema, { body: {
1860
+ case: "attach",
1861
+ value: {
1862
+ processId: request.process_id,
1863
+ offset: BigInt(request.offset),
1864
+ shared: request.shared ?? false
1865
+ }
1866
+ } }).body);
1867
+ break;
1868
+ case "kill":
1869
+ this.connection.send(this.id, create(ClientFrameSchema, { body: {
1870
+ case: "kill",
1871
+ value: { processId: request.process_id }
1872
+ } }).body);
1873
+ break;
1874
+ case "resize":
1875
+ this.connection.send(this.id, create(ClientFrameSchema, { body: {
1876
+ case: "resize",
1877
+ value: {
1878
+ processId: request.process_id,
1879
+ terminal: {
1880
+ rows: request.rows,
1881
+ cols: request.cols
1882
+ }
1883
+ }
1884
+ } }).body);
1885
+ break;
1886
+ }
1887
+ }
1888
+ send(bytes) {
1889
+ const sending = this.sending.then(async () => {
1890
+ for (let offset = 0; offset < bytes.length; offset += MAX_DATA) {
1891
+ const chunk = bytes.subarray(offset, offset + MAX_DATA);
1892
+ while (this.sendCredit < dataCost(chunk.length)) {
1893
+ if (this.readyState !== WebSocket.OPEN) throw new Error("Process is disconnected");
1894
+ await new Promise((resolve) => {
1895
+ this.creditChanged = resolve;
1896
+ });
1897
+ }
1898
+ if (this.readyState !== WebSocket.OPEN) throw new Error("Process is disconnected");
1899
+ this.sendCredit -= dataCost(chunk.length);
1900
+ this.connection.send(this.id, {
1901
+ case: "stdin",
1902
+ value: chunk
1903
+ });
1904
+ await this.connection.writable();
1905
+ }
1906
+ });
1907
+ this.sending = sending.catch(() => {});
1908
+ return sending;
1909
+ }
1910
+ /** Returns credit for output the application has taken. */
1911
+ release(cost) {
1912
+ if (this.readyState === WebSocket.CLOSED) return;
1913
+ this.consumed += cost;
1914
+ if (this.consumed < INITIAL_WINDOW / 2) return;
1915
+ this.receiveCredit += this.consumed;
1916
+ this.connection.send(this.id, {
1917
+ case: "windowUpdate",
1918
+ value: create(WindowUpdateSchema, { bytes: this.consumed })
1919
+ });
1920
+ this.consumed = 0;
1921
+ }
1922
+ async closeStdin() {
1923
+ await this.sending;
1924
+ if (this.readyState !== WebSocket.OPEN) throw new Error("Process is disconnected");
1925
+ this.connection.send(this.id, create(ClientFrameSchema, { body: {
1926
+ case: "closeStdin",
1927
+ value: {}
1928
+ } }).body);
1929
+ }
1930
+ close() {
1931
+ if (this.readyState !== WebSocket.OPEN) return;
1932
+ this.readyState = WebSocket.CLOSING;
1933
+ this.connection.send(this.id, create(ClientFrameSchema, { body: {
1934
+ case: "detach",
1935
+ value: {}
1936
+ } }).body);
1937
+ }
1938
+ receive(frame) {
1939
+ const body = frame.body;
1940
+ let event;
1941
+ switch (body.case) {
1942
+ case "started":
1943
+ case "attached":
1944
+ event = {
1945
+ type: body.case,
1946
+ process_id: body.value.processId
1947
+ };
1948
+ break;
1949
+ case "windowUpdate":
1950
+ this.sendCredit += body.value.bytes;
1951
+ this.creditChanged?.();
1952
+ return;
1953
+ case "stdout":
1954
+ case "stderr": {
1955
+ if (body.value.data.length > MAX_DATA) throw new Error("Process output exceeds chunk size");
1956
+ const cost = dataCost(body.value.data.length);
1957
+ if (cost > this.receiveCredit) throw new Error("Process output exceeded its flow-control window");
1958
+ this.receiveCredit -= cost;
1959
+ const offset = Number(body.value.offset);
1960
+ if (!Number.isSafeInteger(offset)) {
1961
+ this.fail("output_offset_overflow", "Process offset exceeds JavaScript integer precision");
1962
+ return;
1963
+ }
1964
+ this.events.dispatchEvent(new MessageEvent("message", { data: {
1965
+ stream: body.case,
1966
+ offset,
1967
+ data: body.value.data,
1968
+ cost
1969
+ } }));
1970
+ return;
1971
+ }
1972
+ case "exit": {
1973
+ const status = {
1974
+ [Exit_Status.COMPLETED]: "completed",
1975
+ [Exit_Status.FAILED]: "failed",
1976
+ [Exit_Status.CANCELLED]: "cancelled",
1977
+ [Exit_Status.TIMED_OUT]: "timed_out"
1978
+ }[body.value.status];
1979
+ if (!status) {
1980
+ this.fail("unsupported_exit_status", `Unknown process exit status ${body.value.status}`);
1981
+ return;
1982
+ }
1983
+ event = {
1984
+ type: "exit",
1985
+ status,
1986
+ exit_code: body.value.exitCode,
1987
+ exit_reason: body.value.exitReason,
1988
+ cursor: Number(body.value.cursor)
1989
+ };
1990
+ break;
1991
+ }
1992
+ case "error":
1993
+ event = {
1994
+ type: "error",
1995
+ error: body.value.code,
1996
+ message: body.value.message
1997
+ };
1998
+ break;
1999
+ case "killed":
2000
+ case "resized":
2001
+ event = { type: body.case };
2002
+ break;
2003
+ case "detached":
2004
+ this.finish();
2005
+ return;
2006
+ case void 0: return;
2007
+ default: throw new Error("Unexpected process channel message");
2008
+ }
2009
+ this.events.dispatchEvent(new MessageEvent("message", { data: event }));
2010
+ if ([
2011
+ "exit",
2012
+ "error",
2013
+ "killed",
2014
+ "resized"
2015
+ ].includes(body.case)) this.finish();
2016
+ }
2017
+ /** Fails only this channel, for a message whose value it cannot represent. */
2018
+ fail(error, message) {
2019
+ if (this.readyState === WebSocket.OPEN) this.connection.send(this.id, create(ClientFrameSchema, { body: {
2020
+ case: "detach",
2021
+ value: {}
2022
+ } }).body);
2023
+ this.events.dispatchEvent(new MessageEvent("message", { data: {
2024
+ type: "error",
2025
+ error,
2026
+ message
2027
+ } }));
2028
+ this.finish();
2029
+ }
2030
+ finish(reason) {
2031
+ if (this.readyState === WebSocket.CLOSED) return;
2032
+ if (reason) this.events.dispatchEvent(new MessageEvent("message", { data: {
2033
+ type: "error",
2034
+ error: "connection_closed",
2035
+ message: String(reason)
2036
+ } }));
2037
+ this.readyState = WebSocket.CLOSED;
2038
+ this.creditChanged?.();
2039
+ this.connection.remove(this.id);
2040
+ this.events.dispatchEvent(new Event("close"));
2041
+ }
2042
+ };
2043
+ //#endregion
2044
+ //#region src/sandbox-process.ts
2045
+ /** @deprecated Use Sandbox.run() and Sandbox.attach(). Removed in the next version. */
2046
+ var SandboxProcesses = class {
2047
+ _sandbox;
2048
+ _disconnect;
2049
+ /** @internal */
2050
+ constructor(_sandbox, _disconnect) {
2051
+ this._sandbox = _sandbox;
2052
+ this._disconnect = _disconnect;
2053
+ }
2054
+ /** @deprecated Use sandbox.run(). Removed in the next version. */
2055
+ start(command, options = {}) {
2056
+ return this._sandbox.run(command, options);
2057
+ }
2058
+ /** @deprecated Use sandbox.attach(). Removed in the next version. */
2059
+ connect(processId, options = {}) {
2060
+ return this._sandbox.attach(processId, options);
2061
+ }
2062
+ /** Disconnect process transport without terminating guest processes. */
2063
+ async disconnect() {
2064
+ this._disconnect();
2065
+ }
2066
+ };
2067
+ var SandboxProcess = class {
2068
+ _collectOutput;
2069
+ _buffer;
2070
+ _openConnection;
2071
+ _controlProcess;
2072
+ status = "running";
2073
+ stdout = "";
2074
+ stderr = "";
2075
+ _id;
2076
+ _cursor;
2077
+ _deliveredCursor;
2078
+ _stdoutDecoder = new TextDecoder();
2079
+ _stderrDecoder = new TextDecoder();
2080
+ _socket;
2081
+ _closed;
2082
+ _manual = false;
2083
+ _stdinClosed = false;
2084
+ _iteratorTaken = false;
2085
+ /** Settles once onOutput has handled the last chunk. */
2086
+ _delivered;
2087
+ _wake;
2088
+ _error;
2089
+ _exit;
2090
+ _result;
2091
+ /** Returns each buffered binary output's credit once the iterator takes it. */
2092
+ _releases = /* @__PURE__ */ new WeakMap();
2093
+ _resolveDone;
2094
+ _done = new Promise((resolve) => {
2095
+ this._resolveDone = resolve;
2096
+ });
2097
+ /** Pull output from the shared buffer. One iterator may consume each handle. */
2098
+ output = { [Symbol.asyncIterator]: () => {
2099
+ if (this._iteratorTaken) throw new Error("Process output already has a consumer: an output iterator or onOutput");
2100
+ this._iteratorTaken = true;
2101
+ return this._iterateOutput();
2102
+ } };
2103
+ /** @internal */
2104
+ constructor(processId, cursor, _collectOutput, _buffer, _openConnection, _controlProcess) {
2105
+ this._collectOutput = _collectOutput;
2106
+ this._buffer = _buffer;
2107
+ this._openConnection = _openConnection;
2108
+ this._controlProcess = _controlProcess;
2109
+ this._id = processId;
2110
+ this._cursor = cursor;
2111
+ this._deliveredCursor = cursor;
2112
+ }
2113
+ get id() {
2114
+ return this._id;
2115
+ }
2116
+ /** Next byte after output accepted into the SDK buffer. */
2117
+ get cursor() {
2118
+ return this._cursor;
2119
+ }
2120
+ get connected() {
2121
+ return this._socket?.readyState === WebSocket.OPEN;
2122
+ }
2123
+ /** Resolves once the runtime has accepted the input; waits while the process is not reading. */
2124
+ async sendInput(data) {
2125
+ if (this._stdinClosed) throw new Error("Process stdin is closed");
2126
+ const bytes = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
2127
+ await this._openSocket().send(bytes);
2128
+ }
2129
+ async closeStdin() {
2130
+ if (this._stdinClosed) return;
2131
+ this._stdinClosed = true;
2132
+ try {
2133
+ await this._openSocket().closeStdin();
2134
+ } catch (error) {
2135
+ this._stdinClosed = false;
2136
+ throw error;
2137
+ }
2138
+ }
2139
+ async resize(size) {
2140
+ if (this.status !== "running") throw new Error("Process has exited");
2141
+ await this._controlProcess({
2142
+ type: "resize",
2143
+ process_id: this._id,
2144
+ ...size
2145
+ });
2146
+ }
2147
+ async kill() {
2148
+ if (!this._exit) await this._controlProcess({
2149
+ type: "kill",
2150
+ process_id: this._id
2151
+ });
2152
+ }
2153
+ async disconnect() {
2154
+ this._manual = true;
2155
+ this._socket?.close();
2156
+ await this._closed;
2157
+ if (!this._exit) this._fail(/* @__PURE__ */ new Error("Process is disconnected"));
2158
+ }
2159
+ async wait() {
2160
+ if (!this._iteratorTaken) for await (const _output of this.output);
2161
+ await this._delivered;
2162
+ await this._done;
2163
+ if (this._error) throw this._error;
2164
+ return this._result;
2165
+ }
2166
+ /** @internal Feeds `output` to `handler`, waiting for each call to settle. */
2167
+ _deliverTo(handler) {
2168
+ const iterator = this.output[Symbol.asyncIterator]();
2169
+ this._delivered = (async () => {
2170
+ try {
2171
+ for (let next = await iterator.next(); !next.done; next = await iterator.next()) await handler(next.value);
2172
+ } catch (error) {
2173
+ this._fail(error);
2174
+ await iterator.return?.(void 0);
2175
+ if (!this._exit) await this.disconnect();
2176
+ }
2177
+ })();
2178
+ }
2179
+ async *_iterateOutput() {
2180
+ try {
2181
+ while (true) {
2182
+ const output = this._buffer.take(this);
2183
+ if (output) {
2184
+ this._releases.get(output)?.();
2185
+ this._deliveredCursor = output.offset + output.data.length;
2186
+ if (this._collectOutput) this._appendText(output.stream, (output.stream === "stdout" ? this._stdoutDecoder : this._stderrDecoder).decode(output.data, { stream: true }));
2187
+ this._complete();
2188
+ yield output;
2189
+ } else {
2190
+ this._complete();
2191
+ if (this._error) throw this._error;
2192
+ if (this._exit) return;
2193
+ await new Promise((resolve) => {
2194
+ this._wake = resolve;
2195
+ });
2196
+ this._wake = void 0;
2197
+ }
2198
+ }
2199
+ } finally {
2200
+ if (!this._exit && !this._error) await this.disconnect();
2201
+ this._buffer.discard(this);
2202
+ this._cursor = this._deliveredCursor;
2203
+ this._complete();
2204
+ }
2205
+ }
2206
+ /** @internal */
2207
+ async _connect(request) {
2208
+ const socket = await this._openConnection();
2209
+ if (this._manual) {
2210
+ socket.close();
2211
+ throw new Error("Process is disconnected");
2212
+ }
2213
+ this._socket = socket;
2214
+ let closed;
2215
+ this._closed = new Promise((resolve) => {
2216
+ closed = resolve;
2217
+ });
2218
+ const expected = request.type === "start" ? "started" : "attached";
2219
+ let settled = false;
2220
+ let resolveReady;
2221
+ let rejectReady;
2222
+ const ready = new Promise((resolve, reject) => {
2223
+ resolveReady = resolve;
2224
+ rejectReady = reject;
2225
+ });
2226
+ socket.addEventListener("message", (message) => {
2227
+ if (this._socket !== socket) return;
2228
+ try {
2229
+ const data = message.data;
2230
+ if ("stream" in data) {
2231
+ this._enqueueOutput(data.data, data.offset, data.stream, () => socket.release(data.cost));
2232
+ return;
2233
+ }
2234
+ const event = data;
2235
+ switch (event.type) {
2236
+ case "started":
2237
+ case "attached":
2238
+ if (event.type !== expected || this._id && this._id !== event.process_id) throw new Error("Unexpected process identity");
2239
+ this._id = event.process_id;
2240
+ settled = true;
2241
+ resolveReady();
2242
+ break;
2243
+ case "exit":
2244
+ this._exit = event;
2245
+ this.status = event.status;
2246
+ this._stdinClosed = true;
2247
+ this._complete();
2248
+ this._wake?.();
2249
+ break;
2250
+ case "error": throw new Error(`${event.error}: ${event.message}`);
2251
+ }
2252
+ } catch (error) {
2253
+ const failure = error instanceof Error ? error : new Error(String(error));
2254
+ if (!settled) rejectReady(failure);
2255
+ this._fail(failure);
2256
+ socket.close();
2257
+ }
2258
+ });
2259
+ socket.addEventListener("error", () => {
2260
+ const error = /* @__PURE__ */ new Error("Process connection failed");
2261
+ if (!settled) rejectReady(error);
2262
+ this._fail(error);
2263
+ });
2264
+ socket.addEventListener("close", () => {
2265
+ if (this._socket === socket) this._socket = void 0;
2266
+ closed();
2267
+ if (!settled) rejectReady(/* @__PURE__ */ new Error("Process connection closed before ready"));
2268
+ if (!this._exit && !this._manual) this._fail(/* @__PURE__ */ new Error("Process connection closed before exit"));
2269
+ }, { once: true });
2270
+ try {
2271
+ socket.sendRequest(request);
2272
+ } catch (error) {
2273
+ rejectReady(error instanceof Error ? error : new Error(String(error)));
2274
+ this._fail(error);
2275
+ socket.close();
2276
+ }
2277
+ await ready;
2278
+ }
2279
+ _openSocket() {
2280
+ if (this.status !== "running") throw new Error("Process has exited");
2281
+ if (!this.connected) throw new Error("Process is disconnected");
2282
+ return this._socket;
2283
+ }
2284
+ _fail(error) {
2285
+ this._error ??= error instanceof Error ? error : new Error(String(error));
2286
+ this._resolveDone();
2287
+ this._wake?.();
2288
+ }
2289
+ _complete() {
2290
+ if (!this._exit || this._buffer.has(this) || this._result) return;
2291
+ this._flushDecoders();
2292
+ this._result = {
2293
+ status: this._exit.status,
2294
+ exitCode: this._exit.exit_code ?? void 0,
2295
+ exitReason: this._exit.exit_reason ?? void 0,
2296
+ stdout: this.stdout,
2297
+ stderr: this.stderr
2298
+ };
2299
+ this._resolveDone();
2300
+ }
2301
+ /** `release` returns the output's flow-control credit once it is consumed. */
2302
+ _enqueueOutput(payload, offset, stream, release) {
2303
+ const end = offset + payload.byteLength;
2304
+ if (end <= this._cursor) {
2305
+ release();
2306
+ return;
2307
+ }
2308
+ if (offset > this._cursor) throw new Error(`Process output gap: expected offset ${this._cursor}, received ${offset}`);
2309
+ const skip = this._cursor - offset;
2310
+ const output = {
2311
+ stream,
2312
+ offset: this._cursor,
2313
+ data: payload.slice(skip)
2314
+ };
2315
+ this._buffer.push(this, output);
2316
+ this._releases.set(output, release);
2317
+ this._cursor = end;
2318
+ this._wake?.();
2319
+ }
2320
+ _appendText(stream, data) {
2321
+ if (stream === "stdout") this.stdout += data;
2322
+ else this.stderr += data;
2323
+ }
2324
+ _flushDecoders() {
2325
+ if (!this._collectOutput) return;
2326
+ this._appendText("stdout", this._stdoutDecoder.decode());
2327
+ this._appendText("stderr", this._stderrDecoder.decode());
2328
+ }
2329
+ };
2330
+ //#endregion
2331
+ //#region src/sandbox-files.ts
2332
+ const DOWNLOAD_CHUNK_BYTES = 512 * 1024;
2333
+ const UPLOAD_COMMAND = `set -eu
2334
+ mkdir -p "$ARCHIL_FILE_PARENT"
2335
+ trap 'rm -f "$ARCHIL_FILE_TEMP"' EXIT HUP INT TERM
2336
+ : > "$ARCHIL_FILE_TEMP"
2337
+ cat > "$ARCHIL_FILE_TEMP"
2338
+ chmod "$ARCHIL_FILE_MODE" "$ARCHIL_FILE_TEMP"
2339
+ mv -f "$ARCHIL_FILE_TEMP" "$ARCHIL_FILE_TARGET"
2340
+ trap - EXIT HUP INT TERM`;
2341
+ const DOWNLOAD_COMMAND = `set -eu
2342
+ trap 'rm -f "$ARCHIL_FILE_TEMP"' EXIT HUP INT TERM
2343
+ exec 3< "$ARCHIL_FILE_PATH"
2344
+ while IFS= read -r count; do
2345
+ dd bs="$count" count=1 <&3 > "$ARCHIL_FILE_TEMP" 2>/dev/null
2346
+ size=$(wc -c < "$ARCHIL_FILE_TEMP")
2347
+ printf '%s\n' "$size"
2348
+ cat "$ARCHIL_FILE_TEMP"
2349
+ [ "$size" -eq "$count" ] || break
2350
+ done`;
2351
+ var ProcessOutputReader = class {
2352
+ _buffer = /* @__PURE__ */ new Uint8Array();
2353
+ _cursor = 0;
2354
+ _stderrDecoder = new TextDecoder();
2355
+ _stderr = "";
2356
+ _process;
2357
+ _output;
2358
+ attach(process) {
2359
+ this._process = process;
2360
+ this._output = process.output[Symbol.asyncIterator]();
2361
+ }
2362
+ async readLine() {
2363
+ while (true) {
2364
+ const newline = this._buffer.indexOf(10);
2365
+ if (newline >= 0) {
2366
+ const line = this._buffer.slice(0, newline);
2367
+ this._buffer = this._buffer.slice(newline + 1);
2368
+ return line;
2369
+ }
2370
+ this._buffer = concat(this._buffer, await this._nextChunk());
2371
+ }
2372
+ }
2373
+ async read(size) {
2374
+ while (this._buffer.length < size) this._buffer = concat(this._buffer, await this._nextChunk());
2375
+ const data = this._buffer.slice(0, size);
2376
+ this._buffer = this._buffer.slice(size);
2377
+ return data;
2378
+ }
2379
+ async wait() {
2380
+ while (!(await this._output.next()).done);
2381
+ assertSuccessful(await this._process.wait(), this._stderr + this._stderrDecoder.decode());
2382
+ }
2383
+ async _nextChunk() {
2384
+ while (true) {
2385
+ const next = await this._output.next();
2386
+ if (next.done) {
2387
+ assertSuccessful(await this._process.wait(), this._stderr + this._stderrDecoder.decode());
2388
+ throw new Error("Sandbox process exited before file transfer completed");
2389
+ }
2390
+ const output = next.value;
2391
+ if (output.offset !== this._cursor) throw new Error(`Sandbox process output gap: expected offset ${this._cursor}, received ${output.offset}`);
2392
+ this._cursor += output.data.length;
2393
+ if (output.stream === "stdout") return output.data;
2394
+ this._stderr += this._stderrDecoder.decode(output.data, { stream: true });
2395
+ }
2396
+ }
2397
+ };
2398
+ var SandboxFiles = class {
2399
+ _sandbox;
2400
+ /** @internal */
2401
+ constructor(sandbox) {
2402
+ this._sandbox = sandbox;
2403
+ }
2404
+ async uploadFile(source, remotePath, options = {}) {
2405
+ const { path, parent } = remoteFilePath(remotePath);
2406
+ const mode = options.mode ?? 420;
2407
+ if (!Number.isInteger(mode) || mode < 0 || mode > 4095) throw new RangeError("mode must be between 0 and 0o7777");
2408
+ let process;
2409
+ try {
2410
+ process = await this._sandbox.run(UPLOAD_COMMAND, { env: {
2411
+ ARCHIL_FILE_PARENT: parent,
2412
+ ARCHIL_FILE_TARGET: path,
2413
+ ARCHIL_FILE_TEMP: `${parent}/.archil-upload-${transferId()}`,
2414
+ ARCHIL_FILE_MODE: mode.toString(8)
2415
+ } });
2416
+ for await (const chunk of fileChunks(source)) await process.sendInput(chunk);
2417
+ await process.closeStdin();
2418
+ assertSuccessful(await process.wait());
2419
+ } catch (error) {
2420
+ if (process) await abort(process);
2421
+ if (error instanceof RangeError || error instanceof TypeError) throw error;
2422
+ throw new SandboxFileTransferError("upload", path, toError(error));
2423
+ } finally {
2424
+ await process?.disconnect();
2425
+ }
2426
+ }
2427
+ async downloadFile(remotePath, write) {
2428
+ const { path } = remoteFilePath(remotePath);
2429
+ const reader = new ProcessOutputReader();
2430
+ let process;
2431
+ try {
2432
+ process = await this._sandbox.run(DOWNLOAD_COMMAND, {
2433
+ env: {
2434
+ ARCHIL_FILE_PATH: path,
2435
+ ARCHIL_FILE_TEMP: `/tmp/.archil-download-${transferId()}`
2436
+ },
2437
+ collectOutput: false
2438
+ });
2439
+ reader.attach(process);
2440
+ while (true) {
2441
+ await process.sendInput(`${DOWNLOAD_CHUNK_BYTES}\n`);
2442
+ const sizeText = new TextDecoder().decode(await reader.readLine()).trim();
2443
+ const size = Number(sizeText);
2444
+ if (!Number.isSafeInteger(size) || size < 0 || size > DOWNLOAD_CHUNK_BYTES) throw new Error(`Sandbox returned an invalid chunk size: ${JSON.stringify(sizeText)}`);
2445
+ if (size === 0) break;
2446
+ await write(await reader.read(size));
2447
+ if (size < DOWNLOAD_CHUNK_BYTES) break;
2448
+ }
2449
+ await reader.wait();
2450
+ } catch (error) {
2451
+ if (process) await abort(process);
2452
+ if (error instanceof RangeError || error instanceof TypeError) throw error;
2453
+ throw new SandboxFileTransferError("download", path, toError(error));
2454
+ } finally {
2455
+ await process?.disconnect();
2456
+ }
2457
+ }
2458
+ };
2459
+ async function* fileChunks(source) {
2460
+ if (source instanceof Uint8Array) {
2461
+ yield source;
2462
+ return;
2463
+ }
2464
+ if (source instanceof ArrayBuffer) {
2465
+ yield new Uint8Array(source);
2466
+ return;
2467
+ }
2468
+ if (source instanceof Blob) {
2469
+ yield* readableChunks(source.stream());
2470
+ return;
2471
+ }
2472
+ if (Symbol.asyncIterator in source) {
2473
+ for await (const chunk of source) yield new Uint8Array(chunk);
2474
+ return;
2475
+ }
2476
+ yield* readableChunks(source);
2477
+ }
2478
+ async function* readableChunks(source) {
2479
+ const reader = source.getReader();
2480
+ try {
2481
+ while (true) {
2482
+ const { done, value } = await reader.read();
2483
+ if (done) return;
2484
+ yield value;
2485
+ }
2486
+ } finally {
2487
+ reader.releaseLock();
2488
+ }
2489
+ }
2490
+ function remoteFilePath(path) {
2491
+ if (path.includes("\0")) throw new TypeError("remote path cannot contain NUL");
2492
+ if (!path.startsWith("/") || path.endsWith("/")) throw new TypeError("remote path must be an absolute file path");
2493
+ return {
2494
+ path,
2495
+ parent: path.slice(0, path.lastIndexOf("/")) || "/"
2496
+ };
2497
+ }
2498
+ function assertSuccessful(result, stderr = result.stderr) {
2499
+ if (result.status === "completed" && result.exitCode === 0) return;
2500
+ throw new Error(stderr.trim() || result.exitReason || `exit code ${String(result.exitCode)}`);
2501
+ }
2502
+ async function abort(process) {
2503
+ try {
2504
+ await process.kill();
2505
+ } catch {}
2506
+ }
2507
+ function transferId() {
2508
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
2509
+ }
2510
+ function concat(left, right) {
2511
+ const result = new Uint8Array(left.byteLength + right.byteLength);
2512
+ result.set(left);
2513
+ result.set(right, left.byteLength);
2514
+ return result;
2515
+ }
2516
+ function toError(error) {
2517
+ return error instanceof Error ? error : new Error(String(error));
2518
+ }
2519
+ //#endregion
2520
+ //#region src/sandbox.ts
2521
+ /** @internal */
2522
+ function sandboxMountWire(mount) {
2523
+ const entry = {
2524
+ disk_id: typeof mount.disk === "string" ? mount.disk : mount.disk.id,
2525
+ read_only: mount.readOnly ?? false,
2526
+ conditional: mount.conditional ?? false
2527
+ };
2528
+ if (mount.path !== void 0) entry.path = mount.path;
2529
+ if (mount.subdirectory !== void 0) entry.subdirectory = mount.subdirectory;
2530
+ if (mount.queueMs !== void 0) entry.queue_ms = mount.queueMs;
2531
+ return entry;
2532
+ }
2533
+ function sandboxMountFromWire(mount) {
2534
+ const out = {
2535
+ diskId: mount.disk_id,
2536
+ path: mount.path,
2537
+ readOnly: mount.read_only ?? false,
2538
+ conditional: mount.conditional ?? false
2539
+ };
2540
+ if (mount.subdirectory !== void 0) out.subdirectory = mount.subdirectory;
2541
+ if (mount.queue_ms !== void 0) out.queueMs = mount.queue_ms;
2542
+ return out;
2543
+ }
2544
+ function portTokenFromWire(data) {
2545
+ return {
2546
+ id: data.id,
2547
+ port: data.port,
2548
+ createdAt: new Date(data.created_at),
2549
+ expiresAt: data.expires_at ? new Date(data.expires_at) : void 0
2550
+ };
2551
+ }
2552
+ const POLL_INTERVAL_MS = 500;
2553
+ function sleep() {
2554
+ return new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
2555
+ }
2556
+ var Sandbox = class Sandbox {
2557
+ id;
2558
+ name;
2559
+ labels;
2560
+ status;
2561
+ vcpuCount;
2562
+ memSizeMiB;
2563
+ baseImage;
2564
+ imageDigest;
2565
+ platform;
2566
+ maxTtlSeconds;
2567
+ idleTtlSeconds;
2568
+ onTimeout;
2569
+ maxConcurrentExecs;
2570
+ endpoints;
2571
+ mounts;
2572
+ createdAt;
2573
+ runningAt;
2574
+ finishedAt;
2575
+ lastActiveAt;
2576
+ exitReason;
2577
+ checkpoint;
2578
+ /** @deprecated Use run() and attach(). Removed in the next version. */
2579
+ processes;
2580
+ files;
2581
+ /** @internal */
2582
+ _client;
2583
+ _processConnection;
2584
+ _processOutput = new ProcessOutputBuffer();
2585
+ /** @internal */
2586
+ constructor(data, client) {
2587
+ this._client = client;
2588
+ this._apply(data);
2589
+ this._processConnection = new ProcessConnection(() => this._connectionEndpoint());
2590
+ this.processes = new SandboxProcesses(this, () => this._processConnection.disconnect());
2591
+ this.files = new SandboxFiles(this);
2592
+ }
2593
+ /** @internal Overwrite this sandbox's fields in place from a fresh wire snapshot. */
2594
+ _apply(data) {
2595
+ this.id = data.sandbox_id;
2596
+ this.name = data.name;
2597
+ this.labels = { ...data.labels };
2598
+ this.status = data.status;
2599
+ this.vcpuCount = data.vcpu_count;
2600
+ this.memSizeMiB = data.mem_size_mib;
2601
+ this.baseImage = data.base_image;
2602
+ this.imageDigest = data.image_digest ?? "";
2603
+ this.platform = data.platform;
2604
+ this.maxTtlSeconds = data.max_ttl_seconds;
2605
+ this.idleTtlSeconds = data.idle_ttl_seconds ?? 0;
2606
+ this.onTimeout = data.on_timeout ?? "pause";
2607
+ this.maxConcurrentExecs = data.max_concurrent_execs;
2608
+ this.endpoints = data.endpoints?.map((endpoint) => ({ ...endpoint }));
2609
+ this.mounts = (data.mounts ?? []).map(sandboxMountFromWire);
2610
+ this.createdAt = new Date(data.created_at);
2611
+ this.runningAt = data.running_at ? new Date(data.running_at) : void 0;
2612
+ this.finishedAt = data.finished_at ? new Date(data.finished_at) : void 0;
2613
+ this.lastActiveAt = new Date(data.last_active_at);
2614
+ this.exitReason = data.exit_reason;
2615
+ this.checkpoint = data.checkpoint;
2616
+ return this;
2617
+ }
2618
+ toJSON() {
2619
+ return {
2620
+ id: this.id,
2621
+ name: this.name,
2622
+ labels: { ...this.labels },
2623
+ status: this.status,
2624
+ vcpuCount: this.vcpuCount,
2625
+ memSizeMiB: this.memSizeMiB,
2626
+ baseImage: this.baseImage,
2627
+ imageDigest: this.imageDigest,
2628
+ platform: this.platform,
2629
+ maxTtlSeconds: this.maxTtlSeconds,
2630
+ idleTtlSeconds: this.idleTtlSeconds,
2631
+ onTimeout: this.onTimeout,
2632
+ maxConcurrentExecs: this.maxConcurrentExecs,
2633
+ endpoints: this.endpoints?.map((endpoint) => ({ ...endpoint })),
2634
+ mounts: this.mounts.map((mount) => ({ ...mount })),
2635
+ createdAt: this.createdAt,
2636
+ runningAt: this.runningAt,
2637
+ finishedAt: this.finishedAt,
2638
+ lastActiveAt: this.lastActiveAt,
2639
+ exitReason: this.exitReason,
2640
+ checkpoint: this.checkpoint
2641
+ };
2642
+ }
2643
+ /** Start a process and return its handle without waiting for exit. */
2644
+ async run(command, options = {}) {
2645
+ const process = new SandboxProcess("", 0, options.collectOutput ?? true, this._processOutput, () => this._processConnection.open(), (request) => this._control(request));
2646
+ const terminal = typeof options.terminal === "object" ? {
2647
+ cols: options.terminal.cols ?? 80,
2648
+ rows: options.terminal.rows ?? 24
2649
+ } : options.terminal;
2650
+ await process._connect({
2651
+ type: "start",
2652
+ command,
2653
+ cwd: options.cwd,
2654
+ terminal,
2655
+ env: options.env ?? {},
2656
+ timeout_seconds: options.timeoutSeconds
2657
+ });
2658
+ if (options.onOutput) process._deliverTo(options.onOutput);
2659
+ return process;
2660
+ }
2661
+ /** Reattach to a process, optionally resuming output from a cursor. */
2662
+ async attach(processId, options = {}) {
2663
+ const offset = options.offset ?? 0;
2664
+ const process = new SandboxProcess(processId, offset, options.collectOutput ?? true, this._processOutput, () => this._processConnection.open(), (request) => this._control(request));
2665
+ await process._connect({
2666
+ type: "attach",
2667
+ process_id: processId,
2668
+ offset,
2669
+ ...options.shared ? { shared: true } : {}
2670
+ });
2671
+ if (options.onOutput) process._deliverTo(options.onOutput);
2672
+ return process;
2673
+ }
2674
+ async _connectionEndpoint() {
2675
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this.id } } }), "transient"));
2676
+ return {
2677
+ url: data.endpoint,
2678
+ token: data.token
2679
+ };
2680
+ }
2681
+ async _control(request) {
2682
+ const socket = await this._processConnection.open();
2683
+ const expected = request.type === "kill" ? "killed" : "resized";
2684
+ await new Promise((resolve, reject) => {
2685
+ socket.addEventListener("message", (message) => {
2686
+ try {
2687
+ const event = message.data;
2688
+ if (event.type === "error") reject(/* @__PURE__ */ new Error(`${event.error}: ${event.message}`));
2689
+ else if (event.type !== expected) reject(/* @__PURE__ */ new Error(`Expected ${expected}, received ${event.type}`));
2690
+ else resolve();
2691
+ } catch (error) {
2692
+ reject(error);
2693
+ } finally {
2694
+ socket.close();
2695
+ }
2696
+ }, { once: true });
2697
+ socket.addEventListener("error", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} request failed`)));
2698
+ socket.addEventListener("close", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} connection closed before confirmation`)));
2699
+ try {
2700
+ socket.sendRequest(request);
2701
+ } catch (error) {
2702
+ reject(error);
2703
+ socket.finish();
2704
+ }
2705
+ });
2706
+ }
2707
+ /** Run a process and wait for it to exit. */
2708
+ async exec(command, options = {}) {
2709
+ return (await this.run(command, options)).wait();
2710
+ }
2711
+ /** Re-fetch this sandbox. */
2712
+ async refresh() {
2713
+ const data = await unwrap(retryApiRequest(() => this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }), "transient"));
2714
+ return this._apply(data);
2715
+ }
2716
+ /** Start this sandbox. */
2717
+ async start(options = {}) {
2718
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/start", {
2719
+ params: {
2720
+ path: { sid: this.id },
2721
+ query: { wait: options.wait ?? true }
2722
+ },
2723
+ ...options.mounts !== void 0 && { body: { mounts: options.mounts.map(sandboxMountWire) } }
2724
+ }), options.mounts === void 0 ? "transient" : "connect"));
2725
+ this._apply(data);
2726
+ return options.wait === false ? this : waitForSandboxStart(this);
2727
+ }
2728
+ /** Stop this sandbox. */
2729
+ async stop(options = {}) {
2730
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/stop", { params: { path: { sid: this.id } } }), "transient"));
2731
+ this._apply(data);
2732
+ return options.wait === false ? this : waitWhileSandboxStatus(this, "stopping");
2733
+ }
2734
+ /** Pause this sandbox, preserving its CPU and memory state. */
2735
+ async pause(options = {}) {
2736
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/pause", { params: { path: { sid: this.id } } }), "transient"));
2737
+ this._apply(data);
2738
+ if (options.wait === false) return this;
2739
+ await waitWhileSandboxStatus(this, "pausing");
2740
+ if (this.status !== "paused") throw new SandboxPauseError(this);
2741
+ return this;
2742
+ }
2743
+ /** Resume this sandbox from its preserved CPU and memory state. */
2744
+ async resume(options = {}) {
2745
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/resume", { params: {
2746
+ path: { sid: this.id },
2747
+ query: { wait: options.wait ?? true }
2748
+ } }), "transient"));
2749
+ this._apply(data);
2750
+ return options.wait === false ? this : waitForSandboxStart(this);
2751
+ }
2752
+ /**
2753
+ * Create an isolated writable branch from this sandbox's current state.
2754
+ * A running sandbox is paused for the snapshot and resumed once the fork is
2755
+ * accepted; a paused or stopped sandbox is left as it is. The fork names the
2756
+ * checkpoint the pause returned, so it does not depend on the source still
2757
+ * being paused when the request lands. Resuming the source is best effort:
2758
+ * the child is returned even if the source could not be resumed, so check
2759
+ * the source's status afterwards if that matters.
2760
+ */
2761
+ async fork(options = {}) {
2762
+ const paused = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/pause", { params: { path: { sid: this.id } } }), "transient"));
2763
+ this._apply(paused);
2764
+ const resumeAfterFork = this.status === "pausing";
2765
+ const checkpoint = this.checkpoint;
2766
+ const wait = resumeAfterFork ? false : options.wait ?? true;
2767
+ const body = {
2768
+ name: options.name,
2769
+ checkpoint,
2770
+ labels: options.labels
2771
+ };
2772
+ const fork = await waitWhileSandboxStatus(this, "pausing").then(() => unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/fork", {
2773
+ params: {
2774
+ path: { sid: this.id },
2775
+ query: { wait }
2776
+ },
2777
+ body
2778
+ }), "connect"))).then((data) => new Sandbox(data, this._client)).finally(() => resumeAfterFork ? this.resume({ wait: false }).catch(() => void 0) : void 0);
2779
+ if (options.wait === false) return fork;
2780
+ await waitForSandboxStart(fork);
2781
+ if (resumeAfterFork) await waitForSandboxStart(this).catch(() => void 0);
2782
+ return fork;
2783
+ }
2784
+ /** Expose a TCP port publicly (1–65535), returning its hostname. */
2785
+ async exposePort(port) {
2786
+ const client = this._client;
2787
+ return (await unwrap(retryApiRequest(() => client.PUT("/api/sandboxes/{sid}/ports/{port}", { params: { path: {
2788
+ sid: this.id,
2789
+ port
2790
+ } } }), "transient"))).hostname;
2791
+ }
2792
+ /** List explicitly exposed public ports. Service-published ports are in `endpoints`. */
2793
+ async listPorts() {
2794
+ const client = this._client;
2795
+ return (await unwrap(retryApiRequest(() => client.GET("/api/sandboxes/{sid}/ports", { params: { path: { sid: this.id } } }), "transient"))).ports;
2796
+ }
2797
+ /** Remove explicit public exposure. A service publishing the same port remains reachable. */
2798
+ async unexposePort(port) {
2799
+ const client = this._client;
2800
+ await unwrapEmpty(retryApiRequest(() => client.DELETE("/api/sandboxes/{sid}/ports/{port}", { params: { path: {
2801
+ sid: this.id,
2802
+ port
2803
+ } } }), "transient"));
2804
+ }
2805
+ /** Authorize HTTP access to one port without making it public. */
2806
+ async createPortToken(port, options = {}) {
2807
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/port-tokens", {
2808
+ params: { path: { sid: this.id } },
2809
+ body: {
2810
+ port,
2811
+ ttl: options.ttl
2812
+ }
2813
+ }), "connect"));
2814
+ return {
2815
+ ...portTokenFromWire(data),
2816
+ hostname: data.hostname,
2817
+ token: data.token
2818
+ };
2819
+ }
2820
+ /** Get token metadata. Expired and revoked tokens return not found. */
2821
+ async getPortToken(tokenId) {
2822
+ return portTokenFromWire(await unwrap(retryApiRequest(() => this._client.GET("/api/sandboxes/{sid}/port-tokens/{token_id}", { params: { path: {
2823
+ sid: this.id,
2824
+ token_id: tokenId
2825
+ } } }), "transient")));
2826
+ }
2827
+ /** List token metadata across pages. `limit` caps the total number returned. */
2828
+ async listPortTokens(options = {}) {
2829
+ const tokens = [];
2830
+ let cursor = options.cursor;
2831
+ for (;;) {
2832
+ const remaining = options.limit === void 0 ? void 0 : options.limit - tokens.length;
2833
+ if (remaining !== void 0 && remaining <= 0) return tokens;
2834
+ const page = await this.listPortTokensPage({
2835
+ limit: remaining === void 0 ? 100 : Math.min(remaining, 100),
2836
+ cursor
2837
+ });
2838
+ tokens.push(...page.tokens);
2839
+ if (!page.nextCursor) return tokens;
2840
+ cursor = page.nextCursor;
2841
+ }
2842
+ }
2843
+ /** Fetch one page of token metadata; pass `nextCursor` back as `cursor`. */
2844
+ async listPortTokensPage(options = {}) {
2845
+ const { data, nextCursor } = await unwrapPage(retryApiRequest(() => this._client.GET("/api/sandboxes/{sid}/port-tokens", { params: {
2846
+ path: { sid: this.id },
2847
+ query: {
2848
+ limit: options.limit ?? 100,
2849
+ cursor: options.cursor
2850
+ }
2851
+ } }), "transient"));
2852
+ return {
2853
+ tokens: data.tokens.map(portTokenFromWire),
2854
+ nextCursor
2855
+ };
2856
+ }
2857
+ /** Revoke a token for new connections. Existing connections remain open. */
2858
+ async deletePortToken(token) {
2859
+ const tokenId = typeof token === "string" ? token : token.id;
2860
+ await unwrapEmpty(retryApiRequest(() => this._client.DELETE("/api/sandboxes/{sid}/port-tokens/{token_id}", { params: { path: {
2861
+ sid: this.id,
2862
+ token_id: tokenId
2863
+ } } }), "transient"));
2864
+ }
2865
+ /** Get this running sandbox's effective network policy. */
2866
+ async getNetwork() {
2867
+ const client = this._client;
2868
+ return unwrap(retryApiRequest(() => client.GET("/api/sandboxes/{sid}/network", { params: { path: { sid: this.id } } }), "transient"));
2869
+ }
2870
+ /** Replace this running sandbox's complete network policy and return the effective policy. */
2871
+ async updateNetwork(network) {
2872
+ const client = this._client;
2873
+ return unwrap(retryApiRequest(() => client.PUT("/api/sandboxes/{sid}/network", {
2874
+ params: { path: { sid: this.id } },
2875
+ body: network
2876
+ }), "transient"));
2877
+ }
2878
+ /** Update either or both TTLs in seconds. Omitted settings remain unchanged. */
2879
+ async setTimeout(timeout) {
2880
+ const options = typeof timeout === "number" ? { timeoutSeconds: timeout } : timeout;
2881
+ const client = this._client;
2882
+ const data = await unwrap(retryApiRequest(() => client.POST("/api/sandboxes/{sid}/timeout", {
2883
+ params: { path: { sid: this.id } },
2884
+ body: {
2885
+ timeout: options.timeoutSeconds,
2886
+ idle_ttl_seconds: options.idleTtlSeconds
2887
+ }
2888
+ }), "transient"));
2889
+ return this._apply(data);
2890
+ }
2891
+ /** Delete this sandbox and its backing disk. */
2892
+ async delete() {
2893
+ await unwrapEmpty(retryApiRequest(() => this._client.DELETE("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }), "transient"));
2894
+ }
2895
+ };
2896
+ /** @internal Continue waiting if the server returned before startup completed. */
2897
+ async function waitForSandboxStart(sandbox) {
2898
+ return waitWhileSandboxStatus(sandbox, "pending");
2899
+ }
2900
+ async function waitWhileSandboxStatus(sandbox, status) {
2901
+ while (sandbox.status === status) {
2902
+ await sleep();
2903
+ await sandbox.refresh();
2904
+ }
2905
+ return sandbox;
2906
+ }
2907
+ //#endregion
2908
+ //#region src/sandboxes.ts
2909
+ /** Server-side maximum page size for `GET /api/sandboxes`. */
2910
+ const SANDBOX_PAGE_LIMIT = 100;
2911
+ function matchesListFilters(sandbox, options) {
2912
+ return Object.entries(options.labels ?? {}).every(([key, value]) => sandbox.labels?.[key] === value) && (options.name === void 0 || sandbox.name === options.name) && sandbox.name.startsWith(options.namePrefix ?? "");
2913
+ }
2914
+ var Sandboxes = class {
2915
+ /** @internal */
2916
+ _client;
2917
+ /** @internal */
2918
+ constructor(client) {
2919
+ this._client = client;
2920
+ }
2921
+ /**
2922
+ * List the account's sandboxes, oldest first, keeping those that match every
2923
+ * filter given. Follows the server's pages until none remain.
2924
+ */
2925
+ async list(options = {}) {
2926
+ const filesystem = typeof options.disk === "string" ? options.disk : options.disk?.id;
2927
+ const labels = Object.entries(options.labels ?? {}).map(([key, value]) => `${key}=${value}`);
2928
+ const client = this._client;
2929
+ const sandboxes = [];
2930
+ let cursor;
2931
+ for (;;) {
2932
+ const { data, nextCursor } = await unwrapPage(retryApiRequest(() => client.GET("/api/sandboxes", { params: { query: {
2933
+ filesystem,
2934
+ label: labels.length > 0 ? labels : void 0,
2935
+ name: options.name,
2936
+ name_prefix: options.namePrefix,
2937
+ limit: SANDBOX_PAGE_LIMIT,
2938
+ cursor
2939
+ } } }), "transient"));
2940
+ for (const sandbox of data?.sandboxes ?? []) if (matchesListFilters(sandbox, options)) sandboxes.push(new Sandbox(sandbox, this._client));
2941
+ if (!nextCursor || nextCursor === cursor) return sandboxes;
2942
+ cursor = nextCursor;
2943
+ }
2944
+ }
2945
+ async get(id) {
2946
+ return new Sandbox(await unwrap(retryApiRequest(() => this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: id } } }), "transient")), this._client);
2947
+ }
2948
+ async create(request = {}, options = {}) {
2949
+ const body = {
2950
+ name: request.name,
2951
+ vcpu_count: request.vcpuCount,
2952
+ mem_size_mib: request.memSizeMiB,
2953
+ base_image: request.baseImage,
2954
+ image_id: request.imageId,
2955
+ env: request.env,
2956
+ max_ttl_seconds: request.maxTtlSeconds,
2957
+ idle_ttl_seconds: request.idleTtlSeconds,
2958
+ on_timeout: request.onTimeout,
2959
+ max_concurrent_execs: request.maxConcurrentExecs,
2960
+ network: request.network,
2961
+ ports: request.ports,
2962
+ ...request.mounts !== void 0 && { mounts: request.mounts.map(sandboxMountWire) },
2963
+ labels: request.labels
2964
+ };
2965
+ const sandbox = new Sandbox(await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes", {
2966
+ params: { query: { wait: options.wait ?? true } },
2967
+ body
2968
+ }), "connect")), this._client);
2969
+ return options.wait === false ? sandbox : waitForSandboxStart(sandbox);
2970
+ }
2971
+ };
2972
+ //#endregion
2973
+ //#region src/tokens.ts
2974
+ var Tokens = class {
2975
+ /** @internal */
2976
+ _client;
2977
+ /** @internal */
2978
+ constructor(client) {
2979
+ this._client = client;
2980
+ }
2981
+ async list(opts) {
2982
+ return (await unwrap(retryApiRequest(() => this._client.GET("/api/tokens", { params: { query: {
2983
+ limit: opts?.limit,
2984
+ cursor: opts?.cursor
2985
+ } } }), "transient"))).tokens ?? [];
2986
+ }
2987
+ async create(req) {
2988
+ return await unwrap(retryApiRequest(() => this._client.POST("/api/tokens", { body: req }), "connect"));
2989
+ }
2990
+ async delete(id) {
2991
+ await unwrapEmpty(retryApiRequest(() => this._client.DELETE("/api/tokens/{tokenId}", { params: { path: { tokenId: id } } }), "connect"));
2992
+ }
2993
+ };
2994
+ //#endregion
2995
+ //#region src/workspace.ts
2996
+ function isExecMountSpec$1(m) {
2997
+ return typeof m === "object" && m !== null && "disk" in m;
2998
+ }
2999
+ /** Keep groups up to the one holding the `maxResults`-th match, and end that
3000
+ * group after up to `after` more lines, which become context so the groups
3001
+ * hold exactly the kept matches. With multiline, a run of matching lines is
3002
+ * one match. Mirrors the controlplane's truncation of a single disk's groups. */
3003
+ function truncateGroups(groups, maxResults, after, multiline) {
3004
+ let seen = 0;
3005
+ for (let i = 0; i < groups.length; i++) {
3006
+ const lines = groups[i].lines;
3007
+ for (let j = 0; j < lines.length; j++) {
3008
+ if (lines[j].match && !(multiline && j > 0 && lines[j - 1].match)) seen++;
3009
+ if (seen === maxResults && !(multiline && j + 1 < lines.length && lines[j + 1].match)) {
3010
+ const kept = lines.slice(0, Math.min(j + 1 + after, lines.length)).map((l, k) => k > j ? {
3011
+ ...l,
3012
+ match: false
3013
+ } : l);
3014
+ return [...groups.slice(0, i), {
3015
+ ...groups[i],
3016
+ lines: kept
3017
+ }];
3018
+ }
3019
+ }
3020
+ }
3021
+ return groups;
3022
+ }
3023
+ /**
3024
+ * A key-routed filesystem spanning several Archil disks. Each disk is mounted
3025
+ * under a name and addressed as the first segment of a key (`<name>/...`);
3026
+ * `getObject`, `putObject`, `deleteObject`, `listObjects`, and `grep` route to
3027
+ * the right disk by that segment (and `listObjects` / `grep` fan out across all
3028
+ * of them when the key/prefix doesn't name one). Implements the same
3029
+ * {@link FileSystem} surface as a single {@link Disk}, so it works anywhere a
3030
+ * disk does. Mounts can be changed at runtime with {@link addDisk} /
3031
+ * {@link removeDisk}.
3032
+ */
3033
+ var Workspace = class {
3034
+ client;
3035
+ mounts = /* @__PURE__ */ new Map();
3036
+ /** @internal Use `archil.workspace({ ... })`. */
3037
+ constructor(client, mounts) {
3038
+ this.client = client;
3039
+ for (const [name, value] of Object.entries(mounts)) this.addDisk(name, value);
3040
+ if (this.mounts.size === 0) throw new Error("workspace() needs at least one disk");
3041
+ }
3042
+ /** Mount (or replace) a disk at `name`; its objects are addressed as
3043
+ * `<name>/...`. Accepts a `Disk` or a mount spec (read-only / subdirectory /
3044
+ * conditional / delegation checkouts); a bare disk-id string is rejected —
3045
+ * fetch the disk first. */
3046
+ addDisk(name, disk) {
3047
+ const rel = name.replace(/^\/+|\/+$/g, "");
3048
+ if (!rel) throw new Error("workspace mount name must be non-empty");
3049
+ if (rel.includes("/")) throw new Error(`workspace mount name '${name}' must not contain '/'`);
3050
+ if (rel === "." || rel === "..") throw new Error(`workspace mount name '${name}' is reserved ('.' and '..' are path navigation, not disk names)`);
3051
+ let d;
3052
+ let readOnly = false;
3053
+ let subdirectory;
3054
+ let conditional = false;
3055
+ let queueMs;
3056
+ let checkoutPaths;
3057
+ if (isExecMountSpec$1(disk)) {
3058
+ d = disk.disk;
3059
+ readOnly = disk.readOnly ?? false;
3060
+ subdirectory = disk.subdirectory;
3061
+ conditional = disk.conditional ?? false;
3062
+ queueMs = disk.queueMs;
3063
+ checkoutPaths = disk.checkoutPaths;
3064
+ } else d = disk;
3065
+ if (typeof d === "string") throw new Error("workspace needs Disk objects, not disk-id strings; fetch with archil.getDisk(id) first");
3066
+ this.mounts.set(rel, {
3067
+ disk: d,
3068
+ readOnly,
3069
+ subdirectory,
3070
+ conditional,
3071
+ queueMs,
3072
+ checkoutPaths
3073
+ });
3074
+ return this;
3075
+ }
3076
+ /** Unmount the disk at `name`. Returns whether a disk was removed. Refuses to
3077
+ * remove the last disk — a workspace must always have at least one (the same
3078
+ * invariant the constructor enforces), else fan-out/exec would have nothing to
3079
+ * route to. */
3080
+ removeDisk(name) {
3081
+ const rel = name.replace(/^\/+|\/+$/g, "");
3082
+ if (this.mounts.has(rel) && this.mounts.size === 1) throw new Error("cannot remove the last disk from a workspace; a workspace must keep at least one");
3083
+ return this.mounts.delete(rel);
3084
+ }
3085
+ /** The names of the currently-mounted disks. */
3086
+ diskNames() {
3087
+ return [...this.mounts.keys()];
3088
+ }
3089
+ unknownDisk(name) {
3090
+ return /* @__PURE__ */ new Error(`No disk named '${name}'. Address objects by disk: ${this.diskNames().map((n) => `${n}/…`).join(", ")}`);
3091
+ }
3092
+ /** Resolve a workspace key (`<name>/...`) to the disk and the disk-relative key. */
3093
+ route(key) {
3094
+ const segs = toSegments(key);
3095
+ if (segs.length === 0) throw new Error("that key is the workspace root, not an object; name a disk, e.g. data/file.txt");
3096
+ const entry = this.mounts.get(segs[0]);
3097
+ if (!entry) throw this.unknownDisk(segs[0]);
3098
+ return {
3099
+ entry,
3100
+ diskKey: this.diskKey(entry, segs.slice(1).join("/"))
3101
+ };
3102
+ }
3103
+ /** Mounts touched by a key prefix; an empty prefix fans out to all of them. */
3104
+ covered(prefix) {
3105
+ const segs = toSegments(prefix);
3106
+ if (segs.length === 0) return [...this.mounts.entries()].map(([name, entry]) => ({
3107
+ name,
3108
+ entry,
3109
+ rel: this.diskKey(entry, "")
3110
+ }));
3111
+ const entry = this.mounts.get(segs[0]);
3112
+ if (!entry) throw this.unknownDisk(segs[0]);
3113
+ return [{
3114
+ name: segs[0],
3115
+ entry,
3116
+ rel: this.diskKey(entry, segs.slice(1).join("/"))
3117
+ }];
3118
+ }
3119
+ /** Route grep globs written against the workspace root to the mounts they
3120
+ * can match. A glob that starts with a mount's name goes to that mount without
3121
+ * the name. One with no `/`, or that starts with `**` + `/` with or without a
3122
+ * leading `/`, goes to every mount as written, and also applies to a mount it
3123
+ * names exactly, like `!cache` or `**` + `/logs/**`. Mount names are matched
3124
+ * literally, so `!l*` doesn't skip a `logs` mount. Leaves out a mount whose
3125
+ * directory an exclude names, or that no include reaches, and throws for any
3126
+ * other glob with a `/`. */
3127
+ rootGlobs(globs) {
3128
+ const routed = new Map([...this.mounts.keys()].map((name) => [name, []]));
3129
+ const excluded = /* @__PURE__ */ new Set();
3130
+ for (const glob of globs) {
3131
+ const exclude = glob.startsWith("!");
3132
+ let body = exclude ? glob.slice(1) : glob;
3133
+ const dirOnly = body.endsWith("/");
3134
+ if (dirOnly) body = body.slice(0, -1);
3135
+ const anchored = body.startsWith("/");
3136
+ if (anchored) body = body.slice(1);
3137
+ const everywhere = !anchored && !body.includes("/") || body === "**" || body.startsWith("**/");
3138
+ if (everywhere) for (const mountGlobs of routed.values()) mountGlobs.push(glob);
3139
+ const path = everywhere && body.startsWith("**/") ? body.slice(3) : body;
3140
+ const slash = path.indexOf("/");
3141
+ const name = slash < 0 ? path : path.slice(0, slash);
3142
+ const rest = slash < 0 ? "" : path.slice(slash + 1);
3143
+ const mountGlobs = routed.get(name);
3144
+ if (!mountGlobs) {
3145
+ if (everywhere) continue;
3146
+ throw new Error(`At the workspace root, a glob with a '/' must start with a mount name (${this.diskNames().map((n) => `${n}/`).join(", ")}) or '**/'; got '${glob}'. To search below one mount, set directory to it.`);
3147
+ }
3148
+ if (rest === "") {
3149
+ if (exclude) excluded.add(name);
3150
+ else excluded.delete(name);
3151
+ continue;
3152
+ }
3153
+ mountGlobs.push(`${exclude ? "!" : ""}${rest.includes("/") ? rest : `/${rest}`}${dirOnly ? "/" : ""}`);
3154
+ }
3155
+ const hasInclude = globs.some((glob) => !glob.startsWith("!"));
3156
+ for (const [name, mountGlobs] of routed) if (excluded.has(name) || hasInclude && mountGlobs.every((glob) => glob.startsWith("!"))) routed.delete(name);
3157
+ return routed;
3158
+ }
3159
+ /** Map a workspace-relative key to the disk's key, applying the mount's subdirectory. */
3160
+ diskKey(entry, rel) {
3161
+ const trimmed = rel.replace(/^\/+/, "");
3162
+ const sub = (entry.subdirectory ?? "").replace(/^\/+|\/+$/g, "");
3163
+ if (!sub) return trimmed;
3164
+ return trimmed ? `${sub}/${trimmed}` : sub;
3165
+ }
3166
+ /** Map a disk key back to its workspace key (`<name>/...`), stripping the mount subdirectory. */
3167
+ abs(name, entry, diskKey) {
3168
+ const sub = (entry.subdirectory ?? "").replace(/^\/+|\/+$/g, "");
3169
+ let rel = diskKey;
3170
+ if (sub && diskKey.startsWith(sub + "/")) rel = diskKey.slice(sub.length + 1);
3171
+ else if (sub && diskKey === sub) rel = "";
3172
+ rel = rel.replace(/^\/+|\/+$/g, "");
3173
+ return rel ? `${name}/${rel}` : name;
3174
+ }
3175
+ async getObject(key) {
3176
+ const { entry, diskKey } = this.route(key);
3177
+ return entry.disk.getObject(diskKey);
3178
+ }
3179
+ async putObject(key, body, options) {
3180
+ const { entry, diskKey } = this.route(key);
3181
+ if (entry.readOnly) throw new Error(`${key} is on a read-only disk and cannot be written.`);
3182
+ return entry.disk.putObject(diskKey, body, options);
3183
+ }
3184
+ async deleteObject(key) {
3185
+ const { entry, diskKey } = this.route(key);
3186
+ if (entry.readOnly) throw new Error(`${key} is on a read-only disk and cannot be deleted.`);
3187
+ await entry.disk.deleteObject(diskKey);
3188
+ }
3189
+ async listObjects(prefix, opts = {}) {
3190
+ if (toSegments(prefix ?? "").length === 0 && !opts.recursive) return {
3191
+ objects: [],
3192
+ commonPrefixes: this.diskNames().map((n) => `${n}/`).sort(),
3193
+ isTruncated: false,
3194
+ keyCount: 0
3195
+ };
3196
+ const covered = this.covered(prefix ?? "");
3197
+ const listings = await Promise.allSettled(covered.map(({ entry, rel }) => {
3198
+ const p = rel ? rel.endsWith("/") ? rel : `${rel}/` : void 0;
3199
+ return entry.disk.listObjects(p, { recursive: opts.recursive });
3200
+ }));
3201
+ const objects = [];
3202
+ const commonPrefixes = [];
3203
+ let isTruncated = false;
3204
+ let keyCount = 0;
3205
+ covered.forEach(({ name, entry }, i) => {
3206
+ const settled = listings[i];
3207
+ if (settled.status === "rejected") {
3208
+ isTruncated = true;
3209
+ return;
3210
+ }
3211
+ const listing = settled.value;
3212
+ for (const cp of listing.commonPrefixes) commonPrefixes.push(`${this.abs(name, entry, cp.replace(/\/+$/, ""))}/`);
3213
+ for (const obj of listing.objects) objects.push({
3214
+ ...obj,
3215
+ key: this.abs(name, entry, obj.key)
3216
+ });
3217
+ isTruncated = isTruncated || listing.isTruncated;
3218
+ keyCount += listing.keyCount;
3219
+ });
3220
+ objects.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
3221
+ commonPrefixes.sort();
3222
+ return {
3223
+ objects,
3224
+ commonPrefixes,
3225
+ isTruncated,
3226
+ keyCount
3227
+ };
3228
+ }
3229
+ /**
3230
+ * Grep the disks `directory` covers in parallel and merge their results. At
3231
+ * the workspace root, a glob with a `/` must start with a mount name, like
3232
+ * `data/src/**`, which applies to that mount only, or with `**` + `/`. A glob
3233
+ * with no `/`, like `*.ts`, or one starting with `**` + `/` with or without a
3234
+ * leading `/`, applies inside every mount, and also to a mount it names
3235
+ * exactly, so `!cache` skips the cache mount. Mount names are matched
3236
+ * literally, not as patterns: `!l*` applies inside every mount, but doesn't
3237
+ * skip a mount named `logs`.
3238
+ */
3239
+ async grep(opts) {
3240
+ const directory = opts.directory ?? "";
3241
+ const rootGlobs = toSegments(directory).length === 0 && opts.globs?.length ? this.rootGlobs(opts.globs) : void 0;
3242
+ const covered = this.covered(directory).flatMap((c) => {
3243
+ if (rootGlobs === void 0) return [{
3244
+ ...c,
3245
+ globs: opts.globs
3246
+ }];
3247
+ const globs = rootGlobs.get(c.name);
3248
+ return globs === void 0 ? [] : [{
3249
+ ...c,
3250
+ globs
3251
+ }];
3252
+ });
3253
+ const results = await Promise.allSettled(covered.map(({ entry, rel, globs }) => entry.disk.grep({
3254
+ ...opts,
3255
+ directory: rel,
3256
+ globs
3257
+ })));
3258
+ for (const settled of results) if (settled.status === "rejected" && settled.reason instanceof ArchilApiError && settled.reason.status === 400) throw settled.reason;
3259
+ const matches = [];
3260
+ const groups = [];
3261
+ let filesScanned = 0;
3262
+ let containersDispatched = 0;
3263
+ let computeSecondsUsed = 0;
3264
+ let durationMs = 0;
3265
+ let listingMs = 0;
3266
+ let grepMs = 0;
3267
+ const reasons = /* @__PURE__ */ new Set();
3268
+ covered.forEach(({ name, entry }, i) => {
3269
+ const settled = results[i];
3270
+ if (settled.status === "rejected") {
3271
+ reasons.add("list_failed");
3272
+ return;
3273
+ }
3274
+ const r = settled.value;
3275
+ filesScanned += r.filesScanned;
3276
+ containersDispatched += r.containersDispatched ?? 0;
3277
+ computeSecondsUsed += r.computeSecondsUsed ?? 0;
3278
+ durationMs = Math.max(durationMs, r.durationMs ?? 0);
3279
+ listingMs = Math.max(listingMs, r.listingMs ?? 0);
3280
+ grepMs = Math.max(grepMs, r.grepMs ?? 0);
3281
+ reasons.add(r.stoppedReason);
3282
+ for (const m of r.matches) matches.push({
3283
+ ...m,
3284
+ file: this.abs(name, entry, m.file)
3285
+ });
3286
+ for (const g of r.groups ?? []) groups.push({
3287
+ ...g,
3288
+ file: this.abs(name, entry, g.file)
3289
+ });
3290
+ });
3291
+ const cap = opts.maxResults ?? 1e3;
3292
+ if (matches.length > cap) reasons.add("max_results");
3293
+ const priority = [
3294
+ "list_failed",
3295
+ "incomplete",
3296
+ "deadline",
3297
+ "max_results"
3298
+ ];
3299
+ const stoppedReason = [...reasons].every((x) => x === "completed") ? "completed" : priority.find((x) => reasons.has(x)) ?? "completed";
3300
+ const withGroups = (opts.contextBefore ?? 0) > 0 || (opts.contextAfter ?? 0) > 0;
3301
+ return {
3302
+ matches: matches.slice(0, cap),
3303
+ ...withGroups && { groups: matches.length > cap ? truncateGroups(groups, cap, opts.contextAfter ?? 0, opts.multiline ?? false) : groups },
3304
+ stoppedReason,
3305
+ filesScanned,
3306
+ containersDispatched,
3307
+ computeSecondsUsed,
3308
+ durationMs,
3309
+ listingMs,
3310
+ grepMs
3311
+ };
3312
+ }
3313
+ exec(command) {
3314
+ const disks = {};
3315
+ for (const [name, entry] of this.mounts) disks[name] = entry.readOnly || entry.subdirectory || entry.conditional || entry.queueMs !== void 0 || entry.checkoutPaths !== void 0 ? {
3316
+ disk: entry.disk,
3317
+ subdirectory: entry.subdirectory,
3318
+ readOnly: entry.readOnly,
3319
+ conditional: entry.conditional,
3320
+ queueMs: entry.queueMs,
3321
+ checkoutPaths: entry.checkoutPaths
3322
+ } : entry.disk;
3323
+ return this.client.exec({
3324
+ disks,
3325
+ command
3326
+ });
3327
+ }
3328
+ };
3329
+ //#endregion
3330
+ //#region src/archil.ts
3331
+ /**
3332
+ * Read an environment variable in a way that is safe in browsers, where the
3333
+ * `process` global does not exist. Returns undefined when there is no process
3334
+ * environment, so the SDK can be bundled and run client-side as long as
3335
+ * credentials are passed explicitly to `new Archil({ ... })`.
3336
+ */
3337
+ function envVar(name) {
3338
+ return typeof process !== "undefined" && process.env ? process.env[name] : void 0;
3339
+ }
3340
+ function isExecMountSpec(m) {
3341
+ return typeof m === "object" && m !== null && "disk" in m;
3342
+ }
3343
+ function diskIdFromMount(m) {
3344
+ return typeof m === "string" ? m : m.id;
3345
+ }
3346
+ var Archil = class {
3347
+ disks;
3348
+ images;
3349
+ sandboxes;
3350
+ tokens;
3351
+ /** @internal */
3352
+ _client;
3353
+ constructor(opts = {}) {
3354
+ const apiKey = opts.apiKey ?? envVar("ARCHIL_API_KEY");
3355
+ const region = opts.region ?? envVar("ARCHIL_REGION");
3356
+ if (!apiKey) throw new Error("Missing API key: pass apiKey in options or set ARCHIL_API_KEY environment variable");
3357
+ if (!region) throw new Error("Missing region: pass region in options or set ARCHIL_REGION environment variable");
3358
+ const controlBaseUrl = opts.baseUrl ?? resolveBaseUrl(region);
3359
+ const client = createApiClient({
3360
+ apiKey,
3361
+ region,
3362
+ baseUrl: controlBaseUrl,
3363
+ tls: opts.tls
3364
+ });
3365
+ const s3BaseUrl = opts.s3BaseUrl ?? envVar("ARCHIL_S3_BASE_URL") ?? deriveS3BaseUrl(controlBaseUrl);
3366
+ this._client = client;
3367
+ this.disks = new Disks(client, region, s3BaseUrl);
3368
+ this.images = new Images(client);
3369
+ this.sandboxes = new Sandboxes(client);
3370
+ this.tokens = new Tokens(client);
3371
+ }
3372
+ /**
3373
+ * Run a command in a container with multiple disks mounted simultaneously,
3374
+ * each at its own relative path under `/mnt/archil`. Blocks until the
3375
+ * command completes and returns its stdout, stderr, exit code, and timing.
3376
+ */
3377
+ async exec(opts) {
3378
+ const disks = {};
3379
+ for (const [relPath, mount] of Object.entries(opts.disks)) if (isExecMountSpec(mount)) {
3380
+ const entry = {
3381
+ disk: diskIdFromMount(mount.disk),
3382
+ readOnly: mount.readOnly ?? false,
3383
+ conditional: mount.conditional ?? false
3384
+ };
3385
+ if (mount.subdirectory !== void 0) entry.subdirectory = mount.subdirectory;
3386
+ if (mount.queueMs !== void 0) entry.queueMs = mount.queueMs;
3387
+ if (mount.checkoutPaths !== void 0) entry.checkoutPaths = mount.checkoutPaths;
3388
+ disks[relPath] = entry;
3389
+ } else disks[relPath] = diskIdFromMount(mount);
3390
+ return unwrap(retryApiRequest(() => this._client.POST("/api/exec", { body: {
3391
+ ...execVmBody(opts),
3392
+ disks,
3393
+ command: opts.command
3394
+ } }), "connect"));
3395
+ }
3396
+ /**
3397
+ * Build an agent filesystem toolset spanning several disks at once. `mounts`
3398
+ * maps a relative path to a disk (or `ExecMountSpec`), exactly like
3399
+ * {@link exec}; each disk appears under `/mnt/archil/<path>`. Hand the result
3400
+ * to a framework adapter (`createDiskTools(workspace)`) to get tools that route
3401
+ * file operations by path and fan `grep`/`list_files` out across the disks.
3402
+ */
3403
+ workspace(mounts) {
3404
+ return new Workspace(this, mounts);
3405
+ }
3406
+ };
3407
+ //#endregion
3408
+ //#region src/index.ts
3409
+ let _options;
3410
+ let _instance;
3411
+ function configure(options) {
3412
+ _options = options;
3413
+ _instance = void 0;
3414
+ }
3415
+ function archil() {
3416
+ if (!_instance) _instance = new Archil(_options);
3417
+ return _instance;
3418
+ }
3419
+ function createDisk(req) {
3420
+ return archil().disks.create(req);
3421
+ }
3422
+ function listDisks(opts) {
3423
+ return archil().disks.list(opts);
3424
+ }
3425
+ function getDisk(id) {
3426
+ return archil().disks.get(id);
3427
+ }
3428
+ function createSandbox(req = {}, opts = {}) {
3429
+ return archil().sandboxes.create(req, opts);
3430
+ }
3431
+ function listSandboxes(opts) {
3432
+ return archil().sandboxes.list(opts);
3433
+ }
3434
+ function getSandbox(id) {
3435
+ return archil().sandboxes.get(id);
3436
+ }
3437
+ function listApiKeys(opts) {
3438
+ return archil().tokens.list(opts);
3439
+ }
3440
+ function createApiKey(req) {
3441
+ return archil().tokens.create(req);
3442
+ }
3443
+ function deleteApiKey(id) {
3444
+ return archil().tokens.delete(id);
3445
+ }
3446
+ /**
3447
+ * Run a command in a container with multiple disks mounted simultaneously,
3448
+ * each at its own relative path under `/mnt/archil`. Blocks until the
3449
+ * command completes and returns its stdout, stderr, exit code, and timing.
3450
+ */
3451
+ function exec(opts) {
3452
+ return archil().exec(opts);
3453
+ }
3454
+ /**
3455
+ * Build an agent filesystem toolset spanning several disks, using the
3456
+ * module-level client. See {@link Archil.workspace}.
3457
+ */
3458
+ function workspace(mounts) {
3459
+ return archil().workspace(mounts);
3460
+ }
3461
+ //#endregion
3462
+ export { Archil, ArchilApiError, ArchilError, ArchilS3Error, Disk, DiskMultipart, Disks, ImageBuildError, Images, Sandbox, SandboxFileTransferError, SandboxFiles, SandboxPauseError, SandboxProcess, SandboxProcesses, Sandboxes, Tokens, USER_AGENT, VERSION, Workspace, configure, createApiKey, createDisk, createSandbox, deleteApiKey, effectiveUploadPartSize, exec, getDisk, getSandbox, listApiKeys, listDisks, listSandboxes, workspace };