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.
@@ -1,4 +1,6 @@
1
1
  import { t as toSegments } from "./paths-Br9snUhy.mjs";
2
+ import { create, fromBinary, toBinary } from "@bufbuild/protobuf";
3
+ import { ClientFrameSchema, Exit_Status, Limits, ServerFrameSchema, WindowUpdateSchema } from "@archildata/api-types/process";
2
4
  //#region src/api-fetch.ts
3
5
  function buildPath(template, params = {}) {
4
6
  return template.replace(/\{([^}]+)\}/g, (_, name) => {
@@ -287,7 +289,7 @@ function deriveS3BaseUrl(controlBaseUrl) {
287
289
  }
288
290
  //#endregion
289
291
  //#region src/version.ts
290
- const VERSION = "1.12.1";
292
+ const VERSION = "1.14.0";
291
293
  const USER_AGENT = `archil-js/${VERSION}`;
292
294
  //#endregion
293
295
  //#region src/client.ts
@@ -1564,6 +1566,8 @@ function imageFromWire(data) {
1564
1566
  digest: data.digest,
1565
1567
  canonicalSource: data.canonical_source,
1566
1568
  failureReason: data.failure_reason,
1569
+ vcpuCount: data.vcpu_count,
1570
+ memSizeMiB: data.mem_size_mib,
1567
1571
  createdAt: new Date(data.created_at),
1568
1572
  updatedAt: new Date(data.updated_at)
1569
1573
  };
@@ -1615,22 +1619,41 @@ var Images = class {
1615
1619
  async _request(request) {
1616
1620
  return imageFromWire(await unwrap(retryApiRequest(() => this._client.POST("/api/images", { body: {
1617
1621
  source: request.source,
1618
- registry_auth: request.registryAuth
1622
+ registry_auth: request.registryAuth,
1623
+ vcpu_count: request.vcpuCount,
1624
+ mem_size_mib: request.memSizeMiB
1619
1625
  } }), "transient")));
1620
1626
  }
1621
1627
  };
1622
1628
  //#endregion
1623
- //#region src/sandbox-process.ts
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
+ //#region src/process-output-buffer.ts
1630
+ /**
1631
+ * Output each process has received but its iterator has not taken yet.
1632
+ * Flow control bounds it to one channel window per process, so it never
1633
+ * needs to refuse output. Output a handle never reads goes with the handle.
1634
+ */
1635
+ var ProcessOutputBuffer = class {
1636
+ queues = /* @__PURE__ */ new WeakMap();
1637
+ has(subscription) {
1638
+ return !!this.queues.get(subscription)?.length;
1639
+ }
1640
+ push(subscription, output) {
1641
+ const queue = this.queues.get(subscription) ?? [];
1642
+ queue.push(output);
1643
+ this.queues.set(subscription, queue);
1644
+ }
1645
+ take(subscription) {
1646
+ const queue = this.queues.get(subscription);
1647
+ const output = queue?.shift();
1648
+ if (queue && !queue.length) this.queues.delete(subscription);
1649
+ return output;
1650
+ }
1651
+ discard(subscription) {
1652
+ this.queues.delete(subscription);
1653
+ }
1629
1654
  };
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.";
1655
+ //#endregion
1656
+ //#region src/process-connection.ts
1634
1657
  async function waitForSocketOpen(socket) {
1635
1658
  if (socket.readyState === WebSocket.OPEN) return;
1636
1659
  await new Promise((resolve, reject) => {
@@ -1658,11 +1681,11 @@ async function waitForSocketOpen(socket) {
1658
1681
  }
1659
1682
  async function openProcessSocket(connectionEndpoint) {
1660
1683
  for (let attempt = 0;; attempt++) {
1661
- const target = await connectionEndpoint();
1662
- const endpoint = typeof target === "string" ? { url: target } : target;
1684
+ const endpoint = await connectionEndpoint();
1663
1685
  let socket;
1664
1686
  try {
1665
- socket = endpoint.protocols ? new WebSocket(endpoint.url, endpoint.protocols) : new WebSocket(endpoint.url);
1687
+ socket = new WebSocket(endpoint.url, [PROTOCOL, `${TOKEN_PROTOCOL_PREFIX}${endpoint.token}`]);
1688
+ socket.binaryType = "arraybuffer";
1666
1689
  await waitForSocketOpen(socket);
1667
1690
  return socket;
1668
1691
  } catch (error) {
@@ -1674,12 +1697,359 @@ async function openProcessSocket(connectionEndpoint) {
1674
1697
  await retrySleep(attempt);
1675
1698
  }
1676
1699
  }
1700
+ /** Bound queued socket writes across all channels of a connection. */
1701
+ async function waitForProcessWrite(socket) {
1702
+ while (socket.bufferedAmount > 256 * 1024) {
1703
+ if (socket.readyState !== WebSocket.OPEN) throw new Error("Process is disconnected");
1704
+ await new Promise((resolve) => setTimeout(resolve, 0));
1705
+ }
1706
+ }
1707
+ const PROTOCOL = "archil.connect.v2";
1708
+ const TOKEN_PROTOCOL_PREFIX = "archil.token.";
1709
+ const MAX_DATA = Limits.MAX_DATA_BYTES;
1710
+ const INITIAL_WINDOW = Limits.INITIAL_WINDOW;
1711
+ const MIN_DATA_COST = Limits.MIN_DATA_COST;
1712
+ const dataCost = (length) => Math.max(length, MIN_DATA_COST);
1713
+ const MAX_CHANNELS = 128;
1714
+ const IDLE_MS = 5e3;
1715
+ /** Owns only the client connection. A disconnected transport never retries START. */
1716
+ var ProcessConnection = class {
1717
+ endpoint;
1718
+ opening;
1719
+ binary;
1720
+ /** Every open connection, including ones a drain or full channel table left behind. */
1721
+ live = /* @__PURE__ */ new Set();
1722
+ generation = 0;
1723
+ constructor(endpoint) {
1724
+ this.endpoint = endpoint;
1725
+ }
1726
+ async open() {
1727
+ for (;;) {
1728
+ if (this.binary?.canOpen) return this.binary.channel();
1729
+ if (!this.opening) {
1730
+ const opening = this.connect().finally(() => {
1731
+ if (this.opening === opening) this.opening = void 0;
1732
+ });
1733
+ this.opening = opening;
1734
+ }
1735
+ const binary = await this.opening;
1736
+ if (binary.canOpen) return binary.channel();
1737
+ }
1738
+ }
1739
+ async connect() {
1740
+ const generation = this.generation;
1741
+ const socket = await openProcessSocket(this.endpoint);
1742
+ if (generation !== this.generation) {
1743
+ socket.close();
1744
+ throw new Error("Process connection opening cancelled");
1745
+ }
1746
+ if (socket.protocol !== PROTOCOL) {
1747
+ socket.close();
1748
+ throw new Error(`Sandbox runtime does not support the ${PROTOCOL} process protocol`);
1749
+ }
1750
+ const binary = new BinaryConnection(socket, () => this.live.delete(binary));
1751
+ this.live.add(binary);
1752
+ this.binary = binary;
1753
+ return binary;
1754
+ }
1755
+ disconnect() {
1756
+ this.generation++;
1757
+ this.opening = void 0;
1758
+ for (const binary of [...this.live]) binary.close();
1759
+ this.binary = void 0;
1760
+ }
1761
+ };
1762
+ var BinaryConnection = class {
1763
+ socket;
1764
+ onClosed;
1765
+ channels = /* @__PURE__ */ new Map();
1766
+ next = 1;
1767
+ draining = false;
1768
+ idle;
1769
+ get canOpen() {
1770
+ return !this.draining && this.socket.readyState === WebSocket.OPEN && this.next < 4294967295 && this.channels.size < MAX_CHANNELS;
1771
+ }
1772
+ constructor(socket, onClosed) {
1773
+ this.socket = socket;
1774
+ this.onClosed = onClosed;
1775
+ socket.addEventListener("message", (message) => {
1776
+ try {
1777
+ const frame = fromBinary(ServerFrameSchema, new Uint8Array(message.data));
1778
+ if (frame.channelId === 0) {
1779
+ if (frame.body.case !== "drain") return;
1780
+ this.draining = true;
1781
+ if (!this.channels.size) this.close();
1782
+ } else this.channels.get(frame.channelId)?.receive(frame);
1783
+ } catch (error) {
1784
+ this.close(error);
1785
+ }
1786
+ });
1787
+ socket.addEventListener("close", () => this.close(/* @__PURE__ */ new Error("Process connection closed before exit")), { once: true });
1788
+ socket.addEventListener("error", () => this.close(/* @__PURE__ */ new Error("Process connection failed")), { once: true });
1789
+ }
1790
+ channel() {
1791
+ if (!this.canOpen) throw new Error("Process connection is draining or full");
1792
+ clearTimeout(this.idle);
1793
+ const channel = new BinaryChannel(this, this.next++);
1794
+ this.channels.set(channel.id, channel);
1795
+ return channel;
1796
+ }
1797
+ send(id, body) {
1798
+ this.socket.send(toBinary(ClientFrameSchema, create(ClientFrameSchema, {
1799
+ channelId: id,
1800
+ body
1801
+ })));
1802
+ }
1803
+ async writable() {
1804
+ await waitForProcessWrite(this.socket);
1805
+ }
1806
+ remove(id) {
1807
+ this.channels.delete(id);
1808
+ if (!this.channels.size) if (this.draining) this.close();
1809
+ else this.idle = setTimeout(() => this.close(), IDLE_MS);
1810
+ }
1811
+ close(reason) {
1812
+ this.draining = true;
1813
+ this.onClosed();
1814
+ clearTimeout(this.idle);
1815
+ for (const channel of [...this.channels.values()]) channel.finish(reason);
1816
+ if (this.socket.readyState < WebSocket.CLOSING) this.socket.close();
1817
+ }
1818
+ };
1819
+ /** @internal WebSocket-shaped channel; generated protobuf owns all wire encoding. */
1820
+ var BinaryChannel = class {
1821
+ connection;
1822
+ id;
1823
+ readyState = WebSocket.OPEN;
1824
+ binaryType = "arraybuffer";
1825
+ events = new EventTarget();
1826
+ addEventListener = this.events.addEventListener.bind(this.events);
1827
+ sending = Promise.resolve();
1828
+ /** Stdin the runtime will accept. */
1829
+ sendCredit = INITIAL_WINDOW;
1830
+ /** Output the runtime may still send. */
1831
+ receiveCredit = INITIAL_WINDOW;
1832
+ /** Output consumed since credit was last returned. */
1833
+ consumed = 0;
1834
+ creditChanged;
1835
+ constructor(connection, id) {
1836
+ this.connection = connection;
1837
+ this.id = id;
1838
+ }
1839
+ sendRequest(request) {
1840
+ switch (request.type) {
1841
+ case "start": {
1842
+ const terminal = request.terminal === true ? {
1843
+ rows: 24,
1844
+ cols: 80
1845
+ } : request.terminal || void 0;
1846
+ this.connection.send(this.id, create(ClientFrameSchema, { body: {
1847
+ case: "start",
1848
+ value: {
1849
+ command: request.command,
1850
+ cwd: request.cwd,
1851
+ terminal,
1852
+ env: request.env,
1853
+ timeoutSeconds: request.timeout_seconds === void 0 ? void 0 : BigInt(request.timeout_seconds)
1854
+ }
1855
+ } }).body);
1856
+ break;
1857
+ }
1858
+ case "attach":
1859
+ this.connection.send(this.id, create(ClientFrameSchema, { body: {
1860
+ case: "attach",
1861
+ value: {
1862
+ processId: request.process_id,
1863
+ offset: BigInt(request.offset),
1864
+ shared: request.shared ?? false
1865
+ }
1866
+ } }).body);
1867
+ break;
1868
+ case "kill":
1869
+ this.connection.send(this.id, create(ClientFrameSchema, { body: {
1870
+ case: "kill",
1871
+ value: { processId: request.process_id }
1872
+ } }).body);
1873
+ break;
1874
+ case "resize":
1875
+ this.connection.send(this.id, create(ClientFrameSchema, { body: {
1876
+ case: "resize",
1877
+ value: {
1878
+ processId: request.process_id,
1879
+ terminal: {
1880
+ rows: request.rows,
1881
+ cols: request.cols
1882
+ }
1883
+ }
1884
+ } }).body);
1885
+ break;
1886
+ }
1887
+ }
1888
+ send(bytes) {
1889
+ const sending = this.sending.then(async () => {
1890
+ for (let offset = 0; offset < bytes.length; offset += MAX_DATA) {
1891
+ const chunk = bytes.subarray(offset, offset + MAX_DATA);
1892
+ while (this.sendCredit < dataCost(chunk.length)) {
1893
+ if (this.readyState !== WebSocket.OPEN) throw new Error("Process is disconnected");
1894
+ await new Promise((resolve) => {
1895
+ this.creditChanged = resolve;
1896
+ });
1897
+ }
1898
+ if (this.readyState !== WebSocket.OPEN) throw new Error("Process is disconnected");
1899
+ this.sendCredit -= dataCost(chunk.length);
1900
+ this.connection.send(this.id, {
1901
+ case: "stdin",
1902
+ value: chunk
1903
+ });
1904
+ await this.connection.writable();
1905
+ }
1906
+ });
1907
+ this.sending = sending.catch(() => {});
1908
+ return sending;
1909
+ }
1910
+ /** Returns credit for output the application has taken. */
1911
+ release(cost) {
1912
+ if (this.readyState === WebSocket.CLOSED) return;
1913
+ this.consumed += cost;
1914
+ if (this.consumed < INITIAL_WINDOW / 2) return;
1915
+ this.receiveCredit += this.consumed;
1916
+ this.connection.send(this.id, {
1917
+ case: "windowUpdate",
1918
+ value: create(WindowUpdateSchema, { bytes: this.consumed })
1919
+ });
1920
+ this.consumed = 0;
1921
+ }
1922
+ async closeStdin() {
1923
+ await this.sending;
1924
+ if (this.readyState !== WebSocket.OPEN) throw new Error("Process is disconnected");
1925
+ this.connection.send(this.id, create(ClientFrameSchema, { body: {
1926
+ case: "closeStdin",
1927
+ value: {}
1928
+ } }).body);
1929
+ }
1930
+ close() {
1931
+ if (this.readyState !== WebSocket.OPEN) return;
1932
+ this.readyState = WebSocket.CLOSING;
1933
+ this.connection.send(this.id, create(ClientFrameSchema, { body: {
1934
+ case: "detach",
1935
+ value: {}
1936
+ } }).body);
1937
+ }
1938
+ receive(frame) {
1939
+ const body = frame.body;
1940
+ let event;
1941
+ switch (body.case) {
1942
+ case "started":
1943
+ case "attached":
1944
+ event = {
1945
+ type: body.case,
1946
+ process_id: body.value.processId
1947
+ };
1948
+ break;
1949
+ case "windowUpdate":
1950
+ this.sendCredit += body.value.bytes;
1951
+ this.creditChanged?.();
1952
+ return;
1953
+ case "stdout":
1954
+ case "stderr": {
1955
+ if (body.value.data.length > MAX_DATA) throw new Error("Process output exceeds chunk size");
1956
+ const cost = dataCost(body.value.data.length);
1957
+ if (cost > this.receiveCredit) throw new Error("Process output exceeded its flow-control window");
1958
+ this.receiveCredit -= cost;
1959
+ const offset = Number(body.value.offset);
1960
+ if (!Number.isSafeInteger(offset)) {
1961
+ this.fail("output_offset_overflow", "Process offset exceeds JavaScript integer precision");
1962
+ return;
1963
+ }
1964
+ this.events.dispatchEvent(new MessageEvent("message", { data: {
1965
+ stream: body.case,
1966
+ offset,
1967
+ data: body.value.data,
1968
+ cost
1969
+ } }));
1970
+ return;
1971
+ }
1972
+ case "exit": {
1973
+ const status = {
1974
+ [Exit_Status.COMPLETED]: "completed",
1975
+ [Exit_Status.FAILED]: "failed",
1976
+ [Exit_Status.CANCELLED]: "cancelled",
1977
+ [Exit_Status.TIMED_OUT]: "timed_out"
1978
+ }[body.value.status];
1979
+ if (!status) {
1980
+ this.fail("unsupported_exit_status", `Unknown process exit status ${body.value.status}`);
1981
+ return;
1982
+ }
1983
+ event = {
1984
+ type: "exit",
1985
+ status,
1986
+ exit_code: body.value.exitCode,
1987
+ exit_reason: body.value.exitReason,
1988
+ cursor: Number(body.value.cursor)
1989
+ };
1990
+ break;
1991
+ }
1992
+ case "error":
1993
+ event = {
1994
+ type: "error",
1995
+ error: body.value.code,
1996
+ message: body.value.message
1997
+ };
1998
+ break;
1999
+ case "killed":
2000
+ case "resized":
2001
+ event = { type: body.case };
2002
+ break;
2003
+ case "detached":
2004
+ this.finish();
2005
+ return;
2006
+ case void 0: return;
2007
+ default: throw new Error("Unexpected process channel message");
2008
+ }
2009
+ this.events.dispatchEvent(new MessageEvent("message", { data: event }));
2010
+ if ([
2011
+ "exit",
2012
+ "error",
2013
+ "killed",
2014
+ "resized"
2015
+ ].includes(body.case)) this.finish();
2016
+ }
2017
+ /** Fails only this channel, for a message whose value it cannot represent. */
2018
+ fail(error, message) {
2019
+ if (this.readyState === WebSocket.OPEN) this.connection.send(this.id, create(ClientFrameSchema, { body: {
2020
+ case: "detach",
2021
+ value: {}
2022
+ } }).body);
2023
+ this.events.dispatchEvent(new MessageEvent("message", { data: {
2024
+ type: "error",
2025
+ error,
2026
+ message
2027
+ } }));
2028
+ this.finish();
2029
+ }
2030
+ finish(reason) {
2031
+ if (this.readyState === WebSocket.CLOSED) return;
2032
+ if (reason) this.events.dispatchEvent(new MessageEvent("message", { data: {
2033
+ type: "error",
2034
+ error: "connection_closed",
2035
+ message: String(reason)
2036
+ } }));
2037
+ this.readyState = WebSocket.CLOSED;
2038
+ this.creditChanged?.();
2039
+ this.connection.remove(this.id);
2040
+ this.events.dispatchEvent(new Event("close"));
2041
+ }
2042
+ };
2043
+ //#endregion
2044
+ //#region src/sandbox-process.ts
1677
2045
  /** @deprecated Use Sandbox.run() and Sandbox.attach(). Removed in the next version. */
1678
2046
  var SandboxProcesses = class {
1679
2047
  _sandbox;
2048
+ _disconnect;
1680
2049
  /** @internal */
1681
- constructor(_sandbox) {
2050
+ constructor(_sandbox, _disconnect) {
1682
2051
  this._sandbox = _sandbox;
2052
+ this._disconnect = _disconnect;
1683
2053
  }
1684
2054
  /** @deprecated Use sandbox.run(). Removed in the next version. */
1685
2055
  start(command, options = {}) {
@@ -1689,51 +2059,82 @@ var SandboxProcesses = class {
1689
2059
  connect(processId, options = {}) {
1690
2060
  return this._sandbox.attach(processId, options);
1691
2061
  }
2062
+ /** Disconnect process transport without terminating guest processes. */
2063
+ async disconnect() {
2064
+ this._disconnect();
2065
+ }
1692
2066
  };
1693
2067
  var SandboxProcess = class {
2068
+ _collectOutput;
2069
+ _buffer;
2070
+ _openConnection;
2071
+ _controlProcess;
1694
2072
  status = "running";
1695
2073
  stdout = "";
1696
2074
  stderr = "";
1697
2075
  _id;
1698
2076
  _cursor;
1699
- _onOutput;
1700
- _collectOutput;
1701
- _connectionEndpoint;
1702
- _controlProcess;
2077
+ _deliveredCursor;
1703
2078
  _stdoutDecoder = new TextDecoder();
1704
2079
  _stderrDecoder = new TextDecoder();
1705
- _terminal;
1706
- _resolveTerminal;
1707
- _result;
1708
2080
  _socket;
1709
- _connectionClosed;
1710
- _connectionError;
2081
+ _closed;
2082
+ _manual = false;
1711
2083
  _stdinClosed = false;
2084
+ _iteratorTaken = false;
2085
+ /** Settles once onOutput has handled the last chunk. */
2086
+ _delivered;
2087
+ _wake;
2088
+ _error;
2089
+ _exit;
2090
+ _result;
2091
+ /** Returns each buffered binary output's credit once the iterator takes it. */
2092
+ _releases = /* @__PURE__ */ new WeakMap();
2093
+ _resolveDone;
2094
+ _done = new Promise((resolve) => {
2095
+ this._resolveDone = resolve;
2096
+ });
2097
+ /** Pull output from the shared buffer. One iterator may consume each handle. */
2098
+ output = { [Symbol.asyncIterator]: () => {
2099
+ if (this._iteratorTaken) throw new Error("Process output already has a consumer: an output iterator or onOutput");
2100
+ this._iteratorTaken = true;
2101
+ return this._iterateOutput();
2102
+ } };
1712
2103
  /** @internal */
1713
- constructor(processId, cursor, onOutput, collectOutput, connectionEndpoint, controlProcess) {
2104
+ constructor(processId, cursor, _collectOutput, _buffer, _openConnection, _controlProcess) {
2105
+ this._collectOutput = _collectOutput;
2106
+ this._buffer = _buffer;
2107
+ this._openConnection = _openConnection;
2108
+ this._controlProcess = _controlProcess;
1714
2109
  this._id = processId;
1715
2110
  this._cursor = cursor;
1716
- this._onOutput = onOutput;
1717
- this._collectOutput = collectOutput;
1718
- this._connectionEndpoint = connectionEndpoint;
1719
- this._controlProcess = controlProcess;
1720
- this._terminal = new Promise((resolve) => {
1721
- this._resolveTerminal = resolve;
1722
- });
2111
+ this._deliveredCursor = cursor;
1723
2112
  }
1724
2113
  get id() {
1725
2114
  return this._id;
1726
2115
  }
2116
+ /** Next byte after output accepted into the SDK buffer. */
1727
2117
  get cursor() {
1728
2118
  return this._cursor;
1729
2119
  }
1730
2120
  get connected() {
1731
2121
  return this._socket?.readyState === WebSocket.OPEN;
1732
2122
  }
2123
+ /** Resolves once the runtime has accepted the input; waits while the process is not reading. */
1733
2124
  async sendInput(data) {
1734
2125
  if (this._stdinClosed) throw new Error("Process stdin is closed");
1735
2126
  const bytes = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
1736
- this._sendInput(bytes);
2127
+ await this._openSocket().send(bytes);
2128
+ }
2129
+ async closeStdin() {
2130
+ if (this._stdinClosed) return;
2131
+ this._stdinClosed = true;
2132
+ try {
2133
+ await this._openSocket().closeStdin();
2134
+ } catch (error) {
2135
+ this._stdinClosed = false;
2136
+ throw error;
2137
+ }
1737
2138
  }
1738
2139
  async resize(size) {
1739
2140
  if (this.status !== "running") throw new Error("Process has exited");
@@ -1743,146 +2144,178 @@ var SandboxProcess = class {
1743
2144
  ...size
1744
2145
  });
1745
2146
  }
1746
- /** Close stdin. Piped processes only. */
1747
- async closeStdin() {
1748
- if (this._stdinClosed) return;
1749
- this._sendControl({ type: "close_stdin" });
1750
- this._stdinClosed = true;
2147
+ async kill() {
2148
+ if (!this._exit) await this._controlProcess({
2149
+ type: "kill",
2150
+ process_id: this._id
2151
+ });
1751
2152
  }
1752
- /** Close this client connection without terminating the process. */
1753
2153
  async disconnect() {
1754
- const socket = this._socket;
1755
- const closed = this._connectionClosed;
1756
- if (!socket) return;
1757
- this._socket = void 0;
1758
- socket.close();
1759
- await closed;
2154
+ this._manual = true;
2155
+ this._socket?.close();
2156
+ await this._closed;
2157
+ if (!this._exit) this._fail(/* @__PURE__ */ new Error("Process is disconnected"));
1760
2158
  }
1761
2159
  async wait() {
1762
- if (this._result) return this._result;
1763
- const closed = this._connectionClosed;
1764
- if (!closed) throw new Error("Process is disconnected");
1765
- await Promise.race([this._terminal, closed]);
1766
- if (this._result) return this._result;
1767
- if (this._connectionError) throw this._connectionError;
1768
- throw new Error("Process connection closed before exit");
2160
+ if (!this._iteratorTaken) for await (const _output of this.output);
2161
+ await this._delivered;
2162
+ await this._done;
2163
+ if (this._error) throw this._error;
2164
+ return this._result;
2165
+ }
2166
+ /** @internal Feeds `output` to `handler`, waiting for each call to settle. */
2167
+ _deliverTo(handler) {
2168
+ const iterator = this.output[Symbol.asyncIterator]();
2169
+ this._delivered = (async () => {
2170
+ try {
2171
+ for (let next = await iterator.next(); !next.done; next = await iterator.next()) await handler(next.value);
2172
+ } catch (error) {
2173
+ this._fail(error);
2174
+ await iterator.return?.(void 0);
2175
+ if (!this._exit) await this.disconnect();
2176
+ }
2177
+ })();
1769
2178
  }
1770
- async kill() {
1771
- if (this._result) return;
1772
- await this._controlProcess({
1773
- type: "kill",
1774
- process_id: this._id
1775
- });
2179
+ async *_iterateOutput() {
2180
+ try {
2181
+ while (true) {
2182
+ const output = this._buffer.take(this);
2183
+ if (output) {
2184
+ this._releases.get(output)?.();
2185
+ this._deliveredCursor = output.offset + output.data.length;
2186
+ if (this._collectOutput) this._appendText(output.stream, (output.stream === "stdout" ? this._stdoutDecoder : this._stderrDecoder).decode(output.data, { stream: true }));
2187
+ this._complete();
2188
+ yield output;
2189
+ } else {
2190
+ this._complete();
2191
+ if (this._error) throw this._error;
2192
+ if (this._exit) return;
2193
+ await new Promise((resolve) => {
2194
+ this._wake = resolve;
2195
+ });
2196
+ this._wake = void 0;
2197
+ }
2198
+ }
2199
+ } finally {
2200
+ if (!this._exit && !this._error) await this.disconnect();
2201
+ this._buffer.discard(this);
2202
+ this._cursor = this._deliveredCursor;
2203
+ this._complete();
2204
+ }
1776
2205
  }
1777
2206
  /** @internal */
1778
2207
  async _connect(request) {
1779
- const socket = await openProcessSocket(this._connectionEndpoint);
1780
- socket.binaryType = "arraybuffer";
2208
+ const socket = await this._openConnection();
2209
+ if (this._manual) {
2210
+ socket.close();
2211
+ throw new Error("Process is disconnected");
2212
+ }
1781
2213
  this._socket = socket;
1782
- let resolveClosed;
1783
- this._connectionClosed = new Promise((resolve) => {
1784
- resolveClosed = resolve;
2214
+ let closed;
2215
+ this._closed = new Promise((resolve) => {
2216
+ closed = resolve;
1785
2217
  });
2218
+ const expected = request.type === "start" ? "started" : "attached";
2219
+ let settled = false;
1786
2220
  let resolveReady;
1787
2221
  let rejectReady;
1788
- let readySettled = false;
1789
2222
  const ready = new Promise((resolve, reject) => {
1790
- resolveReady = () => {
1791
- readySettled = true;
1792
- resolve();
1793
- };
1794
- rejectReady = (error) => {
1795
- readySettled = true;
1796
- reject(error);
1797
- };
2223
+ resolveReady = resolve;
2224
+ rejectReady = reject;
1798
2225
  });
1799
- const expectedReady = request.type === "start" ? "started" : "attached";
1800
- const fail = (error) => {
1801
- if (!readySettled) rejectReady(error instanceof Error ? error : new Error(String(error)));
1802
- };
1803
2226
  socket.addEventListener("message", (message) => {
1804
- let output;
2227
+ if (this._socket !== socket) return;
1805
2228
  try {
1806
- output = this._handleMessage(message.data, expectedReady, resolveReady);
2229
+ const data = message.data;
2230
+ if ("stream" in data) {
2231
+ this._enqueueOutput(data.data, data.offset, data.stream, () => socket.release(data.cost));
2232
+ return;
2233
+ }
2234
+ const event = data;
2235
+ switch (event.type) {
2236
+ case "started":
2237
+ case "attached":
2238
+ if (event.type !== expected || this._id && this._id !== event.process_id) throw new Error("Unexpected process identity");
2239
+ this._id = event.process_id;
2240
+ settled = true;
2241
+ resolveReady();
2242
+ break;
2243
+ case "exit":
2244
+ this._exit = event;
2245
+ this.status = event.status;
2246
+ this._stdinClosed = true;
2247
+ this._complete();
2248
+ this._wake?.();
2249
+ break;
2250
+ case "error": throw new Error(`${event.error}: ${event.message}`);
2251
+ }
1807
2252
  } catch (error) {
1808
- const connectionError = error instanceof Error ? error : new Error(String(error));
1809
- this._connectionError = connectionError;
1810
- fail(connectionError);
2253
+ const failure = error instanceof Error ? error : new Error(String(error));
2254
+ if (!settled) rejectReady(failure);
2255
+ this._fail(failure);
1811
2256
  socket.close();
1812
- return;
1813
2257
  }
1814
- if (output) this._onOutput?.(output);
1815
2258
  });
1816
2259
  socket.addEventListener("error", () => {
1817
2260
  const error = /* @__PURE__ */ new Error("Process connection failed");
1818
- this._connectionError = error;
1819
- fail(error);
2261
+ if (!settled) rejectReady(error);
2262
+ this._fail(error);
1820
2263
  });
1821
- socket.addEventListener("close", (event) => {
1822
- const reason = CLOSE_REASONS[event.code];
1823
- if (reason && !this._result) this._connectionError = new Error(reason);
2264
+ socket.addEventListener("close", () => {
1824
2265
  if (this._socket === socket) this._socket = void 0;
1825
- if (!readySettled) rejectReady(/* @__PURE__ */ new Error("Process connection closed before ready"));
1826
- resolveClosed();
2266
+ closed();
2267
+ if (!settled) rejectReady(/* @__PURE__ */ new Error("Process connection closed before ready"));
2268
+ if (!this._exit && !this._manual) this._fail(/* @__PURE__ */ new Error("Process connection closed before exit"));
1827
2269
  }, { once: true });
1828
- socket.send(JSON.stringify(request));
2270
+ try {
2271
+ socket.sendRequest(request);
2272
+ } catch (error) {
2273
+ rejectReady(error instanceof Error ? error : new Error(String(error)));
2274
+ this._fail(error);
2275
+ socket.close();
2276
+ }
1829
2277
  await ready;
1830
2278
  }
1831
2279
  _openSocket() {
1832
2280
  if (this.status !== "running") throw new Error("Process has exited");
1833
- if (!this._socket || this._socket.readyState !== WebSocket.OPEN) throw new Error("Process is disconnected");
2281
+ if (!this.connected) throw new Error("Process is disconnected");
1834
2282
  return this._socket;
1835
2283
  }
1836
- _sendControl(message) {
1837
- this._openSocket().send(JSON.stringify(message));
2284
+ _fail(error) {
2285
+ this._error ??= error instanceof Error ? error : new Error(String(error));
2286
+ this._resolveDone();
2287
+ this._wake?.();
1838
2288
  }
1839
- _sendInput(data) {
1840
- const socket = this._openSocket();
1841
- for (let offset = 0; offset < data.byteLength; offset += PROCESS_STDIN_CHUNK_BYTES) {
1842
- const chunk = new Uint8Array(Math.min(PROCESS_STDIN_CHUNK_BYTES, data.byteLength - offset));
1843
- chunk.set(data.subarray(offset, offset + chunk.byteLength));
1844
- socket.send(chunk);
1845
- }
1846
- }
1847
- _handleMessage(data, expectedReady, ready) {
1848
- if (typeof data !== "string") return this._handleOutput(data);
1849
- const event = JSON.parse(data);
1850
- switch (event.type) {
1851
- case "started":
1852
- case "attached":
1853
- if (event.type !== expectedReady) throw new Error(`Expected ${expectedReady}, received ${event.type}`);
1854
- if (this._id && this._id !== event.process_id) throw new Error("Runtime returned a different process ID");
1855
- this._id = event.process_id;
1856
- ready();
1857
- return;
1858
- case "exit":
1859
- this._finish(event);
1860
- return;
1861
- case "error": throw /* @__PURE__ */ new Error(`${event.error}: ${event.message}`);
1862
- }
2289
+ _complete() {
2290
+ if (!this._exit || this._buffer.has(this) || this._result) return;
2291
+ this._flushDecoders();
2292
+ this._result = {
2293
+ status: this._exit.status,
2294
+ exitCode: this._exit.exit_code ?? void 0,
2295
+ exitReason: this._exit.exit_reason ?? void 0,
2296
+ stdout: this.stdout,
2297
+ stderr: this.stderr
2298
+ };
2299
+ this._resolveDone();
1863
2300
  }
1864
- _handleOutput(data) {
1865
- const bytes = new Uint8Array(data);
1866
- if (bytes.byteLength < 9 || bytes[0] !== 1 && bytes[0] !== 2) throw new Error("Invalid process output frame");
1867
- const offset = Number(new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getBigUint64(1));
1868
- const payload = bytes.subarray(9);
2301
+ /** `release` returns the output's flow-control credit once it is consumed. */
2302
+ _enqueueOutput(payload, offset, stream, release) {
1869
2303
  const end = offset + payload.byteLength;
1870
- if (end <= this._cursor) return;
1871
- if (offset > this._cursor) {
1872
- this._flushDecoders();
1873
- this._cursor = offset;
2304
+ if (end <= this._cursor) {
2305
+ release();
2306
+ return;
1874
2307
  }
1875
- const skip = Math.max(0, this._cursor - offset);
1876
- const unread = payload.subarray(skip);
1877
- const unreadOffset = offset + skip;
1878
- this._cursor = end;
1879
- const stream = bytes[0] === 1 ? "stdout" : "stderr";
1880
- if (this._collectOutput) this._appendText(stream, (stream === "stdout" ? this._stdoutDecoder : this._stderrDecoder).decode(unread, { stream: true }));
1881
- return {
2308
+ if (offset > this._cursor) throw new Error(`Process output gap: expected offset ${this._cursor}, received ${offset}`);
2309
+ const skip = this._cursor - offset;
2310
+ const output = {
1882
2311
  stream,
1883
- offset: unreadOffset,
1884
- data: unread
2312
+ offset: this._cursor,
2313
+ data: payload.slice(skip)
1885
2314
  };
2315
+ this._buffer.push(this, output);
2316
+ this._releases.set(output, release);
2317
+ this._cursor = end;
2318
+ this._wake?.();
1886
2319
  }
1887
2320
  _appendText(stream, data) {
1888
2321
  if (stream === "stdout") this.stdout += data;
@@ -1893,21 +2326,6 @@ var SandboxProcess = class {
1893
2326
  this._appendText("stdout", this._stdoutDecoder.decode());
1894
2327
  this._appendText("stderr", this._stderrDecoder.decode());
1895
2328
  }
1896
- _finish(event) {
1897
- if (this._result) return;
1898
- this.status = event.status;
1899
- this._stdinClosed = true;
1900
- this._flushDecoders();
1901
- this._cursor = Math.max(this._cursor, event.cursor);
1902
- this._result = {
1903
- status: event.status,
1904
- exitCode: event.exit_code ?? void 0,
1905
- exitReason: event.exit_reason ?? void 0,
1906
- stdout: this.stdout,
1907
- stderr: this.stderr
1908
- };
1909
- this._resolveTerminal(this._result);
1910
- }
1911
2329
  };
1912
2330
  //#endregion
1913
2331
  //#region src/sandbox-files.ts
@@ -1931,32 +2349,15 @@ while IFS= read -r count; do
1931
2349
  [ "$size" -eq "$count" ] || break
1932
2350
  done`;
1933
2351
  var ProcessOutputReader = class {
1934
- onOutput = (output) => {
1935
- if (output.offset !== this._cursor) {
1936
- this._push(/* @__PURE__ */ new Error(`Sandbox process output gap: expected offset ${this._cursor}, received ${output.offset}`));
1937
- return;
1938
- }
1939
- this._cursor += output.data.byteLength;
1940
- if (output.stream === "stdout") this._push(output.data);
1941
- else this._stderr += this._stderrDecoder.decode(output.data, { stream: true });
1942
- };
1943
2352
  _buffer = /* @__PURE__ */ new Uint8Array();
1944
2353
  _cursor = 0;
1945
- _chunks = [];
1946
2354
  _stderrDecoder = new TextDecoder();
1947
2355
  _stderr = "";
1948
- _waiting;
1949
- _exit;
2356
+ _process;
2357
+ _output;
1950
2358
  attach(process) {
1951
- this._exit = process.wait();
1952
- this._exit.then((result) => {
1953
- try {
1954
- assertSuccessful(result, this._stderrText());
1955
- this._push(/* @__PURE__ */ new Error("Sandbox process exited before file transfer completed"));
1956
- } catch (error) {
1957
- this._push(toError(error));
1958
- }
1959
- }, (error) => this._push(toError(error)));
2359
+ this._process = process;
2360
+ this._output = process.output[Symbol.asyncIterator]();
1960
2361
  }
1961
2362
  async readLine() {
1962
2363
  while (true) {
@@ -1970,32 +2371,28 @@ var ProcessOutputReader = class {
1970
2371
  }
1971
2372
  }
1972
2373
  async read(size) {
1973
- while (this._buffer.byteLength < size) this._buffer = concat(this._buffer, await this._nextChunk());
2374
+ while (this._buffer.length < size) this._buffer = concat(this._buffer, await this._nextChunk());
1974
2375
  const data = this._buffer.slice(0, size);
1975
2376
  this._buffer = this._buffer.slice(size);
1976
2377
  return data;
1977
2378
  }
1978
2379
  async wait() {
1979
- if (!this._exit) throw new Error("File transfer process has not started");
1980
- assertSuccessful(await this._exit, this._stderrText());
1981
- }
1982
- _stderrText() {
1983
- this._stderr += this._stderrDecoder.decode();
1984
- return this._stderr;
1985
- }
1986
- _push(value) {
1987
- const waiting = this._waiting;
1988
- if (waiting) {
1989
- this._waiting = void 0;
1990
- waiting(value);
1991
- } else this._chunks.push(value);
2380
+ while (!(await this._output.next()).done);
2381
+ assertSuccessful(await this._process.wait(), this._stderr + this._stderrDecoder.decode());
1992
2382
  }
1993
2383
  async _nextChunk() {
1994
- const value = this._chunks.shift() ?? await new Promise((resolve) => {
1995
- this._waiting = resolve;
1996
- });
1997
- if (value instanceof Error) throw value;
1998
- return value;
2384
+ while (true) {
2385
+ const next = await this._output.next();
2386
+ if (next.done) {
2387
+ assertSuccessful(await this._process.wait(), this._stderr + this._stderrDecoder.decode());
2388
+ throw new Error("Sandbox process exited before file transfer completed");
2389
+ }
2390
+ const output = next.value;
2391
+ if (output.offset !== this._cursor) throw new Error(`Sandbox process output gap: expected offset ${this._cursor}, received ${output.offset}`);
2392
+ this._cursor += output.data.length;
2393
+ if (output.stream === "stdout") return output.data;
2394
+ this._stderr += this._stderrDecoder.decode(output.data, { stream: true });
2395
+ }
1999
2396
  }
2000
2397
  };
2001
2398
  var SandboxFiles = class {
@@ -2037,7 +2434,6 @@ var SandboxFiles = class {
2037
2434
  ARCHIL_FILE_PATH: path,
2038
2435
  ARCHIL_FILE_TEMP: `/tmp/.archil-download-${transferId()}`
2039
2436
  },
2040
- onOutput: reader.onOutput,
2041
2437
  collectOutput: false
2042
2438
  });
2043
2439
  reader.attach(process);
@@ -2160,6 +2556,7 @@ function sleep() {
2160
2556
  var Sandbox = class Sandbox {
2161
2557
  id;
2162
2558
  name;
2559
+ labels;
2163
2560
  status;
2164
2561
  vcpuCount;
2165
2562
  memSizeMiB;
@@ -2168,6 +2565,7 @@ var Sandbox = class Sandbox {
2168
2565
  platform;
2169
2566
  maxTtlSeconds;
2170
2567
  idleTtlSeconds;
2568
+ onTimeout;
2171
2569
  maxConcurrentExecs;
2172
2570
  endpoints;
2173
2571
  mounts;
@@ -2182,17 +2580,21 @@ var Sandbox = class Sandbox {
2182
2580
  files;
2183
2581
  /** @internal */
2184
2582
  _client;
2583
+ _processConnection;
2584
+ _processOutput = new ProcessOutputBuffer();
2185
2585
  /** @internal */
2186
2586
  constructor(data, client) {
2187
2587
  this._client = client;
2188
2588
  this._apply(data);
2189
- this.processes = new SandboxProcesses(this);
2589
+ this._processConnection = new ProcessConnection(() => this._connectionEndpoint());
2590
+ this.processes = new SandboxProcesses(this, () => this._processConnection.disconnect());
2190
2591
  this.files = new SandboxFiles(this);
2191
2592
  }
2192
2593
  /** @internal Overwrite this sandbox's fields in place from a fresh wire snapshot. */
2193
2594
  _apply(data) {
2194
2595
  this.id = data.sandbox_id;
2195
2596
  this.name = data.name;
2597
+ this.labels = { ...data.labels };
2196
2598
  this.status = data.status;
2197
2599
  this.vcpuCount = data.vcpu_count;
2198
2600
  this.memSizeMiB = data.mem_size_mib;
@@ -2201,6 +2603,7 @@ var Sandbox = class Sandbox {
2201
2603
  this.platform = data.platform;
2202
2604
  this.maxTtlSeconds = data.max_ttl_seconds;
2203
2605
  this.idleTtlSeconds = data.idle_ttl_seconds ?? 0;
2606
+ this.onTimeout = data.on_timeout ?? "pause";
2204
2607
  this.maxConcurrentExecs = data.max_concurrent_execs;
2205
2608
  this.endpoints = data.endpoints?.map((endpoint) => ({ ...endpoint }));
2206
2609
  this.mounts = (data.mounts ?? []).map(sandboxMountFromWire);
@@ -2216,6 +2619,7 @@ var Sandbox = class Sandbox {
2216
2619
  return {
2217
2620
  id: this.id,
2218
2621
  name: this.name,
2622
+ labels: { ...this.labels },
2219
2623
  status: this.status,
2220
2624
  vcpuCount: this.vcpuCount,
2221
2625
  memSizeMiB: this.memSizeMiB,
@@ -2224,6 +2628,7 @@ var Sandbox = class Sandbox {
2224
2628
  platform: this.platform,
2225
2629
  maxTtlSeconds: this.maxTtlSeconds,
2226
2630
  idleTtlSeconds: this.idleTtlSeconds,
2631
+ onTimeout: this.onTimeout,
2227
2632
  maxConcurrentExecs: this.maxConcurrentExecs,
2228
2633
  endpoints: this.endpoints?.map((endpoint) => ({ ...endpoint })),
2229
2634
  mounts: this.mounts.map((mount) => ({ ...mount })),
@@ -2237,7 +2642,7 @@ var Sandbox = class Sandbox {
2237
2642
  }
2238
2643
  /** Start a process and return its handle without waiting for exit. */
2239
2644
  async run(command, options = {}) {
2240
- const process = new SandboxProcess("", 0, options.onOutput, options.collectOutput ?? true, () => this._connectionEndpoint(), (request) => this._control(request));
2645
+ const process = new SandboxProcess("", 0, options.collectOutput ?? true, this._processOutput, () => this._processConnection.open(), (request) => this._control(request));
2241
2646
  const terminal = typeof options.terminal === "object" ? {
2242
2647
  cols: options.terminal.cols ?? 80,
2243
2648
  rows: options.terminal.rows ?? 24
@@ -2250,35 +2655,36 @@ var Sandbox = class Sandbox {
2250
2655
  env: options.env ?? {},
2251
2656
  timeout_seconds: options.timeoutSeconds
2252
2657
  });
2658
+ if (options.onOutput) process._deliverTo(options.onOutput);
2253
2659
  return process;
2254
2660
  }
2255
2661
  /** Reattach to a process, optionally resuming output from a cursor. */
2256
2662
  async attach(processId, options = {}) {
2257
2663
  const offset = options.offset ?? 0;
2258
- const process = new SandboxProcess(processId, offset, options.onOutput, options.collectOutput ?? true, () => this._connectionEndpoint(), (request) => this._control(request));
2664
+ const process = new SandboxProcess(processId, offset, options.collectOutput ?? true, this._processOutput, () => this._processConnection.open(), (request) => this._control(request));
2259
2665
  await process._connect({
2260
2666
  type: "attach",
2261
2667
  process_id: processId,
2262
2668
  offset,
2263
2669
  ...options.shared ? { shared: true } : {}
2264
2670
  });
2671
+ if (options.onOutput) process._deliverTo(options.onOutput);
2265
2672
  return process;
2266
2673
  }
2267
2674
  async _connectionEndpoint() {
2268
2675
  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 {
2676
+ return {
2270
2677
  url: data.endpoint,
2271
- protocols: [CONNECT_SUBPROTOCOL, `${TOKEN_SUBPROTOCOL_PREFIX}${data.token}`]
2678
+ token: data.token
2272
2679
  };
2273
- return { url: data.url };
2274
2680
  }
2275
2681
  async _control(request) {
2276
- const socket = await openProcessSocket(() => this._connectionEndpoint());
2682
+ const socket = await this._processConnection.open();
2277
2683
  const expected = request.type === "kill" ? "killed" : "resized";
2278
2684
  await new Promise((resolve, reject) => {
2279
2685
  socket.addEventListener("message", (message) => {
2280
2686
  try {
2281
- const event = JSON.parse(message.data);
2687
+ const event = message.data;
2282
2688
  if (event.type === "error") reject(/* @__PURE__ */ new Error(`${event.error}: ${event.message}`));
2283
2689
  else if (event.type !== expected) reject(/* @__PURE__ */ new Error(`Expected ${expected}, received ${event.type}`));
2284
2690
  else resolve();
@@ -2290,7 +2696,12 @@ var Sandbox = class Sandbox {
2290
2696
  }, { once: true });
2291
2697
  socket.addEventListener("error", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} request failed`)));
2292
2698
  socket.addEventListener("close", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} connection closed before confirmation`)));
2293
- socket.send(JSON.stringify(request));
2699
+ try {
2700
+ socket.sendRequest(request);
2701
+ } catch (error) {
2702
+ reject(error);
2703
+ socket.finish();
2704
+ }
2294
2705
  });
2295
2706
  }
2296
2707
  /** Run a process and wait for it to exit. */
@@ -2355,7 +2766,8 @@ var Sandbox = class Sandbox {
2355
2766
  const wait = resumeAfterFork ? false : options.wait ?? true;
2356
2767
  const body = {
2357
2768
  name: options.name,
2358
- checkpoint
2769
+ checkpoint,
2770
+ labels: options.labels
2359
2771
  };
2360
2772
  const fork = await waitWhileSandboxStatus(this, "pausing").then(() => unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/fork", {
2361
2773
  params: {
@@ -2494,6 +2906,11 @@ async function waitWhileSandboxStatus(sandbox, status) {
2494
2906
  }
2495
2907
  //#endregion
2496
2908
  //#region src/sandboxes.ts
2909
+ /** Server-side maximum page size for `GET /api/sandboxes`. */
2910
+ const SANDBOX_PAGE_LIMIT = 100;
2911
+ function matchesListFilters(sandbox, options) {
2912
+ return Object.entries(options.labels ?? {}).every(([key, value]) => sandbox.labels?.[key] === value) && (options.name === void 0 || sandbox.name === options.name) && sandbox.name.startsWith(options.namePrefix ?? "");
2913
+ }
2497
2914
  var Sandboxes = class {
2498
2915
  /** @internal */
2499
2916
  _client;
@@ -2501,10 +2918,29 @@ var Sandboxes = class {
2501
2918
  constructor(client) {
2502
2919
  this._client = client;
2503
2920
  }
2504
- /** List the account's sandboxes, oldest first. */
2921
+ /**
2922
+ * List the account's sandboxes, oldest first, keeping those that match every
2923
+ * filter given. Follows the server's pages until none remain.
2924
+ */
2505
2925
  async list(options = {}) {
2506
2926
  const filesystem = typeof options.disk === "string" ? options.disk : options.disk?.id;
2507
- return ((await unwrap(retryApiRequest(() => this._client.GET("/api/sandboxes", { params: { query: { filesystem } } }), "transient")))?.sandboxes ?? []).map((sandbox) => new Sandbox(sandbox, this._client));
2927
+ const labels = Object.entries(options.labels ?? {}).map(([key, value]) => `${key}=${value}`);
2928
+ const client = this._client;
2929
+ const sandboxes = [];
2930
+ let cursor;
2931
+ for (;;) {
2932
+ const { data, nextCursor } = await unwrapPage(retryApiRequest(() => client.GET("/api/sandboxes", { params: { query: {
2933
+ filesystem,
2934
+ label: labels.length > 0 ? labels : void 0,
2935
+ name: options.name,
2936
+ name_prefix: options.namePrefix,
2937
+ limit: SANDBOX_PAGE_LIMIT,
2938
+ cursor
2939
+ } } }), "transient"));
2940
+ for (const sandbox of data?.sandboxes ?? []) if (matchesListFilters(sandbox, options)) sandboxes.push(new Sandbox(sandbox, this._client));
2941
+ if (!nextCursor || nextCursor === cursor) return sandboxes;
2942
+ cursor = nextCursor;
2943
+ }
2508
2944
  }
2509
2945
  async get(id) {
2510
2946
  return new Sandbox(await unwrap(retryApiRequest(() => this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: id } } }), "transient")), this._client);
@@ -2519,10 +2955,12 @@ var Sandboxes = class {
2519
2955
  env: request.env,
2520
2956
  max_ttl_seconds: request.maxTtlSeconds,
2521
2957
  idle_ttl_seconds: request.idleTtlSeconds,
2958
+ on_timeout: request.onTimeout,
2522
2959
  max_concurrent_execs: request.maxConcurrentExecs,
2523
2960
  network: request.network,
2524
2961
  ports: request.ports,
2525
- ...request.mounts !== void 0 && { mounts: request.mounts.map(sandboxMountWire) }
2962
+ ...request.mounts !== void 0 && { mounts: request.mounts.map(sandboxMountWire) },
2963
+ labels: request.labels
2526
2964
  };
2527
2965
  const sandbox = new Sandbox(await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes", {
2528
2966
  params: { query: { wait: options.wait ?? true } },