disk 1.12.1 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,5 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
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");
3
5
  //#region src/api-fetch.ts
4
6
  function buildPath(template, params = {}) {
5
7
  return template.replace(/\{([^}]+)\}/g, (_, name) => {
@@ -288,7 +290,7 @@ function deriveS3BaseUrl(controlBaseUrl) {
288
290
  }
289
291
  //#endregion
290
292
  //#region src/version.ts
291
- const VERSION = "1.12.1";
293
+ const VERSION = "1.14.0";
292
294
  const USER_AGENT = `archil-js/${VERSION}`;
293
295
  //#endregion
294
296
  //#region src/client.ts
@@ -1565,6 +1567,8 @@ function imageFromWire(data) {
1565
1567
  digest: data.digest,
1566
1568
  canonicalSource: data.canonical_source,
1567
1569
  failureReason: data.failure_reason,
1570
+ vcpuCount: data.vcpu_count,
1571
+ memSizeMiB: data.mem_size_mib,
1568
1572
  createdAt: new Date(data.created_at),
1569
1573
  updatedAt: new Date(data.updated_at)
1570
1574
  };
@@ -1616,22 +1620,41 @@ var Images = class {
1616
1620
  async _request(request) {
1617
1621
  return imageFromWire(await unwrap(retryApiRequest(() => this._client.POST("/api/images", { body: {
1618
1622
  source: request.source,
1619
- registry_auth: request.registryAuth
1623
+ registry_auth: request.registryAuth,
1624
+ vcpu_count: request.vcpuCount,
1625
+ mem_size_mib: request.memSizeMiB
1620
1626
  } }), "transient")));
1621
1627
  }
1622
1628
  };
1623
1629
  //#endregion
1624
- //#region src/sandbox-process.ts
1625
- const PROCESS_STDIN_CHUNK_BYTES = 1024 * 1024;
1626
- /** Close codes the runtime uses when it ends a connection to a running process. */
1627
- const CLOSE_REASONS = {
1628
- 4001: "Process was taken over by another connection",
1629
- 4003: "Process owner disconnected"
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
+ }
1630
1655
  };
1631
- /** The subprotocol the runtime selects for a process connection. */
1632
- const CONNECT_SUBPROTOCOL = "archil.connect.v1";
1633
- /** Prefix of the subprotocol that carries a connection token. */
1634
- const TOKEN_SUBPROTOCOL_PREFIX = "archil.token.";
1656
+ //#endregion
1657
+ //#region src/process-connection.ts
1635
1658
  async function waitForSocketOpen(socket) {
1636
1659
  if (socket.readyState === WebSocket.OPEN) return;
1637
1660
  await new Promise((resolve, reject) => {
@@ -1659,11 +1682,11 @@ async function waitForSocketOpen(socket) {
1659
1682
  }
1660
1683
  async function openProcessSocket(connectionEndpoint) {
1661
1684
  for (let attempt = 0;; attempt++) {
1662
- const target = await connectionEndpoint();
1663
- const endpoint = typeof target === "string" ? { url: target } : target;
1685
+ const endpoint = await connectionEndpoint();
1664
1686
  let socket;
1665
1687
  try {
1666
- socket = endpoint.protocols ? new WebSocket(endpoint.url, endpoint.protocols) : new WebSocket(endpoint.url);
1688
+ socket = new WebSocket(endpoint.url, [PROTOCOL, `${TOKEN_PROTOCOL_PREFIX}${endpoint.token}`]);
1689
+ socket.binaryType = "arraybuffer";
1667
1690
  await waitForSocketOpen(socket);
1668
1691
  return socket;
1669
1692
  } catch (error) {
@@ -1675,12 +1698,359 @@ async function openProcessSocket(connectionEndpoint) {
1675
1698
  await retrySleep(attempt);
1676
1699
  }
1677
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
1678
2046
  /** @deprecated Use Sandbox.run() and Sandbox.attach(). Removed in the next version. */
1679
2047
  var SandboxProcesses = class {
1680
2048
  _sandbox;
2049
+ _disconnect;
1681
2050
  /** @internal */
1682
- constructor(_sandbox) {
2051
+ constructor(_sandbox, _disconnect) {
1683
2052
  this._sandbox = _sandbox;
2053
+ this._disconnect = _disconnect;
1684
2054
  }
1685
2055
  /** @deprecated Use sandbox.run(). Removed in the next version. */
1686
2056
  start(command, options = {}) {
@@ -1690,51 +2060,82 @@ var SandboxProcesses = class {
1690
2060
  connect(processId, options = {}) {
1691
2061
  return this._sandbox.attach(processId, options);
1692
2062
  }
2063
+ /** Disconnect process transport without terminating guest processes. */
2064
+ async disconnect() {
2065
+ this._disconnect();
2066
+ }
1693
2067
  };
1694
2068
  var SandboxProcess = class {
2069
+ _collectOutput;
2070
+ _buffer;
2071
+ _openConnection;
2072
+ _controlProcess;
1695
2073
  status = "running";
1696
2074
  stdout = "";
1697
2075
  stderr = "";
1698
2076
  _id;
1699
2077
  _cursor;
1700
- _onOutput;
1701
- _collectOutput;
1702
- _connectionEndpoint;
1703
- _controlProcess;
2078
+ _deliveredCursor;
1704
2079
  _stdoutDecoder = new TextDecoder();
1705
2080
  _stderrDecoder = new TextDecoder();
1706
- _terminal;
1707
- _resolveTerminal;
1708
- _result;
1709
2081
  _socket;
1710
- _connectionClosed;
1711
- _connectionError;
2082
+ _closed;
2083
+ _manual = false;
1712
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
+ } };
1713
2104
  /** @internal */
1714
- constructor(processId, cursor, onOutput, collectOutput, connectionEndpoint, controlProcess) {
2105
+ constructor(processId, cursor, _collectOutput, _buffer, _openConnection, _controlProcess) {
2106
+ this._collectOutput = _collectOutput;
2107
+ this._buffer = _buffer;
2108
+ this._openConnection = _openConnection;
2109
+ this._controlProcess = _controlProcess;
1715
2110
  this._id = processId;
1716
2111
  this._cursor = cursor;
1717
- this._onOutput = onOutput;
1718
- this._collectOutput = collectOutput;
1719
- this._connectionEndpoint = connectionEndpoint;
1720
- this._controlProcess = controlProcess;
1721
- this._terminal = new Promise((resolve) => {
1722
- this._resolveTerminal = resolve;
1723
- });
2112
+ this._deliveredCursor = cursor;
1724
2113
  }
1725
2114
  get id() {
1726
2115
  return this._id;
1727
2116
  }
2117
+ /** Next byte after output accepted into the SDK buffer. */
1728
2118
  get cursor() {
1729
2119
  return this._cursor;
1730
2120
  }
1731
2121
  get connected() {
1732
2122
  return this._socket?.readyState === WebSocket.OPEN;
1733
2123
  }
2124
+ /** Resolves once the runtime has accepted the input; waits while the process is not reading. */
1734
2125
  async sendInput(data) {
1735
2126
  if (this._stdinClosed) throw new Error("Process stdin is closed");
1736
2127
  const bytes = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
1737
- this._sendInput(bytes);
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
+ }
1738
2139
  }
1739
2140
  async resize(size) {
1740
2141
  if (this.status !== "running") throw new Error("Process has exited");
@@ -1744,146 +2145,178 @@ var SandboxProcess = class {
1744
2145
  ...size
1745
2146
  });
1746
2147
  }
1747
- /** Close stdin. Piped processes only. */
1748
- async closeStdin() {
1749
- if (this._stdinClosed) return;
1750
- this._sendControl({ type: "close_stdin" });
1751
- this._stdinClosed = true;
2148
+ async kill() {
2149
+ if (!this._exit) await this._controlProcess({
2150
+ type: "kill",
2151
+ process_id: this._id
2152
+ });
1752
2153
  }
1753
- /** Close this client connection without terminating the process. */
1754
2154
  async disconnect() {
1755
- const socket = this._socket;
1756
- const closed = this._connectionClosed;
1757
- if (!socket) return;
1758
- this._socket = void 0;
1759
- socket.close();
1760
- await closed;
2155
+ this._manual = true;
2156
+ this._socket?.close();
2157
+ await this._closed;
2158
+ if (!this._exit) this._fail(/* @__PURE__ */ new Error("Process is disconnected"));
1761
2159
  }
1762
2160
  async wait() {
1763
- if (this._result) return this._result;
1764
- const closed = this._connectionClosed;
1765
- if (!closed) throw new Error("Process is disconnected");
1766
- await Promise.race([this._terminal, closed]);
1767
- if (this._result) return this._result;
1768
- if (this._connectionError) throw this._connectionError;
1769
- throw new Error("Process connection closed before exit");
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
+ })();
1770
2179
  }
1771
- async kill() {
1772
- if (this._result) return;
1773
- await this._controlProcess({
1774
- type: "kill",
1775
- process_id: this._id
1776
- });
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
+ }
1777
2206
  }
1778
2207
  /** @internal */
1779
2208
  async _connect(request) {
1780
- const socket = await openProcessSocket(this._connectionEndpoint);
1781
- socket.binaryType = "arraybuffer";
2209
+ const socket = await this._openConnection();
2210
+ if (this._manual) {
2211
+ socket.close();
2212
+ throw new Error("Process is disconnected");
2213
+ }
1782
2214
  this._socket = socket;
1783
- let resolveClosed;
1784
- this._connectionClosed = new Promise((resolve) => {
1785
- resolveClosed = resolve;
2215
+ let closed;
2216
+ this._closed = new Promise((resolve) => {
2217
+ closed = resolve;
1786
2218
  });
2219
+ const expected = request.type === "start" ? "started" : "attached";
2220
+ let settled = false;
1787
2221
  let resolveReady;
1788
2222
  let rejectReady;
1789
- let readySettled = false;
1790
2223
  const ready = new Promise((resolve, reject) => {
1791
- resolveReady = () => {
1792
- readySettled = true;
1793
- resolve();
1794
- };
1795
- rejectReady = (error) => {
1796
- readySettled = true;
1797
- reject(error);
1798
- };
2224
+ resolveReady = resolve;
2225
+ rejectReady = reject;
1799
2226
  });
1800
- const expectedReady = request.type === "start" ? "started" : "attached";
1801
- const fail = (error) => {
1802
- if (!readySettled) rejectReady(error instanceof Error ? error : new Error(String(error)));
1803
- };
1804
2227
  socket.addEventListener("message", (message) => {
1805
- let output;
2228
+ if (this._socket !== socket) return;
1806
2229
  try {
1807
- output = this._handleMessage(message.data, expectedReady, resolveReady);
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
+ }
1808
2253
  } catch (error) {
1809
- const connectionError = error instanceof Error ? error : new Error(String(error));
1810
- this._connectionError = connectionError;
1811
- fail(connectionError);
2254
+ const failure = error instanceof Error ? error : new Error(String(error));
2255
+ if (!settled) rejectReady(failure);
2256
+ this._fail(failure);
1812
2257
  socket.close();
1813
- return;
1814
2258
  }
1815
- if (output) this._onOutput?.(output);
1816
2259
  });
1817
2260
  socket.addEventListener("error", () => {
1818
2261
  const error = /* @__PURE__ */ new Error("Process connection failed");
1819
- this._connectionError = error;
1820
- fail(error);
2262
+ if (!settled) rejectReady(error);
2263
+ this._fail(error);
1821
2264
  });
1822
- socket.addEventListener("close", (event) => {
1823
- const reason = CLOSE_REASONS[event.code];
1824
- if (reason && !this._result) this._connectionError = new Error(reason);
2265
+ socket.addEventListener("close", () => {
1825
2266
  if (this._socket === socket) this._socket = void 0;
1826
- if (!readySettled) rejectReady(/* @__PURE__ */ new Error("Process connection closed before ready"));
1827
- resolveClosed();
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"));
1828
2270
  }, { once: true });
1829
- socket.send(JSON.stringify(request));
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
+ }
1830
2278
  await ready;
1831
2279
  }
1832
2280
  _openSocket() {
1833
2281
  if (this.status !== "running") throw new Error("Process has exited");
1834
- if (!this._socket || this._socket.readyState !== WebSocket.OPEN) throw new Error("Process is disconnected");
2282
+ if (!this.connected) throw new Error("Process is disconnected");
1835
2283
  return this._socket;
1836
2284
  }
1837
- _sendControl(message) {
1838
- this._openSocket().send(JSON.stringify(message));
2285
+ _fail(error) {
2286
+ this._error ??= error instanceof Error ? error : new Error(String(error));
2287
+ this._resolveDone();
2288
+ this._wake?.();
1839
2289
  }
1840
- _sendInput(data) {
1841
- const socket = this._openSocket();
1842
- for (let offset = 0; offset < data.byteLength; offset += PROCESS_STDIN_CHUNK_BYTES) {
1843
- const chunk = new Uint8Array(Math.min(PROCESS_STDIN_CHUNK_BYTES, data.byteLength - offset));
1844
- chunk.set(data.subarray(offset, offset + chunk.byteLength));
1845
- socket.send(chunk);
1846
- }
1847
- }
1848
- _handleMessage(data, expectedReady, ready) {
1849
- if (typeof data !== "string") return this._handleOutput(data);
1850
- const event = JSON.parse(data);
1851
- switch (event.type) {
1852
- case "started":
1853
- case "attached":
1854
- if (event.type !== expectedReady) throw new Error(`Expected ${expectedReady}, received ${event.type}`);
1855
- if (this._id && this._id !== event.process_id) throw new Error("Runtime returned a different process ID");
1856
- this._id = event.process_id;
1857
- ready();
1858
- return;
1859
- case "exit":
1860
- this._finish(event);
1861
- return;
1862
- case "error": throw /* @__PURE__ */ new Error(`${event.error}: ${event.message}`);
1863
- }
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();
1864
2301
  }
1865
- _handleOutput(data) {
1866
- const bytes = new Uint8Array(data);
1867
- if (bytes.byteLength < 9 || bytes[0] !== 1 && bytes[0] !== 2) throw new Error("Invalid process output frame");
1868
- const offset = Number(new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getBigUint64(1));
1869
- const payload = bytes.subarray(9);
2302
+ /** `release` returns the output's flow-control credit once it is consumed. */
2303
+ _enqueueOutput(payload, offset, stream, release) {
1870
2304
  const end = offset + payload.byteLength;
1871
- if (end <= this._cursor) return;
1872
- if (offset > this._cursor) {
1873
- this._flushDecoders();
1874
- this._cursor = offset;
2305
+ if (end <= this._cursor) {
2306
+ release();
2307
+ return;
1875
2308
  }
1876
- const skip = Math.max(0, this._cursor - offset);
1877
- const unread = payload.subarray(skip);
1878
- const unreadOffset = offset + skip;
1879
- this._cursor = end;
1880
- const stream = bytes[0] === 1 ? "stdout" : "stderr";
1881
- if (this._collectOutput) this._appendText(stream, (stream === "stdout" ? this._stdoutDecoder : this._stderrDecoder).decode(unread, { stream: true }));
1882
- return {
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 = {
1883
2312
  stream,
1884
- offset: unreadOffset,
1885
- data: unread
2313
+ offset: this._cursor,
2314
+ data: payload.slice(skip)
1886
2315
  };
2316
+ this._buffer.push(this, output);
2317
+ this._releases.set(output, release);
2318
+ this._cursor = end;
2319
+ this._wake?.();
1887
2320
  }
1888
2321
  _appendText(stream, data) {
1889
2322
  if (stream === "stdout") this.stdout += data;
@@ -1894,21 +2327,6 @@ var SandboxProcess = class {
1894
2327
  this._appendText("stdout", this._stdoutDecoder.decode());
1895
2328
  this._appendText("stderr", this._stderrDecoder.decode());
1896
2329
  }
1897
- _finish(event) {
1898
- if (this._result) return;
1899
- this.status = event.status;
1900
- this._stdinClosed = true;
1901
- this._flushDecoders();
1902
- this._cursor = Math.max(this._cursor, event.cursor);
1903
- this._result = {
1904
- status: event.status,
1905
- exitCode: event.exit_code ?? void 0,
1906
- exitReason: event.exit_reason ?? void 0,
1907
- stdout: this.stdout,
1908
- stderr: this.stderr
1909
- };
1910
- this._resolveTerminal(this._result);
1911
- }
1912
2330
  };
1913
2331
  //#endregion
1914
2332
  //#region src/sandbox-files.ts
@@ -1932,32 +2350,15 @@ while IFS= read -r count; do
1932
2350
  [ "$size" -eq "$count" ] || break
1933
2351
  done`;
1934
2352
  var ProcessOutputReader = class {
1935
- onOutput = (output) => {
1936
- if (output.offset !== this._cursor) {
1937
- this._push(/* @__PURE__ */ new Error(`Sandbox process output gap: expected offset ${this._cursor}, received ${output.offset}`));
1938
- return;
1939
- }
1940
- this._cursor += output.data.byteLength;
1941
- if (output.stream === "stdout") this._push(output.data);
1942
- else this._stderr += this._stderrDecoder.decode(output.data, { stream: true });
1943
- };
1944
2353
  _buffer = /* @__PURE__ */ new Uint8Array();
1945
2354
  _cursor = 0;
1946
- _chunks = [];
1947
2355
  _stderrDecoder = new TextDecoder();
1948
2356
  _stderr = "";
1949
- _waiting;
1950
- _exit;
2357
+ _process;
2358
+ _output;
1951
2359
  attach(process) {
1952
- this._exit = process.wait();
1953
- this._exit.then((result) => {
1954
- try {
1955
- assertSuccessful(result, this._stderrText());
1956
- this._push(/* @__PURE__ */ new Error("Sandbox process exited before file transfer completed"));
1957
- } catch (error) {
1958
- this._push(toError(error));
1959
- }
1960
- }, (error) => this._push(toError(error)));
2360
+ this._process = process;
2361
+ this._output = process.output[Symbol.asyncIterator]();
1961
2362
  }
1962
2363
  async readLine() {
1963
2364
  while (true) {
@@ -1971,32 +2372,28 @@ var ProcessOutputReader = class {
1971
2372
  }
1972
2373
  }
1973
2374
  async read(size) {
1974
- while (this._buffer.byteLength < size) this._buffer = concat(this._buffer, await this._nextChunk());
2375
+ while (this._buffer.length < size) this._buffer = concat(this._buffer, await this._nextChunk());
1975
2376
  const data = this._buffer.slice(0, size);
1976
2377
  this._buffer = this._buffer.slice(size);
1977
2378
  return data;
1978
2379
  }
1979
2380
  async wait() {
1980
- if (!this._exit) throw new Error("File transfer process has not started");
1981
- assertSuccessful(await this._exit, this._stderrText());
1982
- }
1983
- _stderrText() {
1984
- this._stderr += this._stderrDecoder.decode();
1985
- return this._stderr;
1986
- }
1987
- _push(value) {
1988
- const waiting = this._waiting;
1989
- if (waiting) {
1990
- this._waiting = void 0;
1991
- waiting(value);
1992
- } else this._chunks.push(value);
2381
+ while (!(await this._output.next()).done);
2382
+ assertSuccessful(await this._process.wait(), this._stderr + this._stderrDecoder.decode());
1993
2383
  }
1994
2384
  async _nextChunk() {
1995
- const value = this._chunks.shift() ?? await new Promise((resolve) => {
1996
- this._waiting = resolve;
1997
- });
1998
- if (value instanceof Error) throw value;
1999
- return value;
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
+ }
2000
2397
  }
2001
2398
  };
2002
2399
  var SandboxFiles = class {
@@ -2038,7 +2435,6 @@ var SandboxFiles = class {
2038
2435
  ARCHIL_FILE_PATH: path,
2039
2436
  ARCHIL_FILE_TEMP: `/tmp/.archil-download-${transferId()}`
2040
2437
  },
2041
- onOutput: reader.onOutput,
2042
2438
  collectOutput: false
2043
2439
  });
2044
2440
  reader.attach(process);
@@ -2161,6 +2557,7 @@ function sleep() {
2161
2557
  var Sandbox = class Sandbox {
2162
2558
  id;
2163
2559
  name;
2560
+ labels;
2164
2561
  status;
2165
2562
  vcpuCount;
2166
2563
  memSizeMiB;
@@ -2169,6 +2566,7 @@ var Sandbox = class Sandbox {
2169
2566
  platform;
2170
2567
  maxTtlSeconds;
2171
2568
  idleTtlSeconds;
2569
+ onTimeout;
2172
2570
  maxConcurrentExecs;
2173
2571
  endpoints;
2174
2572
  mounts;
@@ -2183,17 +2581,21 @@ var Sandbox = class Sandbox {
2183
2581
  files;
2184
2582
  /** @internal */
2185
2583
  _client;
2584
+ _processConnection;
2585
+ _processOutput = new ProcessOutputBuffer();
2186
2586
  /** @internal */
2187
2587
  constructor(data, client) {
2188
2588
  this._client = client;
2189
2589
  this._apply(data);
2190
- this.processes = new SandboxProcesses(this);
2590
+ this._processConnection = new ProcessConnection(() => this._connectionEndpoint());
2591
+ this.processes = new SandboxProcesses(this, () => this._processConnection.disconnect());
2191
2592
  this.files = new SandboxFiles(this);
2192
2593
  }
2193
2594
  /** @internal Overwrite this sandbox's fields in place from a fresh wire snapshot. */
2194
2595
  _apply(data) {
2195
2596
  this.id = data.sandbox_id;
2196
2597
  this.name = data.name;
2598
+ this.labels = { ...data.labels };
2197
2599
  this.status = data.status;
2198
2600
  this.vcpuCount = data.vcpu_count;
2199
2601
  this.memSizeMiB = data.mem_size_mib;
@@ -2202,6 +2604,7 @@ var Sandbox = class Sandbox {
2202
2604
  this.platform = data.platform;
2203
2605
  this.maxTtlSeconds = data.max_ttl_seconds;
2204
2606
  this.idleTtlSeconds = data.idle_ttl_seconds ?? 0;
2607
+ this.onTimeout = data.on_timeout ?? "pause";
2205
2608
  this.maxConcurrentExecs = data.max_concurrent_execs;
2206
2609
  this.endpoints = data.endpoints?.map((endpoint) => ({ ...endpoint }));
2207
2610
  this.mounts = (data.mounts ?? []).map(sandboxMountFromWire);
@@ -2217,6 +2620,7 @@ var Sandbox = class Sandbox {
2217
2620
  return {
2218
2621
  id: this.id,
2219
2622
  name: this.name,
2623
+ labels: { ...this.labels },
2220
2624
  status: this.status,
2221
2625
  vcpuCount: this.vcpuCount,
2222
2626
  memSizeMiB: this.memSizeMiB,
@@ -2225,6 +2629,7 @@ var Sandbox = class Sandbox {
2225
2629
  platform: this.platform,
2226
2630
  maxTtlSeconds: this.maxTtlSeconds,
2227
2631
  idleTtlSeconds: this.idleTtlSeconds,
2632
+ onTimeout: this.onTimeout,
2228
2633
  maxConcurrentExecs: this.maxConcurrentExecs,
2229
2634
  endpoints: this.endpoints?.map((endpoint) => ({ ...endpoint })),
2230
2635
  mounts: this.mounts.map((mount) => ({ ...mount })),
@@ -2238,7 +2643,7 @@ var Sandbox = class Sandbox {
2238
2643
  }
2239
2644
  /** Start a process and return its handle without waiting for exit. */
2240
2645
  async run(command, options = {}) {
2241
- const process = new SandboxProcess("", 0, options.onOutput, options.collectOutput ?? true, () => this._connectionEndpoint(), (request) => this._control(request));
2646
+ const process = new SandboxProcess("", 0, options.collectOutput ?? true, this._processOutput, () => this._processConnection.open(), (request) => this._control(request));
2242
2647
  const terminal = typeof options.terminal === "object" ? {
2243
2648
  cols: options.terminal.cols ?? 80,
2244
2649
  rows: options.terminal.rows ?? 24
@@ -2251,35 +2656,36 @@ var Sandbox = class Sandbox {
2251
2656
  env: options.env ?? {},
2252
2657
  timeout_seconds: options.timeoutSeconds
2253
2658
  });
2659
+ if (options.onOutput) process._deliverTo(options.onOutput);
2254
2660
  return process;
2255
2661
  }
2256
2662
  /** Reattach to a process, optionally resuming output from a cursor. */
2257
2663
  async attach(processId, options = {}) {
2258
2664
  const offset = options.offset ?? 0;
2259
- const process = new SandboxProcess(processId, offset, options.onOutput, options.collectOutput ?? true, () => this._connectionEndpoint(), (request) => this._control(request));
2665
+ const process = new SandboxProcess(processId, offset, options.collectOutput ?? true, this._processOutput, () => this._processConnection.open(), (request) => this._control(request));
2260
2666
  await process._connect({
2261
2667
  type: "attach",
2262
2668
  process_id: processId,
2263
2669
  offset,
2264
2670
  ...options.shared ? { shared: true } : {}
2265
2671
  });
2672
+ if (options.onOutput) process._deliverTo(options.onOutput);
2266
2673
  return process;
2267
2674
  }
2268
2675
  async _connectionEndpoint() {
2269
2676
  const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this.id } } }), "transient"));
2270
- if (data.endpoint && data.token) return {
2677
+ return {
2271
2678
  url: data.endpoint,
2272
- protocols: [CONNECT_SUBPROTOCOL, `${TOKEN_SUBPROTOCOL_PREFIX}${data.token}`]
2679
+ token: data.token
2273
2680
  };
2274
- return { url: data.url };
2275
2681
  }
2276
2682
  async _control(request) {
2277
- const socket = await openProcessSocket(() => this._connectionEndpoint());
2683
+ const socket = await this._processConnection.open();
2278
2684
  const expected = request.type === "kill" ? "killed" : "resized";
2279
2685
  await new Promise((resolve, reject) => {
2280
2686
  socket.addEventListener("message", (message) => {
2281
2687
  try {
2282
- const event = JSON.parse(message.data);
2688
+ const event = message.data;
2283
2689
  if (event.type === "error") reject(/* @__PURE__ */ new Error(`${event.error}: ${event.message}`));
2284
2690
  else if (event.type !== expected) reject(/* @__PURE__ */ new Error(`Expected ${expected}, received ${event.type}`));
2285
2691
  else resolve();
@@ -2291,7 +2697,12 @@ var Sandbox = class Sandbox {
2291
2697
  }, { once: true });
2292
2698
  socket.addEventListener("error", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} request failed`)));
2293
2699
  socket.addEventListener("close", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} connection closed before confirmation`)));
2294
- socket.send(JSON.stringify(request));
2700
+ try {
2701
+ socket.sendRequest(request);
2702
+ } catch (error) {
2703
+ reject(error);
2704
+ socket.finish();
2705
+ }
2295
2706
  });
2296
2707
  }
2297
2708
  /** Run a process and wait for it to exit. */
@@ -2356,7 +2767,8 @@ var Sandbox = class Sandbox {
2356
2767
  const wait = resumeAfterFork ? false : options.wait ?? true;
2357
2768
  const body = {
2358
2769
  name: options.name,
2359
- checkpoint
2770
+ checkpoint,
2771
+ labels: options.labels
2360
2772
  };
2361
2773
  const fork = await waitWhileSandboxStatus(this, "pausing").then(() => unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/fork", {
2362
2774
  params: {
@@ -2495,6 +2907,11 @@ async function waitWhileSandboxStatus(sandbox, status) {
2495
2907
  }
2496
2908
  //#endregion
2497
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
+ }
2498
2915
  var Sandboxes = class {
2499
2916
  /** @internal */
2500
2917
  _client;
@@ -2502,10 +2919,29 @@ var Sandboxes = class {
2502
2919
  constructor(client) {
2503
2920
  this._client = client;
2504
2921
  }
2505
- /** List the account's sandboxes, oldest first. */
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
+ */
2506
2926
  async list(options = {}) {
2507
2927
  const filesystem = typeof options.disk === "string" ? options.disk : options.disk?.id;
2508
- return ((await unwrap(retryApiRequest(() => this._client.GET("/api/sandboxes", { params: { query: { filesystem } } }), "transient")))?.sandboxes ?? []).map((sandbox) => new Sandbox(sandbox, this._client));
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
+ }
2509
2945
  }
2510
2946
  async get(id) {
2511
2947
  return new Sandbox(await unwrap(retryApiRequest(() => this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: id } } }), "transient")), this._client);
@@ -2520,10 +2956,12 @@ var Sandboxes = class {
2520
2956
  env: request.env,
2521
2957
  max_ttl_seconds: request.maxTtlSeconds,
2522
2958
  idle_ttl_seconds: request.idleTtlSeconds,
2959
+ on_timeout: request.onTimeout,
2523
2960
  max_concurrent_execs: request.maxConcurrentExecs,
2524
2961
  network: request.network,
2525
2962
  ports: request.ports,
2526
- ...request.mounts !== void 0 && { mounts: request.mounts.map(sandboxMountWire) }
2963
+ ...request.mounts !== void 0 && { mounts: request.mounts.map(sandboxMountWire) },
2964
+ labels: request.labels
2527
2965
  };
2528
2966
  const sandbox = new Sandbox(await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes", {
2529
2967
  params: { query: { wait: options.wait ?? true } },