disk 1.10.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -1,8 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { a as deleteApiKey, k as ArchilApiError, l as listApiKeys, n as createApiKey, r as createDisk, s as getDisk, t as configure, u as listDisks } from "./src-BND_QqPx.mjs";
3
- import { a as addGlobalOptions, c as resolveProgramCredentials, l as renderTable, o as addProfileCommands, s as isProfileCommand, t as optionalInteger } from "./sandbox-options-DV7SSadf.mjs";
2
+ import { a as deleteApiKey, k as ArchilApiError, l as listApiKeys, n as createApiKey, r as createDisk, s as getDisk, t as configure, u as listDisks } from "./src-V9HdQW-c.mjs";
3
+ import { a as addGlobalOptions, c as resolveProgramCredentials, d as Command, l as renderTable, o as addProfileCommands, s as isProfileCommand, t as optionalInteger } from "./sandbox-options-Cz_oVr-y.mjs";
4
4
  import { createRequire } from "node:module";
5
- import { Command } from "commander";
6
5
  //#region bin/cli.ts
7
6
  const pkg = createRequire(import.meta.url)("../package.json");
8
7
  const program = new Command();
package/dist/index.cjs CHANGED
@@ -1,40 +1,165 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region \0rolldown/runtime.js
3
- var __create = Object.create;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getProtoOf = Object.getPrototypeOf;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
- key = keys[i];
12
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
- get: ((k) => from[k]).bind(null, key),
14
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
- });
16
- }
17
- return to;
18
- };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
- value: mod,
21
- enumerable: true
22
- }) : target, mod));
23
- //#endregion
24
2
  const require_paths = require("./paths-1c4QqbOB.cjs");
25
- let openapi_fetch = require("openapi-fetch");
26
- openapi_fetch = __toESM(openapi_fetch, 1);
3
+ //#region src/api-fetch.ts
4
+ function buildPath(template, params = {}) {
5
+ return template.replace(/\{([^}]+)\}/g, (_, name) => {
6
+ const value = params[name];
7
+ if (value === void 0) throw new Error(`Missing path parameter '${name}' for ${template}`);
8
+ return encodeURIComponent(String(value));
9
+ });
10
+ }
11
+ /** Serialize a query object; undefined/null values are omitted and arrays repeat the key. */
12
+ function buildQuery(query = {}) {
13
+ const parts = [];
14
+ for (const [name, value] of Object.entries(query)) for (const item of Array.isArray(value) ? value : [value]) {
15
+ if (item === void 0 || item === null) continue;
16
+ parts.push(`${encodeURIComponent(name)}=${encodeURIComponent(String(item))}`);
17
+ }
18
+ return parts.length > 0 ? `?${parts.join("&")}` : "";
19
+ }
20
+ function createClient(config) {
21
+ const baseUrl = config.baseUrl.replace(/\/+$/, "");
22
+ const send = (request) => (config.fetch ?? globalThis.fetch)(request);
23
+ const headersFor = (extra = {}) => {
24
+ const headers = new Headers(config.headers);
25
+ for (const [name, value] of Object.entries(extra)) if (value !== void 0) headers.set(name, value);
26
+ return headers;
27
+ };
28
+ const call = async (method, path, init = {}) => {
29
+ const url = baseUrl + buildPath(path, init.params?.path) + buildQuery(init.params?.query);
30
+ const headers = headersFor(init.params?.header);
31
+ let body;
32
+ if (init.body !== void 0) {
33
+ body = JSON.stringify(init.body);
34
+ if (!headers.has("Content-Type")) headers.set("Content-Type", "application/json");
35
+ }
36
+ const response = await send(new Request(url, {
37
+ method,
38
+ headers,
39
+ body
40
+ }));
41
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
42
+ await response.body?.cancel().catch(() => {});
43
+ return response.ok ? {
44
+ data: void 0,
45
+ response
46
+ } : {
47
+ error: void 0,
48
+ response
49
+ };
50
+ }
51
+ if (response.ok) return {
52
+ data: await response.json(),
53
+ response
54
+ };
55
+ const text = await response.text();
56
+ let error = text;
57
+ try {
58
+ error = JSON.parse(text);
59
+ } catch {}
60
+ return {
61
+ error,
62
+ response
63
+ };
64
+ };
65
+ const method = (name) => ((path, init) => call(name, path, init));
66
+ return {
67
+ GET: method("GET"),
68
+ PUT: method("PUT"),
69
+ POST: method("POST"),
70
+ DELETE: method("DELETE"),
71
+ PATCH: method("PATCH"),
72
+ raw: (methodName, url, init = {}) => send(new Request(url, {
73
+ method: methodName,
74
+ headers: headersFor(init.headers),
75
+ body: init.body
76
+ }))
77
+ };
78
+ }
79
+ //#endregion
27
80
  //#region src/s3xml.ts
28
- const parser = new (require("fast-xml-parser")).XMLParser({
29
- isArray: (name) => name === "Contents" || name === "CommonPrefixes",
30
- parseTagValue: false,
31
- trimValues: true,
32
- ignoreAttributes: true
33
- });
81
+ const ALWAYS_ARRAY = /* @__PURE__ */ new Set(["Contents", "CommonPrefixes"]);
82
+ const NAMED_ENTITIES = {
83
+ amp: "&",
84
+ lt: "<",
85
+ gt: ">",
86
+ quot: "\"",
87
+ apos: "'"
88
+ };
89
+ function decodeEntities(text) {
90
+ if (!text.includes("&")) return text;
91
+ return text.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);/g, (match, ref) => {
92
+ if (ref[0] === "#") {
93
+ const code = ref[1] === "x" || ref[1] === "X" ? parseInt(ref.slice(2), 16) : parseInt(ref.slice(1), 10);
94
+ return code > 1114111 ? match : String.fromCodePoint(code);
95
+ }
96
+ return Object.hasOwn(NAMED_ENTITIES, ref) ? NAMED_ENTITIES[ref] : match;
97
+ });
98
+ }
99
+ function setOwn(target, name, value) {
100
+ Object.defineProperty(target, name, {
101
+ value,
102
+ enumerable: true,
103
+ writable: true,
104
+ configurable: true
105
+ });
106
+ }
107
+ function addChild(parent, name, value) {
108
+ parent.hasChildren = true;
109
+ const existing = Object.hasOwn(parent.children, name) ? parent.children[name] : void 0;
110
+ if (existing === void 0) setOwn(parent.children, name, ALWAYS_ARRAY.has(name) ? [value] : value);
111
+ else if (Array.isArray(existing)) existing.push(value);
112
+ else setOwn(parent.children, name, [existing, value]);
113
+ }
114
+ /** Index just past `terminator`, searching from `from`; throws if it never appears. */
115
+ function skipPast(xml, terminator, from) {
116
+ const end = xml.indexOf(terminator, from);
117
+ if (end === -1) throw new Error(`Malformed XML: missing '${terminator}'`);
118
+ return end + terminator.length;
119
+ }
34
120
  /** Parse an XML document into a plain object. Returns {} for empty/blank input. */
35
121
  function parseXml(xml) {
36
- if (!xml.trim()) return {};
37
- return parser.parse(xml);
122
+ const root = {
123
+ name: "",
124
+ children: {},
125
+ hasChildren: false,
126
+ text: ""
127
+ };
128
+ const stack = [root];
129
+ let position = 0;
130
+ while (position < xml.length) {
131
+ const current = stack[stack.length - 1];
132
+ const open = xml.indexOf("<", position);
133
+ current.text += decodeEntities(xml.slice(position, open === -1 ? xml.length : open));
134
+ if (open === -1) break;
135
+ if (xml.startsWith("<!--", open)) position = skipPast(xml, "-->", open + 4);
136
+ else if (xml.startsWith("<![CDATA[", open)) {
137
+ position = skipPast(xml, "]]>", open + 9);
138
+ current.text += xml.slice(open + 9, position - 3);
139
+ } else if (xml.startsWith("<?", open)) position = skipPast(xml, "?>", open + 2);
140
+ else if (xml.startsWith("<!", open)) throw new Error("Malformed XML: DOCTYPE and other declarations are not supported");
141
+ else {
142
+ position = skipPast(xml, ">", open + 1);
143
+ const tag = xml.slice(open + 1, position - 1);
144
+ const closing = tag.startsWith("/");
145
+ const selfClosing = !closing && tag.endsWith("/");
146
+ const name = /^[^\s/]+/.exec(closing ? tag.slice(1) : tag)?.[0];
147
+ if (!name) throw new Error(`Malformed XML: invalid tag <${tag}>`);
148
+ if (closing) {
149
+ if (current.name !== name || stack.length === 1) throw new Error(`Malformed XML: unexpected </${name}>`);
150
+ stack.pop();
151
+ addChild(stack[stack.length - 1], name, current.hasChildren ? current.children : current.text);
152
+ } else if (selfClosing) addChild(current, name, "");
153
+ else stack.push({
154
+ name,
155
+ children: {},
156
+ hasChildren: false,
157
+ text: ""
158
+ });
159
+ }
160
+ }
161
+ if (stack.length !== 1) throw new Error(`Malformed XML: unclosed <${stack[stack.length - 1].name}>`);
162
+ return root.children;
38
163
  }
39
164
  //#endregion
40
165
  //#region src/errors.ts
@@ -163,11 +288,10 @@ function deriveS3BaseUrl(controlBaseUrl) {
163
288
  }
164
289
  //#endregion
165
290
  //#region src/version.ts
166
- const VERSION = "1.10.0";
291
+ const VERSION = "1.12.0";
167
292
  const USER_AGENT = `archil-js/${VERSION}`;
168
293
  //#endregion
169
294
  //#region src/client.ts
170
- const createClient = typeof openapi_fetch.default === "function" ? openapi_fetch.default : openapi_fetch.default.default;
171
295
  function isNodeRuntime() {
172
296
  return typeof process !== "undefined" && typeof process.versions?.node === "string";
173
297
  }
@@ -198,10 +322,10 @@ const bufferRequestBodies = (dispatch) => (options, handler) => {
198
322
  return true;
199
323
  };
200
324
  const sharedTransports = /* @__PURE__ */ new Map();
201
- function dispatcherKey(baseUrl, apiKey, ca) {
325
+ function dispatcherKey(baseUrl, authorization, ca) {
202
326
  return JSON.stringify([
203
327
  new URL(baseUrl).origin,
204
- apiKey,
328
+ authorization,
205
329
  ca?.map((cert) => cert.toString("base64"))
206
330
  ]);
207
331
  }
@@ -227,13 +351,13 @@ function getSharedTransport(key, ca) {
227
351
  });
228
352
  return transport;
229
353
  }
230
- function createPooledFetch(baseUrl, apiKey, tls) {
354
+ function createPooledFetch(baseUrl, authorization, tls) {
231
355
  if (!isNodeRuntime()) {
232
356
  if (tls?.ca !== void 0) throw new Error("Custom TLS CAs require Node.js");
233
357
  return;
234
358
  }
235
359
  const ca = tls?.ca === void 0 ? void 0 : (Array.isArray(tls.ca) ? tls.ca : [tls.ca]).map((cert) => Buffer.from(cert));
236
- const key = dispatcherKey(baseUrl, apiKey, ca);
360
+ const key = dispatcherKey(baseUrl, authorization, ca);
237
361
  return async (request) => {
238
362
  const { fetch, dispatcher } = await getSharedTransport(key, ca);
239
363
  const body = request.body === null ? null : new Uint8Array(await request.arrayBuffer());
@@ -247,14 +371,23 @@ function createPooledFetch(baseUrl, apiKey, tls) {
247
371
  });
248
372
  };
249
373
  }
374
+ /**
375
+ * The `Authorization` value for an API key: the key exactly as given, as a
376
+ * bearer token. Credential-injecting proxies substitute a placeholder only when
377
+ * it is the whole token, so the SDK must not add a prefix to it. The control
378
+ * plane accepts the key with or without its `key-` prefix after `Bearer`.
379
+ */
380
+ function apiKeyAuthorization(apiKey) {
381
+ return `Bearer ${apiKey}`;
382
+ }
250
383
  function createApiClient(opts) {
251
384
  const baseUrl = opts.baseUrl ?? resolveBaseUrl(opts.region);
252
- const apiKey = `key-${opts.apiKey.replace(/^key-/, "")}`;
385
+ const authorization = apiKeyAuthorization(opts.apiKey);
253
386
  return createClient({
254
387
  baseUrl,
255
- fetch: createPooledFetch(baseUrl, apiKey, opts.tls),
388
+ fetch: createPooledFetch(baseUrl, authorization, opts.tls),
256
389
  headers: {
257
- Authorization: apiKey,
390
+ Authorization: authorization,
258
391
  "User-Agent": USER_AGENT
259
392
  }
260
393
  });
@@ -294,6 +427,22 @@ async function unwrapEmpty(promise) {
294
427
  }
295
428
  if (!body.success) throw new ArchilApiError(body.error ?? "Unknown API error", response.status, body.code);
296
429
  }
430
+ //#endregion
431
+ //#region src/exec-options.ts
432
+ /**
433
+ * @internal Copies only the known option keys into a request body. Every key
434
+ * is required here, so an option added to the API fails to compile until it is
435
+ * copied.
436
+ */
437
+ function execVmBody(options) {
438
+ return {
439
+ baseImage: options?.baseImage,
440
+ imageId: options?.imageId,
441
+ vcpuCount: options?.vcpuCount,
442
+ memSizeMib: options?.memSizeMib,
443
+ network: options?.network
444
+ };
445
+ }
297
446
  const RETRY_BASE_MS = 100;
298
447
  const RETRY_CAP_MS = 2e3;
299
448
  const TRANSIENT_STATUSES = /* @__PURE__ */ new Set([
@@ -465,6 +614,23 @@ var Disk = class {
465
614
  await this.removeUser("token", identifier);
466
615
  }
467
616
  /**
617
+ * Create an S3 access key pair for this disk's S3 API. The secret key is
618
+ * returned only here. The keys reach the whole disk, read-write unless
619
+ * `readOnly` is set, so keep them server-side and give browsers presigned
620
+ * URLs instead.
621
+ */
622
+ async createS3Credentials(options = {}) {
623
+ const user = await this.addUser({
624
+ ...options,
625
+ type: "s3"
626
+ });
627
+ if (!user.s3AccessKeyId || !user.s3SecretKey || !user.identifier) throw new Error("Server did not return generated S3 credentials");
628
+ return user;
629
+ }
630
+ async removeS3Credentials(accessKeyId) {
631
+ await this.removeUser("s3", accessKeyId);
632
+ }
633
+ /**
468
634
  * List all delegations currently held on this disk. A delegation grants a
469
635
  * client exclusive write access to an inode; it has no ID of its own and is
470
636
  * identified by the (clientId, inodeId) pair — pass those to
@@ -556,10 +722,13 @@ var Disk = class {
556
722
  * Execute a command in a container with this disk mounted.
557
723
  * Blocks until the command completes and returns stdout, stderr, and exit code.
558
724
  */
559
- async exec(command) {
725
+ async exec(command, options) {
560
726
  return unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/exec", {
561
727
  params: { path: { id: this.id } },
562
- body: { command }
728
+ body: {
729
+ ...execVmBody(options),
730
+ command
731
+ }
563
732
  }), "connect"));
564
733
  }
565
734
  /**
@@ -906,29 +1075,22 @@ var Disk = class {
906
1075
  */
907
1076
  async _s3Request(method, key, opts = {}) {
908
1077
  if (!this._s3BaseUrl) throw new Error("S3 base URL not configured. Pass s3BaseUrl to new Archil({...}) or set ARCHIL_S3_BASE_URL.");
909
- const call = this._client[method];
910
1078
  const encodedKey = key.replace(/^\//, "").split("/").map(encodeURIComponent).join("/");
911
1079
  const path = encodedKey ? `/${this.id}/${encodedKey}` : `/${this.id}`;
1080
+ const url = `${this._s3BaseUrl.replace(/\/+$/, "")}${path}${buildQuery(opts.query)}`;
912
1081
  const init = {
913
- baseUrl: this._s3BaseUrl,
914
- parseAs: "stream",
915
- ...opts.query ? { params: { query: opts.query } } : {},
916
- ...opts.body !== void 0 ? {
917
- body: opts.body,
918
- bodySerializer: (b) => b
919
- } : {},
920
- ...opts.contentType || opts.extraHeaders ? { headers: {
1082
+ body: opts.body,
1083
+ headers: {
921
1084
  ...opts.contentType ? { "Content-Type": opts.contentType } : {},
922
1085
  ...opts.extraHeaders
923
- } } : {}
1086
+ }
924
1087
  };
925
1088
  const hasBody = method === "GET" || method === "POST";
926
1089
  const maxRetries = opts.retry === false ? 0 : 3;
927
1090
  for (let attempt = 0;; attempt++) {
928
- let error;
929
1091
  let response;
930
1092
  try {
931
- ({error, response} = await call(path, init));
1093
+ response = await this._client.raw(method, url, init);
932
1094
  } catch (transportError) {
933
1095
  if (attempt < maxRetries) {
934
1096
  await retrySleep(attempt);
@@ -942,15 +1104,15 @@ var Disk = class {
942
1104
  await retrySleep(attempt);
943
1105
  continue;
944
1106
  }
945
- const message = typeof error === "string" ? error : error ? JSON.stringify(error) : "";
946
1107
  return {
947
1108
  ok: false,
948
1109
  status: response.status,
949
1110
  statusText: response.statusText,
950
1111
  headers: response.headers,
951
- body: new TextEncoder().encode(message)
1112
+ body: new Uint8Array(await response.arrayBuffer())
952
1113
  };
953
1114
  }
1115
+ if (!hasBody) await response.body?.cancel().catch(() => {});
954
1116
  const bytes = hasBody ? new Uint8Array(await response.arrayBuffer()) : /* @__PURE__ */ new Uint8Array(0);
955
1117
  return {
956
1118
  ok: true,
@@ -1376,10 +1538,13 @@ var Disks = class {
1376
1538
  * disk ID directly so callers that do not need its metadata can execute
1377
1539
  * without fetching the disk first.
1378
1540
  */
1379
- async exec(id, command) {
1541
+ async exec(id, command, options) {
1380
1542
  return unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/exec", {
1381
1543
  params: { path: { id } },
1382
- body: { command }
1544
+ body: {
1545
+ ...execVmBody(options),
1546
+ command
1547
+ }
1383
1548
  }), "connect"));
1384
1549
  }
1385
1550
  };
@@ -1457,6 +1622,15 @@ var Images = class {
1457
1622
  //#endregion
1458
1623
  //#region src/sandbox-process.ts
1459
1624
  const PROCESS_STDIN_CHUNK_BYTES = 1024 * 1024;
1625
+ /** Close codes the runtime uses when it ends a connection to a running process. */
1626
+ const CLOSE_REASONS = {
1627
+ 4001: "Process was taken over by another connection",
1628
+ 4003: "Process owner disconnected"
1629
+ };
1630
+ /** The subprotocol the runtime selects for a process connection. */
1631
+ const CONNECT_SUBPROTOCOL = "archil.connect.v1";
1632
+ /** Prefix of the subprotocol that carries a connection token. */
1633
+ const TOKEN_SUBPROTOCOL_PREFIX = "archil.token.";
1460
1634
  async function waitForSocketOpen(socket) {
1461
1635
  if (socket.readyState === WebSocket.OPEN) return;
1462
1636
  await new Promise((resolve, reject) => {
@@ -1482,12 +1656,13 @@ async function waitForSocketOpen(socket) {
1482
1656
  socket.addEventListener("close", closed, { once: true });
1483
1657
  });
1484
1658
  }
1485
- async function openProcessSocket(connectionUrl) {
1659
+ async function openProcessSocket(connectionEndpoint) {
1486
1660
  for (let attempt = 0;; attempt++) {
1487
- const url = await connectionUrl();
1661
+ const target = await connectionEndpoint();
1662
+ const endpoint = typeof target === "string" ? { url: target } : target;
1488
1663
  let socket;
1489
1664
  try {
1490
- socket = new WebSocket(url);
1665
+ socket = endpoint.protocols ? new WebSocket(endpoint.url, endpoint.protocols) : new WebSocket(endpoint.url);
1491
1666
  await waitForSocketOpen(socket);
1492
1667
  return socket;
1493
1668
  } catch (error) {
@@ -1523,7 +1698,7 @@ var SandboxProcess = class {
1523
1698
  _cursor;
1524
1699
  _onOutput;
1525
1700
  _collectOutput;
1526
- _connectionUrl;
1701
+ _connectionEndpoint;
1527
1702
  _controlProcess;
1528
1703
  _stdoutDecoder = new TextDecoder();
1529
1704
  _stderrDecoder = new TextDecoder();
@@ -1535,12 +1710,12 @@ var SandboxProcess = class {
1535
1710
  _connectionError;
1536
1711
  _stdinClosed = false;
1537
1712
  /** @internal */
1538
- constructor(processId, cursor, onOutput, collectOutput, connectionUrl, controlProcess) {
1713
+ constructor(processId, cursor, onOutput, collectOutput, connectionEndpoint, controlProcess) {
1539
1714
  this._id = processId;
1540
1715
  this._cursor = cursor;
1541
1716
  this._onOutput = onOutput;
1542
1717
  this._collectOutput = collectOutput;
1543
- this._connectionUrl = connectionUrl;
1718
+ this._connectionEndpoint = connectionEndpoint;
1544
1719
  this._controlProcess = controlProcess;
1545
1720
  this._terminal = new Promise((resolve) => {
1546
1721
  this._resolveTerminal = resolve;
@@ -1601,7 +1776,7 @@ var SandboxProcess = class {
1601
1776
  }
1602
1777
  /** @internal */
1603
1778
  async _connect(request) {
1604
- const socket = await openProcessSocket(this._connectionUrl);
1779
+ const socket = await openProcessSocket(this._connectionEndpoint);
1605
1780
  socket.binaryType = "arraybuffer";
1606
1781
  this._socket = socket;
1607
1782
  let resolveClosed;
@@ -1643,7 +1818,9 @@ var SandboxProcess = class {
1643
1818
  this._connectionError = error;
1644
1819
  fail(error);
1645
1820
  });
1646
- socket.addEventListener("close", () => {
1821
+ socket.addEventListener("close", (event) => {
1822
+ const reason = CLOSE_REASONS[event.code];
1823
+ if (reason && !this._result) this._connectionError = new Error(reason);
1647
1824
  if (this._socket === socket) this._socket = void 0;
1648
1825
  if (!readySettled) rejectReady(/* @__PURE__ */ new Error("Process connection closed before ready"));
1649
1826
  resolveClosed();
@@ -2060,7 +2237,7 @@ var Sandbox = class Sandbox {
2060
2237
  }
2061
2238
  /** Start a process and return its handle without waiting for exit. */
2062
2239
  async run(command, options = {}) {
2063
- const process = new SandboxProcess("", 0, options.onOutput, options.collectOutput ?? true, () => this._connectionUrl(), (request) => this._control(request));
2240
+ const process = new SandboxProcess("", 0, options.onOutput, options.collectOutput ?? true, () => this._connectionEndpoint(), (request) => this._control(request));
2064
2241
  const terminal = typeof options.terminal === "object" ? {
2065
2242
  cols: options.terminal.cols ?? 80,
2066
2243
  rows: options.terminal.rows ?? 24
@@ -2078,19 +2255,25 @@ var Sandbox = class Sandbox {
2078
2255
  /** Reattach to a process, optionally resuming output from a cursor. */
2079
2256
  async attach(processId, options = {}) {
2080
2257
  const offset = options.offset ?? 0;
2081
- const process = new SandboxProcess(processId, offset, options.onOutput, options.collectOutput ?? true, () => this._connectionUrl(), (request) => this._control(request));
2258
+ const process = new SandboxProcess(processId, offset, options.onOutput, options.collectOutput ?? true, () => this._connectionEndpoint(), (request) => this._control(request));
2082
2259
  await process._connect({
2083
2260
  type: "attach",
2084
2261
  process_id: processId,
2085
- offset
2262
+ offset,
2263
+ ...options.shared ? { shared: true } : {}
2086
2264
  });
2087
2265
  return process;
2088
2266
  }
2089
- async _connectionUrl() {
2090
- return (await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this.id } } }), "transient"))).url;
2267
+ async _connectionEndpoint() {
2268
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this.id } } }), "transient"));
2269
+ if (data.endpoint && data.token) return {
2270
+ url: data.endpoint,
2271
+ protocols: [CONNECT_SUBPROTOCOL, `${TOKEN_SUBPROTOCOL_PREFIX}${data.token}`]
2272
+ };
2273
+ return { url: data.url };
2091
2274
  }
2092
2275
  async _control(request) {
2093
- const socket = await openProcessSocket(() => this._connectionUrl());
2276
+ const socket = await openProcessSocket(() => this._connectionEndpoint());
2094
2277
  const expected = request.type === "kill" ? "killed" : "resized";
2095
2278
  await new Promise((resolve, reject) => {
2096
2279
  socket.addEventListener("message", (message) => {
@@ -2767,6 +2950,7 @@ var Archil = class {
2767
2950
  disks[relPath] = entry;
2768
2951
  } else disks[relPath] = diskIdFromMount(mount);
2769
2952
  return unwrap(retryApiRequest(() => this._client.POST("/api/exec", { body: {
2953
+ ...execVmBody(opts),
2770
2954
  disks,
2771
2955
  command: opts.command
2772
2956
  } }), "connect"));