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