disk 1.1.2 → 1.3.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/README.md CHANGED
@@ -151,6 +151,58 @@ const all = await client.sandboxes.list();
151
151
  const usingDisk = await client.sandboxes.list({ disk: "dsk-abc123" });
152
152
  ```
153
153
 
154
+ Expose TCP ports publicly when creating a sandbox or later with `exposePort`:
155
+
156
+ ```ts
157
+ const web = await client.sandboxes.create({ baseImage: "python:3.12-slim", ports: [8080] });
158
+ const server = await web.processes.start("python -m http.server 8080 --bind 0.0.0.0");
159
+ await server.disconnect(); // The server keeps running.
160
+
161
+ const hostname = await web.exposePort(8080); // Returns the hostname, including if already public.
162
+ console.log(`https://${hostname}`); // Available once the server is listening.
163
+ console.log(await web.listPorts()); // [{ port: 8080, hostname: "..." }]
164
+ await web.unexposePort(8080);
165
+ ```
166
+
167
+ Ports must be between 1 and 65535. Exposing a port makes it publicly accessible
168
+ without authentication; your application must listen on that port. HTTP services
169
+ are reached through HTTPS on the returned hostname.
170
+ `listPorts()` returns only explicitly exposed ports; `sandbox.endpoints` contains
171
+ service-published ports. Deleting explicit exposure leaves a service publishing
172
+ the same port reachable and does not stop the listening process. Routing changes
173
+ may take a few seconds to propagate, and existing connections remain open.
174
+
175
+ `fork` pauses a running sandbox while the snapshot is taken and resumes it once the
176
+ fork is accepted. A paused or stopped sandbox is forked in place and left as it is.
177
+
178
+ For private HTTP access, create a port token without exposing the port publicly:
179
+
180
+ ```ts
181
+ const privateWeb = await client.sandboxes.create({ baseImage: "python:3.12-slim" });
182
+ const server = await privateWeb.processes.start("python -m http.server 8080 --bind 0.0.0.0");
183
+ await server.disconnect();
184
+
185
+ const access = await privateWeb.createPortToken(8080, { ttl: "1h" });
186
+ // Once the server is listening:
187
+ const response = await fetch(`https://${access.hostname}/`, {
188
+ headers: { "X-Archil-Token": access.token },
189
+ });
190
+ console.log(await response.text());
191
+
192
+ const metadata = await privateWeb.getPortToken(access.id);
193
+ const tokens = await privateWeb.listPortTokens();
194
+ const page = await privateWeb.listPortTokensPage({ limit: 10 });
195
+ await privateWeb.deletePortToken(access);
196
+ await privateWeb.delete();
197
+ ```
198
+
199
+ The secret and hostname are returned only by `createPortToken`; get/list return
200
+ metadata. Save the secret when creating it. Omit `ttl` for no expiration, or use
201
+ a duration up to `"8760h"` (365 days). `listPortTokens` follows all pages (its
202
+ `limit` caps the total); `listPortTokensPage` returns `nextCursor` for pagination.
203
+ Public ports bypass token authentication. Revocation and expiry deny new
204
+ connections with HTTP 401; existing connections remain open.
205
+
154
206
  Network egress can optionally be restricted when creating a sandbox:
155
207
 
156
208
  ```ts
@@ -194,8 +246,31 @@ console.log(effective, await restricted.getNetwork());
194
246
  await restricted.updateNetwork({}); // Restore unrestricted egress.
195
247
  ```
196
248
 
249
+ Set hard and idle TTLs at creation or edit them while running. All values are
250
+ seconds, matching the Python SDK:
251
+
252
+ ```ts
253
+ const timed = await archil.sandboxes.create({ maxTtlSeconds: 3600, idleTtlSeconds: 300 });
254
+ await timed.setTimeout(7200);
255
+ await timed.setTimeout({ idleTtlSeconds: 60 });
256
+ await timed.setTimeout({ timeoutSeconds: 3600, idleTtlSeconds: 300 });
257
+ await timed.setTimeout({ idleTtlSeconds: 0 });
258
+ console.log(timed.maxTtlSeconds, timed.idleTtlSeconds);
259
+ ```
260
+
261
+ Omitted settings stay unchanged on edits. Updating the hard TTL resets its
262
+ deadline from now; an idle-only edit does not. Changes made while inactive apply
263
+ to the next powered-on session. Idle TTL accepts 0–86,400 seconds; omitted or
264
+ zero at creation disables it, and zero on edits disables it again.
265
+
266
+ Both TTLs pause the sandbox, preserving memory and processes. Open direct
267
+ process connections prevent idle expiry, but not hard expiry. The idle countdown
268
+ starts when the last connection closes; detached processes and service-port
269
+ traffic do not keep it alive. Disable idle TTL for unattended jobs.
270
+
197
271
  Sandboxes support 1–32 vCPUs and 256–65,536 MiB of memory. When omitted,
198
- `vcpuCount` defaults to 1 and `memSizeMiB` defaults to 2,048 MiB.
272
+ `vcpuCount` defaults to 1 and `memSizeMiB` defaults to 2,048 MiB. Sandbox
273
+ timeouts default to 24 hours and can be reset up to 24 hours from now.
199
274
 
200
275
  `sandbox.processes.start()` always returns a runtime-owned process immediately.
201
276
  Pass `terminal: true` when the command needs terminal behavior, or provide
package/dist/cli.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { O as ArchilApiError, a as deleteApiKey, l as listApiKeys, n as createApiKey, r as createDisk, s as getDisk, t as configure, u as listDisks } from "./src-DXNLDPID.mjs";
3
- import { a as renderTable, i as resolveProgramCredentials, n as addProfileCommands, r as isProfileCommand, t as addGlobalOptions } from "./common-DUyyWu2M.mjs";
2
+ import { O as ArchilApiError, a as deleteApiKey, l as listApiKeys, n as createApiKey, r as createDisk, s as getDisk, t as configure, u as listDisks } from "./src-CvTkHglv.mjs";
3
+ import { a as renderTable, i as resolveProgramCredentials, n as addProfileCommands, r as isProfileCommand, t as addGlobalOptions } from "./common-BFAzXgkJ.mjs";
4
4
  import { createRequire } from "node:module";
5
5
  import { Command } from "commander";
6
6
  //#region bin/cli.ts
@@ -1,4 +1,4 @@
1
- import { D as REGION_URLS, p as Archil } from "./src-DXNLDPID.mjs";
1
+ import { D as REGION_URLS, p as Archil } from "./src-CvTkHglv.mjs";
2
2
  import { Option } from "commander";
3
3
  import { isCancel, password, spinner } from "@clack/prompts";
4
4
  import { chmod, mkdir, open, readFile, rename, rm, stat } from "node:fs/promises";
@@ -1,6 +1,5 @@
1
1
  import { Client } from "openapi-fetch";
2
2
  import { components, paths } from "@archildata/api-types";
3
-
4
3
  //#region src/client.d.ts
5
4
  type ApiClient = Client<paths>;
6
5
  //#endregion
@@ -1,6 +1,5 @@
1
1
  import { Client } from "openapi-fetch";
2
2
  import { components, paths } from "@archildata/api-types";
3
-
4
3
  //#region src/client.d.ts
5
4
  type ApiClient = Client<paths>;
6
5
  //#endregion
package/dist/index.cjs CHANGED
@@ -145,7 +145,7 @@ function deriveS3BaseUrl(controlBaseUrl) {
145
145
  }
146
146
  //#endregion
147
147
  //#region src/version.ts
148
- const VERSION = "1.1.2";
148
+ const VERSION = "1.3.0";
149
149
  const USER_AGENT = `archil-js/${VERSION}`;
150
150
  //#endregion
151
151
  //#region src/client.ts
@@ -154,6 +154,49 @@ function isNodeRuntime() {
154
154
  return typeof process !== "undefined" && typeof process.versions?.node === "string";
155
155
  }
156
156
  const undiciModule = isNodeRuntime() ? import("undici") : void 0;
157
+ const CONTROL_PLANE_CONNECTIONS = 1;
158
+ const CONTROL_PLANE_CONCURRENT_STREAMS = 100;
159
+ function isAsyncIterableBody(body) {
160
+ return body != null && typeof body === "object" && Symbol.asyncIterator in body;
161
+ }
162
+ async function bufferBody(body) {
163
+ const chunks = [];
164
+ for await (const chunk of body) chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
165
+ return Buffer.concat(chunks);
166
+ }
167
+ const multiplexHttp2Requests = (dispatch) => (options, handler) => {
168
+ let requestStarted = false;
169
+ const guardedHandler = {
170
+ onRequestStart(controller, context) {
171
+ if (requestStarted) {
172
+ controller.abort(/* @__PURE__ */ new Error("Archil control-plane requests are not replayed after a connection failure"));
173
+ return;
174
+ }
175
+ requestStarted = true;
176
+ handler.onRequestStart?.(controller, context);
177
+ },
178
+ onRequestUpgrade: handler.onRequestUpgrade?.bind(handler),
179
+ onResponseStart: handler.onResponseStart?.bind(handler),
180
+ onResponseData: handler.onResponseData?.bind(handler),
181
+ onResponseEnd: handler.onResponseEnd?.bind(handler),
182
+ onResponseError: handler.onResponseError?.bind(handler)
183
+ };
184
+ const dispatchBody = (body) => dispatch({
185
+ ...options,
186
+ body,
187
+ idempotent: true
188
+ }, guardedHandler);
189
+ if (!isAsyncIterableBody(options.body)) return dispatchBody(options.body);
190
+ bufferBody(options.body).then(dispatchBody, (error) => handler.onResponseError?.({
191
+ aborted: false,
192
+ paused: false,
193
+ reason: null,
194
+ abort() {},
195
+ pause() {},
196
+ resume() {}
197
+ }, error instanceof Error ? error : new Error(String(error))));
198
+ return true;
199
+ };
157
200
  const sharedDispatchers = /* @__PURE__ */ new Map();
158
201
  function dispatcherKey(baseUrl, apiKey) {
159
202
  return `${new URL(baseUrl).origin}\0${apiKey}`;
@@ -167,10 +210,11 @@ function getSharedDispatcher(baseUrl, apiKey) {
167
210
  const { Agent } = await undiciModule;
168
211
  return new Agent({
169
212
  allowH2: true,
170
- connections: 100,
213
+ connections: CONTROL_PLANE_CONNECTIONS,
214
+ pipelining: CONTROL_PLANE_CONCURRENT_STREAMS,
171
215
  keepAliveTimeout: 6e4,
172
216
  keepAliveMaxTimeout: 6e5
173
- });
217
+ }).compose(multiplexHttp2Requests);
174
218
  })();
175
219
  sharedDispatchers.set(key, dispatcher);
176
220
  dispatcher.catch(() => {
@@ -1809,6 +1853,14 @@ function toError(error) {
1809
1853
  }
1810
1854
  //#endregion
1811
1855
  //#region src/sandbox.ts
1856
+ function portTokenFromWire(data) {
1857
+ return {
1858
+ id: data.id,
1859
+ port: data.port,
1860
+ createdAt: new Date(data.created_at),
1861
+ expiresAt: data.expires_at ? new Date(data.expires_at) : void 0
1862
+ };
1863
+ }
1812
1864
  const POLL_INTERVAL_MS = 500;
1813
1865
  function sleep() {
1814
1866
  return new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
@@ -1822,14 +1874,15 @@ var Sandbox = class Sandbox {
1822
1874
  baseImage;
1823
1875
  platform;
1824
1876
  maxTtlSeconds;
1877
+ idleTtlSeconds;
1825
1878
  maxConcurrentExecs;
1826
1879
  endpoints;
1827
1880
  createdAt;
1828
1881
  runningAt;
1829
1882
  finishedAt;
1830
1883
  lastActiveAt;
1831
- expiresAt;
1832
1884
  exitReason;
1885
+ checkpoint;
1833
1886
  processes;
1834
1887
  files;
1835
1888
  /** @internal */
@@ -1851,14 +1904,15 @@ var Sandbox = class Sandbox {
1851
1904
  this.baseImage = data.base_image;
1852
1905
  this.platform = data.platform;
1853
1906
  this.maxTtlSeconds = data.max_ttl_seconds;
1907
+ this.idleTtlSeconds = data.idle_ttl_seconds ?? 0;
1854
1908
  this.maxConcurrentExecs = data.max_concurrent_execs;
1855
1909
  this.endpoints = data.endpoints?.map((endpoint) => ({ ...endpoint }));
1856
1910
  this.createdAt = new Date(data.created_at);
1857
1911
  this.runningAt = data.running_at ? new Date(data.running_at) : void 0;
1858
1912
  this.finishedAt = data.finished_at ? new Date(data.finished_at) : void 0;
1859
1913
  this.lastActiveAt = new Date(data.last_active_at);
1860
- this.expiresAt = data.expires_at ? new Date(data.expires_at) : void 0;
1861
1914
  this.exitReason = data.exit_reason;
1915
+ this.checkpoint = data.checkpoint;
1862
1916
  return this;
1863
1917
  }
1864
1918
  toJSON() {
@@ -1871,14 +1925,15 @@ var Sandbox = class Sandbox {
1871
1925
  baseImage: this.baseImage,
1872
1926
  platform: this.platform,
1873
1927
  maxTtlSeconds: this.maxTtlSeconds,
1928
+ idleTtlSeconds: this.idleTtlSeconds,
1874
1929
  maxConcurrentExecs: this.maxConcurrentExecs,
1875
1930
  endpoints: this.endpoints?.map((endpoint) => ({ ...endpoint })),
1876
1931
  createdAt: this.createdAt,
1877
1932
  runningAt: this.runningAt,
1878
1933
  finishedAt: this.finishedAt,
1879
1934
  lastActiveAt: this.lastActiveAt,
1880
- expiresAt: this.expiresAt,
1881
- exitReason: this.exitReason
1935
+ exitReason: this.exitReason,
1936
+ checkpoint: this.checkpoint
1882
1937
  };
1883
1938
  }
1884
1939
  /** Run a process and wait for it to exit. */
@@ -1920,17 +1975,117 @@ var Sandbox = class Sandbox {
1920
1975
  this._apply(data);
1921
1976
  return options.wait === false ? this : waitForSandboxStart(this);
1922
1977
  }
1923
- /** Create an isolated writable branch from this sandbox's current state. */
1978
+ /**
1979
+ * Create an isolated writable branch from this sandbox's current state.
1980
+ * A running sandbox is paused for the snapshot and resumed once the fork is
1981
+ * accepted; a paused or stopped sandbox is left as it is. The fork names the
1982
+ * checkpoint the pause returned, so it does not depend on the source still
1983
+ * being paused when the request lands. Resuming the source is best effort:
1984
+ * the child is returned even if the source could not be resumed, so check
1985
+ * the source's status afterwards if that matters.
1986
+ */
1924
1987
  async fork(options = {}) {
1925
- const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/fork", {
1988
+ const paused = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/pause", { params: { path: { sid: this.id } } }), "transient"));
1989
+ this._apply(paused);
1990
+ const resumeAfterFork = this.status === "pausing";
1991
+ const checkpoint = this.checkpoint;
1992
+ const wait = resumeAfterFork ? false : options.wait ?? true;
1993
+ const body = {
1994
+ name: options.name,
1995
+ checkpoint
1996
+ };
1997
+ const fork = await waitWhileSandboxStatus(this, "pausing").then(() => unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/fork", {
1926
1998
  params: {
1927
1999
  path: { sid: this.id },
1928
- query: { wait: options.wait ?? true }
2000
+ query: { wait }
1929
2001
  },
1930
- body: options.name === void 0 ? void 0 : { name: options.name }
2002
+ body
2003
+ }), "connect"))).then((data) => new Sandbox(data, this._client)).finally(() => resumeAfterFork ? this.resume({ wait: false }).catch(() => void 0) : void 0);
2004
+ if (options.wait === false) return fork;
2005
+ await waitForSandboxStart(fork);
2006
+ if (resumeAfterFork) await waitForSandboxStart(this).catch(() => void 0);
2007
+ return fork;
2008
+ }
2009
+ /** Expose a TCP port publicly (1–65535), returning its hostname. */
2010
+ async exposePort(port) {
2011
+ const client = this._client;
2012
+ return (await unwrap(retryApiRequest(() => client.PUT("/api/sandboxes/{sid}/ports/{port}", { params: { path: {
2013
+ sid: this.id,
2014
+ port
2015
+ } } }), "transient"))).hostname;
2016
+ }
2017
+ /** List explicitly exposed public ports. Service-published ports are in `endpoints`. */
2018
+ async listPorts() {
2019
+ const client = this._client;
2020
+ return (await unwrap(retryApiRequest(() => client.GET("/api/sandboxes/{sid}/ports", { params: { path: { sid: this.id } } }), "transient"))).ports;
2021
+ }
2022
+ /** Remove explicit public exposure. A service publishing the same port remains reachable. */
2023
+ async unexposePort(port) {
2024
+ const client = this._client;
2025
+ await unwrapEmpty(retryApiRequest(() => client.DELETE("/api/sandboxes/{sid}/ports/{port}", { params: { path: {
2026
+ sid: this.id,
2027
+ port
2028
+ } } }), "transient"));
2029
+ }
2030
+ /** Authorize HTTP access to one port without making it public. */
2031
+ async createPortToken(port, options = {}) {
2032
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/port-tokens", {
2033
+ params: { path: { sid: this.id } },
2034
+ body: {
2035
+ port,
2036
+ ttl: options.ttl
2037
+ }
1931
2038
  }), "connect"));
1932
- const fork = new Sandbox(data, this._client);
1933
- return options.wait === false ? fork : waitForSandboxStart(fork);
2039
+ return {
2040
+ ...portTokenFromWire(data),
2041
+ hostname: data.hostname,
2042
+ token: data.token
2043
+ };
2044
+ }
2045
+ /** Get token metadata. Expired and revoked tokens return not found. */
2046
+ async getPortToken(tokenId) {
2047
+ return portTokenFromWire(await unwrap(retryApiRequest(() => this._client.GET("/api/sandboxes/{sid}/port-tokens/{token_id}", { params: { path: {
2048
+ sid: this.id,
2049
+ token_id: tokenId
2050
+ } } }), "transient")));
2051
+ }
2052
+ /** List token metadata across pages. `limit` caps the total number returned. */
2053
+ async listPortTokens(options = {}) {
2054
+ const tokens = [];
2055
+ let cursor = options.cursor;
2056
+ for (;;) {
2057
+ const remaining = options.limit === void 0 ? void 0 : options.limit - tokens.length;
2058
+ if (remaining !== void 0 && remaining <= 0) return tokens;
2059
+ const page = await this.listPortTokensPage({
2060
+ limit: remaining === void 0 ? 100 : Math.min(remaining, 100),
2061
+ cursor
2062
+ });
2063
+ tokens.push(...page.tokens);
2064
+ if (!page.nextCursor) return tokens;
2065
+ cursor = page.nextCursor;
2066
+ }
2067
+ }
2068
+ /** Fetch one page of token metadata; pass `nextCursor` back as `cursor`. */
2069
+ async listPortTokensPage(options = {}) {
2070
+ const { data, nextCursor } = await unwrapPage(retryApiRequest(() => this._client.GET("/api/sandboxes/{sid}/port-tokens", { params: {
2071
+ path: { sid: this.id },
2072
+ query: {
2073
+ limit: options.limit ?? 100,
2074
+ cursor: options.cursor
2075
+ }
2076
+ } }), "transient"));
2077
+ return {
2078
+ tokens: data.tokens.map(portTokenFromWire),
2079
+ nextCursor
2080
+ };
2081
+ }
2082
+ /** Revoke a token for new connections. Existing connections remain open. */
2083
+ async deletePortToken(token) {
2084
+ const tokenId = typeof token === "string" ? token : token.id;
2085
+ await unwrapEmpty(retryApiRequest(() => this._client.DELETE("/api/sandboxes/{sid}/port-tokens/{token_id}", { params: { path: {
2086
+ sid: this.id,
2087
+ token_id: tokenId
2088
+ } } }), "transient"));
1934
2089
  }
1935
2090
  /** Get this running sandbox's effective network policy. */
1936
2091
  async getNetwork() {
@@ -1945,6 +2100,19 @@ var Sandbox = class Sandbox {
1945
2100
  body: network
1946
2101
  }), "transient"));
1947
2102
  }
2103
+ /** Update either or both TTLs in seconds. Omitted settings remain unchanged. */
2104
+ async setTimeout(timeout) {
2105
+ const options = typeof timeout === "number" ? { timeoutSeconds: timeout } : timeout;
2106
+ const client = this._client;
2107
+ const data = await unwrap(retryApiRequest(() => client.POST("/api/sandboxes/{sid}/timeout", {
2108
+ params: { path: { sid: this.id } },
2109
+ body: {
2110
+ timeout: options.timeoutSeconds,
2111
+ idle_ttl_seconds: options.idleTtlSeconds
2112
+ }
2113
+ }), "transient"));
2114
+ return this._apply(data);
2115
+ }
1948
2116
  /** Delete this sandbox and its backing disk. */
1949
2117
  async delete() {
1950
2118
  await unwrapEmpty(retryApiRequest(() => this._client.DELETE("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }), "transient"));
@@ -1986,8 +2154,10 @@ var Sandboxes = class {
1986
2154
  base_image: request.baseImage,
1987
2155
  env: request.env,
1988
2156
  max_ttl_seconds: request.maxTtlSeconds,
2157
+ idle_ttl_seconds: request.idleTtlSeconds,
1989
2158
  max_concurrent_execs: request.maxConcurrentExecs,
1990
- network: request.network
2159
+ network: request.network,
2160
+ ports: request.ports
1991
2161
  };
1992
2162
  const sandbox = new Sandbox(await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes", {
1993
2163
  params: { query: { wait: options.wait ?? true } },
@@ -2015,7 +2185,7 @@ var Tokens = class {
2015
2185
  return await unwrap(this._client.POST("/api/tokens", { body: req }));
2016
2186
  }
2017
2187
  async delete(id) {
2018
- await unwrapEmpty(this._client.DELETE("/api/tokens/{id}", { params: { path: { id } } }));
2188
+ await unwrapEmpty(this._client.DELETE("/api/tokens/{tokenId}", { params: { path: { tokenId: id } } }));
2019
2189
  }
2020
2190
  };
2021
2191
  //#endregion
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as S3Mount, A as ApiTokenResponse, B as DiskStatus, C as PutObjectOptions, D as ShareUrlResult, E as ShareUrlOptions, F as CreateApiTokenRequest, G as GrepMatch, H as ExecDiskResult, I as CreateDiskRequest, J as MountConfigResponse, K as GrepStoppedReason, L as Delegation, M as AwsStsUser, N as AzureBlobMount, O as UploadPart, P as ConnectedClient, Q as S3CompatibleMount, R as DiskMetrics, S as PosixCreateAttrs, T as S3Object, U as ExecRequest, V as DiskUser, W as GCSMount, X as R2Mount, Y as MountResponse, Z as RootAttrs, _ as MultipartUploadListing, a as DeleteObjectsResult, b as PartInfo, c as ExecResult, d as ListMultipartUploadsOptions, et as TokenUser, f as ListObjectsOptions, g as MultipartUpload, h as MountOptions, i as DeleteObjectsOptions, j as AuthorizedUser, k as effectiveUploadPartSize, l as GrepOptions, m as ListPartsOptions, n as CompletedMultipartUpload, nt as ApiClient, o as Disk, p as ListObjectsResult, q as MountConfig, r as DeleteObjectsError, s as DiskMultipart, t as AppendObjectOptions, tt as FileSystem, u as GrepResult, v as MultipartUploadSummary, w as PutObjectResult, x as PartListing, y as ObjectMetadata, z as DiskResponse } from "./disk-DqGdJGsu.cjs";
1
+ import { $ as S3Mount, A as ApiTokenResponse, B as DiskStatus, C as PutObjectOptions, D as ShareUrlResult, E as ShareUrlOptions, F as CreateApiTokenRequest, G as GrepMatch, H as ExecDiskResult, I as CreateDiskRequest, J as MountConfigResponse, K as GrepStoppedReason, L as Delegation, M as AwsStsUser, N as AzureBlobMount, O as UploadPart, P as ConnectedClient, Q as S3CompatibleMount, R as DiskMetrics, S as PosixCreateAttrs, T as S3Object, U as ExecRequest, V as DiskUser, W as GCSMount, X as R2Mount, Y as MountResponse, Z as RootAttrs, _ as MultipartUploadListing, a as DeleteObjectsResult, b as PartInfo, c as ExecResult, d as ListMultipartUploadsOptions, et as TokenUser, f as ListObjectsOptions, g as MultipartUpload, h as MountOptions, i as DeleteObjectsOptions, j as AuthorizedUser, k as effectiveUploadPartSize, l as GrepOptions, m as ListPartsOptions, n as CompletedMultipartUpload, nt as ApiClient, o as Disk, p as ListObjectsResult, q as MountConfig, r as DeleteObjectsError, s as DiskMultipart, t as AppendObjectOptions, tt as FileSystem, u as GrepResult, v as MultipartUploadSummary, w as PutObjectResult, x as PartListing, y as ObjectMetadata, z as DiskResponse } from "./disk-CiLNoFCd.cjs";
2
2
  import { components } from "@archildata/api-types";
3
3
 
4
4
  //#region src/disks.d.ts
@@ -201,12 +201,38 @@ type SandboxEgressRule = components["schemas"]["SandboxEgressRule"];
201
201
  type SandboxEgressTransform = components["schemas"]["SandboxEgressTransform"];
202
202
  type SandboxNetwork = components["schemas"]["SandboxNetwork"];
203
203
  /** @internal */
204
- type SandboxWire = components["schemas"]["Sandbox"];
204
+ type SandboxWire = components["schemas"]["Sandbox"] & {
205
+ idle_ttl_seconds?: number;
206
+ };
205
207
  type SandboxStatus = components["schemas"]["SandboxState"];
206
208
  interface SandboxEndpoint {
207
209
  port: number;
208
210
  hostname: string;
209
211
  }
212
+ /** Port-token metadata. The secret and hostname are returned only on creation. */
213
+ interface SandboxPortToken {
214
+ id: string;
215
+ port: number;
216
+ createdAt: Date;
217
+ expiresAt?: Date;
218
+ }
219
+ interface CreatedSandboxPortToken extends SandboxPortToken {
220
+ hostname: string;
221
+ /** Send in X-Archil-Token. Save it now; it cannot be retrieved again. */
222
+ token: string;
223
+ }
224
+ interface CreateSandboxPortTokenOptions {
225
+ /** Duration such as "1h" or "30m", up to "8760h" (365 days). Omit for no expiration. */
226
+ ttl?: string;
227
+ }
228
+ interface ListSandboxPortTokensOptions {
229
+ limit?: number;
230
+ cursor?: string;
231
+ }
232
+ interface SandboxPortTokenPage {
233
+ tokens: SandboxPortToken[];
234
+ nextCursor?: string;
235
+ }
210
236
  interface SandboxResponse {
211
237
  id: string;
212
238
  name: string;
@@ -216,6 +242,7 @@ interface SandboxResponse {
216
242
  baseImage: string;
217
243
  platform?: "arm64" | "amd64";
218
244
  maxTtlSeconds: number;
245
+ idleTtlSeconds: number;
219
246
  /** Maximum concurrently attached process sessions. Detached processes and one-shot controls do not count. */
220
247
  maxConcurrentExecs: number;
221
248
  endpoints?: SandboxEndpoint[];
@@ -223,8 +250,9 @@ interface SandboxResponse {
223
250
  runningAt?: Date;
224
251
  finishedAt?: Date;
225
252
  lastActiveAt: Date;
226
- expiresAt?: Date;
227
253
  exitReason?: string;
254
+ /** Disk checkpoint the current session leaves behind; present while pausing, paused, stopping, or stopped. */
255
+ checkpoint?: string;
228
256
  }
229
257
  interface SandboxWaitOptions {
230
258
  /**
@@ -237,6 +265,12 @@ interface SandboxForkOptions extends SandboxWaitOptions {
237
265
  /** Name for the fork. The server generates one when omitted. */
238
266
  name?: string;
239
267
  }
268
+ interface SandboxTimeoutOptions {
269
+ /** Hard lifetime in seconds. Omit to leave its deadline unchanged. */
270
+ timeoutSeconds?: number;
271
+ /** Seconds without a direct process connection. Zero disables idle expiry; omit to leave unchanged. */
272
+ idleTtlSeconds?: number;
273
+ }
240
274
  declare class Sandbox {
241
275
  id: string;
242
276
  name: string;
@@ -246,14 +280,15 @@ declare class Sandbox {
246
280
  baseImage: string;
247
281
  platform?: "arm64" | "amd64";
248
282
  maxTtlSeconds: number;
283
+ idleTtlSeconds: number;
249
284
  maxConcurrentExecs: number;
250
285
  endpoints?: SandboxEndpoint[];
251
286
  createdAt: Date;
252
287
  runningAt?: Date;
253
288
  finishedAt?: Date;
254
289
  lastActiveAt: Date;
255
- expiresAt?: Date;
256
290
  exitReason?: string;
291
+ checkpoint?: string;
257
292
  readonly processes: SandboxProcesses;
258
293
  readonly files: SandboxFiles;
259
294
  /** @internal */
@@ -275,12 +310,38 @@ declare class Sandbox {
275
310
  pause(options?: SandboxWaitOptions): Promise<Sandbox | this>;
276
311
  /** Resume this sandbox from its preserved CPU and memory state. */
277
312
  resume(options?: SandboxWaitOptions): Promise<Sandbox | this>;
278
- /** Create an isolated writable branch from this sandbox's current state. */
313
+ /**
314
+ * Create an isolated writable branch from this sandbox's current state.
315
+ * A running sandbox is paused for the snapshot and resumed once the fork is
316
+ * accepted; a paused or stopped sandbox is left as it is. The fork names the
317
+ * checkpoint the pause returned, so it does not depend on the source still
318
+ * being paused when the request lands. Resuming the source is best effort:
319
+ * the child is returned even if the source could not be resumed, so check
320
+ * the source's status afterwards if that matters.
321
+ */
279
322
  fork(options?: SandboxForkOptions): Promise<Sandbox>;
323
+ /** Expose a TCP port publicly (1–65535), returning its hostname. */
324
+ exposePort(port: number): Promise<string>;
325
+ /** List explicitly exposed public ports. Service-published ports are in `endpoints`. */
326
+ listPorts(): Promise<SandboxEndpoint[]>;
327
+ /** Remove explicit public exposure. A service publishing the same port remains reachable. */
328
+ unexposePort(port: number): Promise<void>;
329
+ /** Authorize HTTP access to one port without making it public. */
330
+ createPortToken(port: number, options?: CreateSandboxPortTokenOptions): Promise<CreatedSandboxPortToken>;
331
+ /** Get token metadata. Expired and revoked tokens return not found. */
332
+ getPortToken(tokenId: string): Promise<SandboxPortToken>;
333
+ /** List token metadata across pages. `limit` caps the total number returned. */
334
+ listPortTokens(options?: ListSandboxPortTokensOptions): Promise<SandboxPortToken[]>;
335
+ /** Fetch one page of token metadata; pass `nextCursor` back as `cursor`. */
336
+ listPortTokensPage(options?: ListSandboxPortTokensOptions): Promise<SandboxPortTokenPage>;
337
+ /** Revoke a token for new connections. Existing connections remain open. */
338
+ deletePortToken(token: SandboxPortToken | string): Promise<void>;
280
339
  /** Get this running sandbox's effective network policy. */
281
340
  getNetwork(): Promise<SandboxNetwork>;
282
341
  /** Replace this running sandbox's complete network policy and return the effective policy. */
283
342
  updateNetwork(network: SandboxNetwork): Promise<SandboxNetwork>;
343
+ /** Update either or both TTLs in seconds. Omitted settings remain unchanged. */
344
+ setTimeout(timeout: number | SandboxTimeoutOptions): Promise<this>;
284
345
  /** Delete this sandbox and its backing disk. */
285
346
  delete(): Promise<void>;
286
347
  }
@@ -305,10 +366,14 @@ interface CreateSandboxRequest {
305
366
  baseImage?: string;
306
367
  env?: Record<string, string>;
307
368
  maxTtlSeconds?: number;
369
+ /** Seconds without a direct process connection before pausing. Omitted or zero disables idle expiry. */
370
+ idleTtlSeconds?: number;
308
371
  /** Maximum concurrently attached exec sessions. Detached processes and one-shot controls do not count. */
309
372
  maxConcurrentExecs?: number;
310
373
  /** Creation-time network policy. Egress is unrestricted when omitted. */
311
374
  network?: SandboxNetwork;
375
+ /** TCP ports to expose publicly, from 1 to 65535. */
376
+ ports?: number[];
312
377
  }
313
378
  interface ListSandboxesOptions {
314
379
  /** Only return sandboxes that mount this disk. */
@@ -565,4 +630,4 @@ declare function exec(opts: ExecOptions): Promise<ExecDiskResult>;
565
630
  */
566
631
  declare function workspace(mounts: Record<string, ExecMount>): Workspace;
567
632
  //#endregion
568
- export { type ApiTokenResponse, type AppendObjectOptions, Archil, ArchilApiError, ArchilError, type ArchilOptions, ArchilS3Error, type AuthorizedUser, type AwsStsUser, type AzureBlobMount, type CompletedMultipartUpload, type ConnectedClient, type CreateApiTokenRequest, type CreateDiskRequest, type CreateDiskResult, type CreateSandboxRequest, type Delegation, type DeleteObjectsError, type DeleteObjectsOptions, type DeleteObjectsResult, Disk, type DiskListPage, type DiskMetrics, DiskMultipart, type DiskResponse, type DiskStatus, type DiskUser, Disks, type ExecMount, type ExecMountSpec, type ExecOptions, type ExecRequest, type ExecResult, type FileSystem, type GCSMount, type GrepMatch, type GrepOptions, type GrepResult, type GrepStoppedReason, type ListDisksOptions, type ListMultipartUploadsOptions, type ListObjectsOptions, type ListObjectsResult, type ListPartsOptions, type ListSandboxesOptions, type ListTokensOptions, type MountConfig, type MountConfigResponse, type MountOptions, type MountResponse, type MultipartUpload, type MultipartUploadListing, type MultipartUploadSummary, type ObjectMetadata, type PartInfo, type PartListing, type PosixCreateAttrs, type PutObjectOptions, type PutObjectResult, type R2Mount, type RootAttrs, type S3CompatibleMount, type S3Mount, type S3Object, Sandbox, type SandboxEgressPolicy, type SandboxEgressRule, type SandboxEgressTransform, type SandboxEndpoint, type SandboxFileSource, SandboxFileTransferError, type SandboxFileUploadOptions, type SandboxFileWriter, SandboxFiles, type SandboxForkOptions, type SandboxNetwork, type SandboxNetworkAction, SandboxProcess, type SandboxProcessConnectOptions, type SandboxProcessOutput, type SandboxProcessOutputHandler, type SandboxProcessResult, type SandboxProcessStartOptions, type SandboxProcessStatus, type SandboxProcessStream, SandboxProcesses, type SandboxResponse, type SandboxStatus, type SandboxTerminalOptions, type SandboxWaitOptions, Sandboxes, type ShareUrlOptions, type ShareUrlResult, type TokenUser, Tokens, USER_AGENT, type UploadPart, VERSION, Workspace, configure, createApiKey, createDisk, createSandbox, deleteApiKey, effectiveUploadPartSize, exec, getDisk, getSandbox, listApiKeys, listDisks, listSandboxes, workspace };
633
+ export { type ApiTokenResponse, type AppendObjectOptions, Archil, ArchilApiError, ArchilError, type ArchilOptions, ArchilS3Error, type AuthorizedUser, type AwsStsUser, type AzureBlobMount, type CompletedMultipartUpload, type ConnectedClient, type CreateApiTokenRequest, type CreateDiskRequest, type CreateDiskResult, type CreateSandboxPortTokenOptions, type CreateSandboxRequest, type CreatedSandboxPortToken, type Delegation, type DeleteObjectsError, type DeleteObjectsOptions, type DeleteObjectsResult, Disk, type DiskListPage, type DiskMetrics, DiskMultipart, type DiskResponse, type DiskStatus, type DiskUser, Disks, type ExecMount, type ExecMountSpec, type ExecOptions, type ExecRequest, type ExecResult, type FileSystem, type GCSMount, type GrepMatch, type GrepOptions, type GrepResult, type GrepStoppedReason, type ListDisksOptions, type ListMultipartUploadsOptions, type ListObjectsOptions, type ListObjectsResult, type ListPartsOptions, type ListSandboxPortTokensOptions, type ListSandboxesOptions, type ListTokensOptions, type MountConfig, type MountConfigResponse, type MountOptions, type MountResponse, type MultipartUpload, type MultipartUploadListing, type MultipartUploadSummary, type ObjectMetadata, type PartInfo, type PartListing, type PosixCreateAttrs, type PutObjectOptions, type PutObjectResult, type R2Mount, type RootAttrs, type S3CompatibleMount, type S3Mount, type S3Object, Sandbox, type SandboxEgressPolicy, type SandboxEgressRule, type SandboxEgressTransform, type SandboxEndpoint, type SandboxFileSource, SandboxFileTransferError, type SandboxFileUploadOptions, type SandboxFileWriter, SandboxFiles, type SandboxForkOptions, type SandboxNetwork, type SandboxNetworkAction, type SandboxPortToken, type SandboxPortTokenPage, SandboxProcess, type SandboxProcessConnectOptions, type SandboxProcessOutput, type SandboxProcessOutputHandler, type SandboxProcessResult, type SandboxProcessStartOptions, type SandboxProcessStatus, type SandboxProcessStream, SandboxProcesses, type SandboxResponse, type SandboxStatus, type SandboxTerminalOptions, type SandboxTimeoutOptions, type SandboxWaitOptions, Sandboxes, type ShareUrlOptions, type ShareUrlResult, type TokenUser, Tokens, USER_AGENT, type UploadPart, VERSION, Workspace, configure, createApiKey, createDisk, createSandbox, deleteApiKey, effectiveUploadPartSize, exec, getDisk, getSandbox, listApiKeys, listDisks, listSandboxes, workspace };
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as S3Mount, A as ApiTokenResponse, B as DiskStatus, C as PutObjectOptions, D as ShareUrlResult, E as ShareUrlOptions, F as CreateApiTokenRequest, G as GrepMatch, H as ExecDiskResult, I as CreateDiskRequest, J as MountConfigResponse, K as GrepStoppedReason, L as Delegation, M as AwsStsUser, N as AzureBlobMount, O as UploadPart, P as ConnectedClient, Q as S3CompatibleMount, R as DiskMetrics, S as PosixCreateAttrs, T as S3Object, U as ExecRequest, V as DiskUser, W as GCSMount, X as R2Mount, Y as MountResponse, Z as RootAttrs, _ as MultipartUploadListing, a as DeleteObjectsResult, b as PartInfo, c as ExecResult, d as ListMultipartUploadsOptions, et as TokenUser, f as ListObjectsOptions, g as MultipartUpload, h as MountOptions, i as DeleteObjectsOptions, j as AuthorizedUser, k as effectiveUploadPartSize, l as GrepOptions, m as ListPartsOptions, n as CompletedMultipartUpload, nt as ApiClient, o as Disk, p as ListObjectsResult, q as MountConfig, r as DeleteObjectsError, s as DiskMultipart, t as AppendObjectOptions, tt as FileSystem, u as GrepResult, v as MultipartUploadSummary, w as PutObjectResult, x as PartListing, y as ObjectMetadata, z as DiskResponse } from "./disk-DqGdJGsu.mjs";
1
+ import { $ as S3Mount, A as ApiTokenResponse, B as DiskStatus, C as PutObjectOptions, D as ShareUrlResult, E as ShareUrlOptions, F as CreateApiTokenRequest, G as GrepMatch, H as ExecDiskResult, I as CreateDiskRequest, J as MountConfigResponse, K as GrepStoppedReason, L as Delegation, M as AwsStsUser, N as AzureBlobMount, O as UploadPart, P as ConnectedClient, Q as S3CompatibleMount, R as DiskMetrics, S as PosixCreateAttrs, T as S3Object, U as ExecRequest, V as DiskUser, W as GCSMount, X as R2Mount, Y as MountResponse, Z as RootAttrs, _ as MultipartUploadListing, a as DeleteObjectsResult, b as PartInfo, c as ExecResult, d as ListMultipartUploadsOptions, et as TokenUser, f as ListObjectsOptions, g as MultipartUpload, h as MountOptions, i as DeleteObjectsOptions, j as AuthorizedUser, k as effectiveUploadPartSize, l as GrepOptions, m as ListPartsOptions, n as CompletedMultipartUpload, nt as ApiClient, o as Disk, p as ListObjectsResult, q as MountConfig, r as DeleteObjectsError, s as DiskMultipart, t as AppendObjectOptions, tt as FileSystem, u as GrepResult, v as MultipartUploadSummary, w as PutObjectResult, x as PartListing, y as ObjectMetadata, z as DiskResponse } from "./disk-CiLNoFCd.mjs";
2
2
  import { components } from "@archildata/api-types";
3
3
 
4
4
  //#region src/disks.d.ts
@@ -201,12 +201,38 @@ type SandboxEgressRule = components["schemas"]["SandboxEgressRule"];
201
201
  type SandboxEgressTransform = components["schemas"]["SandboxEgressTransform"];
202
202
  type SandboxNetwork = components["schemas"]["SandboxNetwork"];
203
203
  /** @internal */
204
- type SandboxWire = components["schemas"]["Sandbox"];
204
+ type SandboxWire = components["schemas"]["Sandbox"] & {
205
+ idle_ttl_seconds?: number;
206
+ };
205
207
  type SandboxStatus = components["schemas"]["SandboxState"];
206
208
  interface SandboxEndpoint {
207
209
  port: number;
208
210
  hostname: string;
209
211
  }
212
+ /** Port-token metadata. The secret and hostname are returned only on creation. */
213
+ interface SandboxPortToken {
214
+ id: string;
215
+ port: number;
216
+ createdAt: Date;
217
+ expiresAt?: Date;
218
+ }
219
+ interface CreatedSandboxPortToken extends SandboxPortToken {
220
+ hostname: string;
221
+ /** Send in X-Archil-Token. Save it now; it cannot be retrieved again. */
222
+ token: string;
223
+ }
224
+ interface CreateSandboxPortTokenOptions {
225
+ /** Duration such as "1h" or "30m", up to "8760h" (365 days). Omit for no expiration. */
226
+ ttl?: string;
227
+ }
228
+ interface ListSandboxPortTokensOptions {
229
+ limit?: number;
230
+ cursor?: string;
231
+ }
232
+ interface SandboxPortTokenPage {
233
+ tokens: SandboxPortToken[];
234
+ nextCursor?: string;
235
+ }
210
236
  interface SandboxResponse {
211
237
  id: string;
212
238
  name: string;
@@ -216,6 +242,7 @@ interface SandboxResponse {
216
242
  baseImage: string;
217
243
  platform?: "arm64" | "amd64";
218
244
  maxTtlSeconds: number;
245
+ idleTtlSeconds: number;
219
246
  /** Maximum concurrently attached process sessions. Detached processes and one-shot controls do not count. */
220
247
  maxConcurrentExecs: number;
221
248
  endpoints?: SandboxEndpoint[];
@@ -223,8 +250,9 @@ interface SandboxResponse {
223
250
  runningAt?: Date;
224
251
  finishedAt?: Date;
225
252
  lastActiveAt: Date;
226
- expiresAt?: Date;
227
253
  exitReason?: string;
254
+ /** Disk checkpoint the current session leaves behind; present while pausing, paused, stopping, or stopped. */
255
+ checkpoint?: string;
228
256
  }
229
257
  interface SandboxWaitOptions {
230
258
  /**
@@ -237,6 +265,12 @@ interface SandboxForkOptions extends SandboxWaitOptions {
237
265
  /** Name for the fork. The server generates one when omitted. */
238
266
  name?: string;
239
267
  }
268
+ interface SandboxTimeoutOptions {
269
+ /** Hard lifetime in seconds. Omit to leave its deadline unchanged. */
270
+ timeoutSeconds?: number;
271
+ /** Seconds without a direct process connection. Zero disables idle expiry; omit to leave unchanged. */
272
+ idleTtlSeconds?: number;
273
+ }
240
274
  declare class Sandbox {
241
275
  id: string;
242
276
  name: string;
@@ -246,14 +280,15 @@ declare class Sandbox {
246
280
  baseImage: string;
247
281
  platform?: "arm64" | "amd64";
248
282
  maxTtlSeconds: number;
283
+ idleTtlSeconds: number;
249
284
  maxConcurrentExecs: number;
250
285
  endpoints?: SandboxEndpoint[];
251
286
  createdAt: Date;
252
287
  runningAt?: Date;
253
288
  finishedAt?: Date;
254
289
  lastActiveAt: Date;
255
- expiresAt?: Date;
256
290
  exitReason?: string;
291
+ checkpoint?: string;
257
292
  readonly processes: SandboxProcesses;
258
293
  readonly files: SandboxFiles;
259
294
  /** @internal */
@@ -275,12 +310,38 @@ declare class Sandbox {
275
310
  pause(options?: SandboxWaitOptions): Promise<Sandbox | this>;
276
311
  /** Resume this sandbox from its preserved CPU and memory state. */
277
312
  resume(options?: SandboxWaitOptions): Promise<Sandbox | this>;
278
- /** Create an isolated writable branch from this sandbox's current state. */
313
+ /**
314
+ * Create an isolated writable branch from this sandbox's current state.
315
+ * A running sandbox is paused for the snapshot and resumed once the fork is
316
+ * accepted; a paused or stopped sandbox is left as it is. The fork names the
317
+ * checkpoint the pause returned, so it does not depend on the source still
318
+ * being paused when the request lands. Resuming the source is best effort:
319
+ * the child is returned even if the source could not be resumed, so check
320
+ * the source's status afterwards if that matters.
321
+ */
279
322
  fork(options?: SandboxForkOptions): Promise<Sandbox>;
323
+ /** Expose a TCP port publicly (1–65535), returning its hostname. */
324
+ exposePort(port: number): Promise<string>;
325
+ /** List explicitly exposed public ports. Service-published ports are in `endpoints`. */
326
+ listPorts(): Promise<SandboxEndpoint[]>;
327
+ /** Remove explicit public exposure. A service publishing the same port remains reachable. */
328
+ unexposePort(port: number): Promise<void>;
329
+ /** Authorize HTTP access to one port without making it public. */
330
+ createPortToken(port: number, options?: CreateSandboxPortTokenOptions): Promise<CreatedSandboxPortToken>;
331
+ /** Get token metadata. Expired and revoked tokens return not found. */
332
+ getPortToken(tokenId: string): Promise<SandboxPortToken>;
333
+ /** List token metadata across pages. `limit` caps the total number returned. */
334
+ listPortTokens(options?: ListSandboxPortTokensOptions): Promise<SandboxPortToken[]>;
335
+ /** Fetch one page of token metadata; pass `nextCursor` back as `cursor`. */
336
+ listPortTokensPage(options?: ListSandboxPortTokensOptions): Promise<SandboxPortTokenPage>;
337
+ /** Revoke a token for new connections. Existing connections remain open. */
338
+ deletePortToken(token: SandboxPortToken | string): Promise<void>;
280
339
  /** Get this running sandbox's effective network policy. */
281
340
  getNetwork(): Promise<SandboxNetwork>;
282
341
  /** Replace this running sandbox's complete network policy and return the effective policy. */
283
342
  updateNetwork(network: SandboxNetwork): Promise<SandboxNetwork>;
343
+ /** Update either or both TTLs in seconds. Omitted settings remain unchanged. */
344
+ setTimeout(timeout: number | SandboxTimeoutOptions): Promise<this>;
284
345
  /** Delete this sandbox and its backing disk. */
285
346
  delete(): Promise<void>;
286
347
  }
@@ -305,10 +366,14 @@ interface CreateSandboxRequest {
305
366
  baseImage?: string;
306
367
  env?: Record<string, string>;
307
368
  maxTtlSeconds?: number;
369
+ /** Seconds without a direct process connection before pausing. Omitted or zero disables idle expiry. */
370
+ idleTtlSeconds?: number;
308
371
  /** Maximum concurrently attached exec sessions. Detached processes and one-shot controls do not count. */
309
372
  maxConcurrentExecs?: number;
310
373
  /** Creation-time network policy. Egress is unrestricted when omitted. */
311
374
  network?: SandboxNetwork;
375
+ /** TCP ports to expose publicly, from 1 to 65535. */
376
+ ports?: number[];
312
377
  }
313
378
  interface ListSandboxesOptions {
314
379
  /** Only return sandboxes that mount this disk. */
@@ -565,4 +630,4 @@ declare function exec(opts: ExecOptions): Promise<ExecDiskResult>;
565
630
  */
566
631
  declare function workspace(mounts: Record<string, ExecMount>): Workspace;
567
632
  //#endregion
568
- export { type ApiTokenResponse, type AppendObjectOptions, Archil, ArchilApiError, ArchilError, type ArchilOptions, ArchilS3Error, type AuthorizedUser, type AwsStsUser, type AzureBlobMount, type CompletedMultipartUpload, type ConnectedClient, type CreateApiTokenRequest, type CreateDiskRequest, type CreateDiskResult, type CreateSandboxRequest, type Delegation, type DeleteObjectsError, type DeleteObjectsOptions, type DeleteObjectsResult, Disk, type DiskListPage, type DiskMetrics, DiskMultipart, type DiskResponse, type DiskStatus, type DiskUser, Disks, type ExecMount, type ExecMountSpec, type ExecOptions, type ExecRequest, type ExecResult, type FileSystem, type GCSMount, type GrepMatch, type GrepOptions, type GrepResult, type GrepStoppedReason, type ListDisksOptions, type ListMultipartUploadsOptions, type ListObjectsOptions, type ListObjectsResult, type ListPartsOptions, type ListSandboxesOptions, type ListTokensOptions, type MountConfig, type MountConfigResponse, type MountOptions, type MountResponse, type MultipartUpload, type MultipartUploadListing, type MultipartUploadSummary, type ObjectMetadata, type PartInfo, type PartListing, type PosixCreateAttrs, type PutObjectOptions, type PutObjectResult, type R2Mount, type RootAttrs, type S3CompatibleMount, type S3Mount, type S3Object, Sandbox, type SandboxEgressPolicy, type SandboxEgressRule, type SandboxEgressTransform, type SandboxEndpoint, type SandboxFileSource, SandboxFileTransferError, type SandboxFileUploadOptions, type SandboxFileWriter, SandboxFiles, type SandboxForkOptions, type SandboxNetwork, type SandboxNetworkAction, SandboxProcess, type SandboxProcessConnectOptions, type SandboxProcessOutput, type SandboxProcessOutputHandler, type SandboxProcessResult, type SandboxProcessStartOptions, type SandboxProcessStatus, type SandboxProcessStream, SandboxProcesses, type SandboxResponse, type SandboxStatus, type SandboxTerminalOptions, type SandboxWaitOptions, Sandboxes, type ShareUrlOptions, type ShareUrlResult, type TokenUser, Tokens, USER_AGENT, type UploadPart, VERSION, Workspace, configure, createApiKey, createDisk, createSandbox, deleteApiKey, effectiveUploadPartSize, exec, getDisk, getSandbox, listApiKeys, listDisks, listSandboxes, workspace };
633
+ export { type ApiTokenResponse, type AppendObjectOptions, Archil, ArchilApiError, ArchilError, type ArchilOptions, ArchilS3Error, type AuthorizedUser, type AwsStsUser, type AzureBlobMount, type CompletedMultipartUpload, type ConnectedClient, type CreateApiTokenRequest, type CreateDiskRequest, type CreateDiskResult, type CreateSandboxPortTokenOptions, type CreateSandboxRequest, type CreatedSandboxPortToken, type Delegation, type DeleteObjectsError, type DeleteObjectsOptions, type DeleteObjectsResult, Disk, type DiskListPage, type DiskMetrics, DiskMultipart, type DiskResponse, type DiskStatus, type DiskUser, Disks, type ExecMount, type ExecMountSpec, type ExecOptions, type ExecRequest, type ExecResult, type FileSystem, type GCSMount, type GrepMatch, type GrepOptions, type GrepResult, type GrepStoppedReason, type ListDisksOptions, type ListMultipartUploadsOptions, type ListObjectsOptions, type ListObjectsResult, type ListPartsOptions, type ListSandboxPortTokensOptions, type ListSandboxesOptions, type ListTokensOptions, type MountConfig, type MountConfigResponse, type MountOptions, type MountResponse, type MultipartUpload, type MultipartUploadListing, type MultipartUploadSummary, type ObjectMetadata, type PartInfo, type PartListing, type PosixCreateAttrs, type PutObjectOptions, type PutObjectResult, type R2Mount, type RootAttrs, type S3CompatibleMount, type S3Mount, type S3Object, Sandbox, type SandboxEgressPolicy, type SandboxEgressRule, type SandboxEgressTransform, type SandboxEndpoint, type SandboxFileSource, SandboxFileTransferError, type SandboxFileUploadOptions, type SandboxFileWriter, SandboxFiles, type SandboxForkOptions, type SandboxNetwork, type SandboxNetworkAction, type SandboxPortToken, type SandboxPortTokenPage, SandboxProcess, type SandboxProcessConnectOptions, type SandboxProcessOutput, type SandboxProcessOutputHandler, type SandboxProcessResult, type SandboxProcessStartOptions, type SandboxProcessStatus, type SandboxProcessStream, SandboxProcesses, type SandboxResponse, type SandboxStatus, type SandboxTerminalOptions, type SandboxTimeoutOptions, type SandboxWaitOptions, Sandboxes, type ShareUrlOptions, type ShareUrlResult, type TokenUser, Tokens, USER_AGENT, type UploadPart, VERSION, Workspace, configure, createApiKey, createDisk, createSandbox, deleteApiKey, effectiveUploadPartSize, exec, getDisk, getSandbox, listApiKeys, listDisks, listSandboxes, workspace };
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { A as ArchilS3Error, C as DiskMultipart, E as VERSION, O as ArchilApiError, S as Disk, T as USER_AGENT, _ as Sandbox, a as deleteApiKey, b as SandboxProcesses, c as getSandbox, d as listSandboxes, f as workspace, g as Sandboxes, h as Tokens, i as createSandbox, j as SandboxFileTransferError, k as ArchilError, l as listApiKeys, m as Workspace, n as createApiKey, o as exec, p as Archil, r as createDisk, s as getDisk, t as configure, u as listDisks, v as SandboxFiles, w as effectiveUploadPartSize, x as Disks, y as SandboxProcess } from "./src-DXNLDPID.mjs";
1
+ import { A as ArchilS3Error, C as DiskMultipart, E as VERSION, O as ArchilApiError, S as Disk, T as USER_AGENT, _ as Sandbox, a as deleteApiKey, b as SandboxProcesses, c as getSandbox, d as listSandboxes, f as workspace, g as Sandboxes, h as Tokens, i as createSandbox, j as SandboxFileTransferError, k as ArchilError, l as listApiKeys, m as Workspace, n as createApiKey, o as exec, p as Archil, r as createDisk, s as getDisk, t as configure, u as listDisks, v as SandboxFiles, w as effectiveUploadPartSize, x as Disks, y as SandboxProcess } from "./src-CvTkHglv.mjs";
2
2
  export { Archil, ArchilApiError, ArchilError, ArchilS3Error, Disk, DiskMultipart, Disks, Sandbox, SandboxFileTransferError, SandboxFiles, SandboxProcess, SandboxProcesses, Sandboxes, Tokens, USER_AGENT, VERSION, Workspace, configure, createApiKey, createDisk, createSandbox, deleteApiKey, effectiveUploadPartSize, exec, getDisk, getSandbox, listApiKeys, listDisks, listSandboxes, workspace };
@@ -1,4 +1,4 @@
1
- import { tt as FileSystem } from "../disk-DqGdJGsu.cjs";
1
+ import { tt as FileSystem } from "../disk-CiLNoFCd.cjs";
2
2
  import { ZodType, z } from "zod";
3
3
 
4
4
  //#region src/internal/tools.d.ts
@@ -1,4 +1,4 @@
1
- import { tt as FileSystem } from "../disk-DqGdJGsu.mjs";
1
+ import { tt as FileSystem } from "../disk-CiLNoFCd.mjs";
2
2
  import { ZodType, z } from "zod";
3
3
 
4
4
  //#region src/internal/tools.d.ts
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { O as ArchilApiError, p as Archil } from "./src-DXNLDPID.mjs";
3
- import { a as renderTable, i as resolveProgramCredentials, n as addProfileCommands, r as isProfileCommand, t as addGlobalOptions } from "./common-DUyyWu2M.mjs";
2
+ import { O as ArchilApiError, p as Archil } from "./src-CvTkHglv.mjs";
3
+ import { a as renderTable, i as resolveProgramCredentials, n as addProfileCommands, r as isProfileCommand, t as addGlobalOptions } from "./common-BFAzXgkJ.mjs";
4
4
  import { createRequire } from "node:module";
5
5
  import { Command } from "commander";
6
6
  import { spinner } from "@clack/prompts";
@@ -30,8 +30,7 @@ function formatSandboxList(sandboxes, format) {
30
30
  String(sandbox.vcpuCount),
31
31
  `${sandbox.memSizeMiB} MiB`,
32
32
  sandbox.baseImage,
33
- date(sandbox.lastActiveAt),
34
- date(sandbox.expiresAt)
33
+ date(sandbox.lastActiveAt)
35
34
  ]), [
36
35
  "id",
37
36
  "name",
@@ -39,8 +38,7 @@ function formatSandboxList(sandboxes, format) {
39
38
  "cpu",
40
39
  "memory",
41
40
  "image",
42
- "last active",
43
- "expires"
41
+ "last active"
44
42
  ]);
45
43
  }
46
44
  function formatSandbox(sandbox, format) {
@@ -54,12 +52,12 @@ function formatSandbox(sandbox, format) {
54
52
  ["image", sandbox.baseImage],
55
53
  ["platform", sandbox.platform ?? ""],
56
54
  ["max TTL", `${sandbox.maxTtlSeconds} seconds`],
55
+ ["idle TTL", sandbox.idleTtlSeconds === 0 ? "disabled" : `${sandbox.idleTtlSeconds} seconds`],
57
56
  ["max concurrent processes", String(sandbox.maxConcurrentExecs)],
58
57
  ["created", date(sandbox.createdAt)],
59
58
  ["running", date(sandbox.runningAt)],
60
59
  ["finished", date(sandbox.finishedAt)],
61
60
  ["last active", date(sandbox.lastActiveAt)],
62
- ["expires", date(sandbox.expiresAt)],
63
61
  ["exit reason", sandbox.exitReason ?? ""]
64
62
  ];
65
63
  for (const endpoint of sandbox.endpoints ?? []) rows.push([`endpoint ${endpoint.port}`, endpoint.hostname]);
@@ -98,6 +96,7 @@ function parseCreateSandboxOptions(name, options) {
98
96
  memSizeMiB: optionalInteger(options.memSizeMib, "Memory", 256, 65536),
99
97
  baseImage: options.baseImage,
100
98
  maxTtlSeconds: optionalInteger(options.maxTtlSeconds, "Max TTL", 1, 2147483647),
99
+ idleTtlSeconds: optionalInteger(options.idleTtlSeconds, "Idle TTL", 0, 86400),
101
100
  maxConcurrentExecs: optionalInteger(options.maxConcurrentProcesses, "Max concurrent processes", 1, 1024),
102
101
  env: parseEnvironment(options.env)
103
102
  };
@@ -332,7 +331,7 @@ function createSandboxProgram(dependencies) {
332
331
  formatOption(program.command("get <id|name>").description("Show sandbox details")).action(async (target, options) => {
333
332
  output(formatSandbox(await resolveSandbox(requireService(), target), options.output));
334
333
  });
335
- waitOption(formatOption(program.command("create [name]").description("Create a sandbox"))).option("--vcpu-count <count>", "Virtual CPU count (1-32)").option("--mem-size-mib <mib>", "Memory in MiB (256-65536)").option("--base-image <image>", "Public OCI image", "ubuntu:26.04").option("--max-ttl-seconds <seconds>", "Maximum sandbox lifetime").option("--max-concurrent-processes <count>", "Maximum attached processes").option("--env <name=value>", "Set an environment variable (repeatable)", (value, previous) => [...previous, value], []).action(async (name, options) => {
334
+ waitOption(formatOption(program.command("create [name]").description("Create a sandbox"))).option("--vcpu-count <count>", "Virtual CPU count (1-32)").option("--mem-size-mib <mib>", "Memory in MiB (256-65536)").option("--base-image <image>", "Public OCI image", "ubuntu:26.04").option("--max-ttl-seconds <seconds>", "Maximum sandbox lifetime").option("--idle-ttl-seconds <seconds>", "Seconds without a process connection before pausing (0 disables)").option("--max-concurrent-processes <count>", "Maximum attached processes").option("--env <name=value>", "Set an environment variable (repeatable)", (value, previous) => [...previous, value], []).action(async (name, options) => {
336
335
  const sandbox = await withSpinner("Creating sandbox", options.wait, () => requireService().create(parseCreateSandboxOptions(name, options), { wait: options.wait }));
337
336
  output(formatSandbox(sandbox, options.output));
338
337
  });
@@ -122,7 +122,7 @@ function deriveS3BaseUrl(controlBaseUrl) {
122
122
  }
123
123
  //#endregion
124
124
  //#region src/version.ts
125
- const VERSION = "1.1.2";
125
+ const VERSION = "1.3.0";
126
126
  const USER_AGENT = `archil-js/${VERSION}`;
127
127
  //#endregion
128
128
  //#region src/client.ts
@@ -131,6 +131,49 @@ function isNodeRuntime() {
131
131
  return typeof process !== "undefined" && typeof process.versions?.node === "string";
132
132
  }
133
133
  const undiciModule = isNodeRuntime() ? import("undici") : void 0;
134
+ const CONTROL_PLANE_CONNECTIONS = 1;
135
+ const CONTROL_PLANE_CONCURRENT_STREAMS = 100;
136
+ function isAsyncIterableBody(body) {
137
+ return body != null && typeof body === "object" && Symbol.asyncIterator in body;
138
+ }
139
+ async function bufferBody(body) {
140
+ const chunks = [];
141
+ for await (const chunk of body) chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
142
+ return Buffer.concat(chunks);
143
+ }
144
+ const multiplexHttp2Requests = (dispatch) => (options, handler) => {
145
+ let requestStarted = false;
146
+ const guardedHandler = {
147
+ onRequestStart(controller, context) {
148
+ if (requestStarted) {
149
+ controller.abort(/* @__PURE__ */ new Error("Archil control-plane requests are not replayed after a connection failure"));
150
+ return;
151
+ }
152
+ requestStarted = true;
153
+ handler.onRequestStart?.(controller, context);
154
+ },
155
+ onRequestUpgrade: handler.onRequestUpgrade?.bind(handler),
156
+ onResponseStart: handler.onResponseStart?.bind(handler),
157
+ onResponseData: handler.onResponseData?.bind(handler),
158
+ onResponseEnd: handler.onResponseEnd?.bind(handler),
159
+ onResponseError: handler.onResponseError?.bind(handler)
160
+ };
161
+ const dispatchBody = (body) => dispatch({
162
+ ...options,
163
+ body,
164
+ idempotent: true
165
+ }, guardedHandler);
166
+ if (!isAsyncIterableBody(options.body)) return dispatchBody(options.body);
167
+ bufferBody(options.body).then(dispatchBody, (error) => handler.onResponseError?.({
168
+ aborted: false,
169
+ paused: false,
170
+ reason: null,
171
+ abort() {},
172
+ pause() {},
173
+ resume() {}
174
+ }, error instanceof Error ? error : new Error(String(error))));
175
+ return true;
176
+ };
134
177
  const sharedDispatchers = /* @__PURE__ */ new Map();
135
178
  function dispatcherKey(baseUrl, apiKey) {
136
179
  return `${new URL(baseUrl).origin}\0${apiKey}`;
@@ -144,10 +187,11 @@ function getSharedDispatcher(baseUrl, apiKey) {
144
187
  const { Agent } = await undiciModule;
145
188
  return new Agent({
146
189
  allowH2: true,
147
- connections: 100,
190
+ connections: CONTROL_PLANE_CONNECTIONS,
191
+ pipelining: CONTROL_PLANE_CONCURRENT_STREAMS,
148
192
  keepAliveTimeout: 6e4,
149
193
  keepAliveMaxTimeout: 6e5
150
- });
194
+ }).compose(multiplexHttp2Requests);
151
195
  })();
152
196
  sharedDispatchers.set(key, dispatcher);
153
197
  dispatcher.catch(() => {
@@ -1786,6 +1830,14 @@ function toError(error) {
1786
1830
  }
1787
1831
  //#endregion
1788
1832
  //#region src/sandbox.ts
1833
+ function portTokenFromWire(data) {
1834
+ return {
1835
+ id: data.id,
1836
+ port: data.port,
1837
+ createdAt: new Date(data.created_at),
1838
+ expiresAt: data.expires_at ? new Date(data.expires_at) : void 0
1839
+ };
1840
+ }
1789
1841
  const POLL_INTERVAL_MS = 500;
1790
1842
  function sleep() {
1791
1843
  return new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
@@ -1799,14 +1851,15 @@ var Sandbox = class Sandbox {
1799
1851
  baseImage;
1800
1852
  platform;
1801
1853
  maxTtlSeconds;
1854
+ idleTtlSeconds;
1802
1855
  maxConcurrentExecs;
1803
1856
  endpoints;
1804
1857
  createdAt;
1805
1858
  runningAt;
1806
1859
  finishedAt;
1807
1860
  lastActiveAt;
1808
- expiresAt;
1809
1861
  exitReason;
1862
+ checkpoint;
1810
1863
  processes;
1811
1864
  files;
1812
1865
  /** @internal */
@@ -1828,14 +1881,15 @@ var Sandbox = class Sandbox {
1828
1881
  this.baseImage = data.base_image;
1829
1882
  this.platform = data.platform;
1830
1883
  this.maxTtlSeconds = data.max_ttl_seconds;
1884
+ this.idleTtlSeconds = data.idle_ttl_seconds ?? 0;
1831
1885
  this.maxConcurrentExecs = data.max_concurrent_execs;
1832
1886
  this.endpoints = data.endpoints?.map((endpoint) => ({ ...endpoint }));
1833
1887
  this.createdAt = new Date(data.created_at);
1834
1888
  this.runningAt = data.running_at ? new Date(data.running_at) : void 0;
1835
1889
  this.finishedAt = data.finished_at ? new Date(data.finished_at) : void 0;
1836
1890
  this.lastActiveAt = new Date(data.last_active_at);
1837
- this.expiresAt = data.expires_at ? new Date(data.expires_at) : void 0;
1838
1891
  this.exitReason = data.exit_reason;
1892
+ this.checkpoint = data.checkpoint;
1839
1893
  return this;
1840
1894
  }
1841
1895
  toJSON() {
@@ -1848,14 +1902,15 @@ var Sandbox = class Sandbox {
1848
1902
  baseImage: this.baseImage,
1849
1903
  platform: this.platform,
1850
1904
  maxTtlSeconds: this.maxTtlSeconds,
1905
+ idleTtlSeconds: this.idleTtlSeconds,
1851
1906
  maxConcurrentExecs: this.maxConcurrentExecs,
1852
1907
  endpoints: this.endpoints?.map((endpoint) => ({ ...endpoint })),
1853
1908
  createdAt: this.createdAt,
1854
1909
  runningAt: this.runningAt,
1855
1910
  finishedAt: this.finishedAt,
1856
1911
  lastActiveAt: this.lastActiveAt,
1857
- expiresAt: this.expiresAt,
1858
- exitReason: this.exitReason
1912
+ exitReason: this.exitReason,
1913
+ checkpoint: this.checkpoint
1859
1914
  };
1860
1915
  }
1861
1916
  /** Run a process and wait for it to exit. */
@@ -1897,17 +1952,117 @@ var Sandbox = class Sandbox {
1897
1952
  this._apply(data);
1898
1953
  return options.wait === false ? this : waitForSandboxStart(this);
1899
1954
  }
1900
- /** Create an isolated writable branch from this sandbox's current state. */
1955
+ /**
1956
+ * Create an isolated writable branch from this sandbox's current state.
1957
+ * A running sandbox is paused for the snapshot and resumed once the fork is
1958
+ * accepted; a paused or stopped sandbox is left as it is. The fork names the
1959
+ * checkpoint the pause returned, so it does not depend on the source still
1960
+ * being paused when the request lands. Resuming the source is best effort:
1961
+ * the child is returned even if the source could not be resumed, so check
1962
+ * the source's status afterwards if that matters.
1963
+ */
1901
1964
  async fork(options = {}) {
1902
- const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/fork", {
1965
+ const paused = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/pause", { params: { path: { sid: this.id } } }), "transient"));
1966
+ this._apply(paused);
1967
+ const resumeAfterFork = this.status === "pausing";
1968
+ const checkpoint = this.checkpoint;
1969
+ const wait = resumeAfterFork ? false : options.wait ?? true;
1970
+ const body = {
1971
+ name: options.name,
1972
+ checkpoint
1973
+ };
1974
+ const fork = await waitWhileSandboxStatus(this, "pausing").then(() => unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/fork", {
1903
1975
  params: {
1904
1976
  path: { sid: this.id },
1905
- query: { wait: options.wait ?? true }
1977
+ query: { wait }
1906
1978
  },
1907
- body: options.name === void 0 ? void 0 : { name: options.name }
1979
+ body
1980
+ }), "connect"))).then((data) => new Sandbox(data, this._client)).finally(() => resumeAfterFork ? this.resume({ wait: false }).catch(() => void 0) : void 0);
1981
+ if (options.wait === false) return fork;
1982
+ await waitForSandboxStart(fork);
1983
+ if (resumeAfterFork) await waitForSandboxStart(this).catch(() => void 0);
1984
+ return fork;
1985
+ }
1986
+ /** Expose a TCP port publicly (1–65535), returning its hostname. */
1987
+ async exposePort(port) {
1988
+ const client = this._client;
1989
+ return (await unwrap(retryApiRequest(() => client.PUT("/api/sandboxes/{sid}/ports/{port}", { params: { path: {
1990
+ sid: this.id,
1991
+ port
1992
+ } } }), "transient"))).hostname;
1993
+ }
1994
+ /** List explicitly exposed public ports. Service-published ports are in `endpoints`. */
1995
+ async listPorts() {
1996
+ const client = this._client;
1997
+ return (await unwrap(retryApiRequest(() => client.GET("/api/sandboxes/{sid}/ports", { params: { path: { sid: this.id } } }), "transient"))).ports;
1998
+ }
1999
+ /** Remove explicit public exposure. A service publishing the same port remains reachable. */
2000
+ async unexposePort(port) {
2001
+ const client = this._client;
2002
+ await unwrapEmpty(retryApiRequest(() => client.DELETE("/api/sandboxes/{sid}/ports/{port}", { params: { path: {
2003
+ sid: this.id,
2004
+ port
2005
+ } } }), "transient"));
2006
+ }
2007
+ /** Authorize HTTP access to one port without making it public. */
2008
+ async createPortToken(port, options = {}) {
2009
+ const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/port-tokens", {
2010
+ params: { path: { sid: this.id } },
2011
+ body: {
2012
+ port,
2013
+ ttl: options.ttl
2014
+ }
1908
2015
  }), "connect"));
1909
- const fork = new Sandbox(data, this._client);
1910
- return options.wait === false ? fork : waitForSandboxStart(fork);
2016
+ return {
2017
+ ...portTokenFromWire(data),
2018
+ hostname: data.hostname,
2019
+ token: data.token
2020
+ };
2021
+ }
2022
+ /** Get token metadata. Expired and revoked tokens return not found. */
2023
+ async getPortToken(tokenId) {
2024
+ return portTokenFromWire(await unwrap(retryApiRequest(() => this._client.GET("/api/sandboxes/{sid}/port-tokens/{token_id}", { params: { path: {
2025
+ sid: this.id,
2026
+ token_id: tokenId
2027
+ } } }), "transient")));
2028
+ }
2029
+ /** List token metadata across pages. `limit` caps the total number returned. */
2030
+ async listPortTokens(options = {}) {
2031
+ const tokens = [];
2032
+ let cursor = options.cursor;
2033
+ for (;;) {
2034
+ const remaining = options.limit === void 0 ? void 0 : options.limit - tokens.length;
2035
+ if (remaining !== void 0 && remaining <= 0) return tokens;
2036
+ const page = await this.listPortTokensPage({
2037
+ limit: remaining === void 0 ? 100 : Math.min(remaining, 100),
2038
+ cursor
2039
+ });
2040
+ tokens.push(...page.tokens);
2041
+ if (!page.nextCursor) return tokens;
2042
+ cursor = page.nextCursor;
2043
+ }
2044
+ }
2045
+ /** Fetch one page of token metadata; pass `nextCursor` back as `cursor`. */
2046
+ async listPortTokensPage(options = {}) {
2047
+ const { data, nextCursor } = await unwrapPage(retryApiRequest(() => this._client.GET("/api/sandboxes/{sid}/port-tokens", { params: {
2048
+ path: { sid: this.id },
2049
+ query: {
2050
+ limit: options.limit ?? 100,
2051
+ cursor: options.cursor
2052
+ }
2053
+ } }), "transient"));
2054
+ return {
2055
+ tokens: data.tokens.map(portTokenFromWire),
2056
+ nextCursor
2057
+ };
2058
+ }
2059
+ /** Revoke a token for new connections. Existing connections remain open. */
2060
+ async deletePortToken(token) {
2061
+ const tokenId = typeof token === "string" ? token : token.id;
2062
+ await unwrapEmpty(retryApiRequest(() => this._client.DELETE("/api/sandboxes/{sid}/port-tokens/{token_id}", { params: { path: {
2063
+ sid: this.id,
2064
+ token_id: tokenId
2065
+ } } }), "transient"));
1911
2066
  }
1912
2067
  /** Get this running sandbox's effective network policy. */
1913
2068
  async getNetwork() {
@@ -1922,6 +2077,19 @@ var Sandbox = class Sandbox {
1922
2077
  body: network
1923
2078
  }), "transient"));
1924
2079
  }
2080
+ /** Update either or both TTLs in seconds. Omitted settings remain unchanged. */
2081
+ async setTimeout(timeout) {
2082
+ const options = typeof timeout === "number" ? { timeoutSeconds: timeout } : timeout;
2083
+ const client = this._client;
2084
+ const data = await unwrap(retryApiRequest(() => client.POST("/api/sandboxes/{sid}/timeout", {
2085
+ params: { path: { sid: this.id } },
2086
+ body: {
2087
+ timeout: options.timeoutSeconds,
2088
+ idle_ttl_seconds: options.idleTtlSeconds
2089
+ }
2090
+ }), "transient"));
2091
+ return this._apply(data);
2092
+ }
1925
2093
  /** Delete this sandbox and its backing disk. */
1926
2094
  async delete() {
1927
2095
  await unwrapEmpty(retryApiRequest(() => this._client.DELETE("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }), "transient"));
@@ -1963,8 +2131,10 @@ var Sandboxes = class {
1963
2131
  base_image: request.baseImage,
1964
2132
  env: request.env,
1965
2133
  max_ttl_seconds: request.maxTtlSeconds,
2134
+ idle_ttl_seconds: request.idleTtlSeconds,
1966
2135
  max_concurrent_execs: request.maxConcurrentExecs,
1967
- network: request.network
2136
+ network: request.network,
2137
+ ports: request.ports
1968
2138
  };
1969
2139
  const sandbox = new Sandbox(await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes", {
1970
2140
  params: { query: { wait: options.wait ?? true } },
@@ -1992,7 +2162,7 @@ var Tokens = class {
1992
2162
  return await unwrap(this._client.POST("/api/tokens", { body: req }));
1993
2163
  }
1994
2164
  async delete(id) {
1995
- await unwrapEmpty(this._client.DELETE("/api/tokens/{id}", { params: { path: { id } } }));
2165
+ await unwrapEmpty(this._client.DELETE("/api/tokens/{tokenId}", { params: { path: { tokenId: id } } }));
1996
2166
  }
1997
2167
  };
1998
2168
  //#endregion
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "disk",
3
- "version": "1.1.2",
3
+ "version": "1.3.0",
4
4
  "description": "Pure-JS client and CLIs for Archil disks and sandboxes",
5
5
  "keywords": [
6
6
  "archil",
@@ -40,7 +40,7 @@
40
40
  "LICENSE"
41
41
  ],
42
42
  "dependencies": {
43
- "@archildata/api-types": "^0.0.24",
43
+ "@archildata/api-types": "^0.0.40",
44
44
  "@clack/prompts": "^1.7.0",
45
45
  "commander": "^14.0.3",
46
46
  "fast-xml-parser": "^5.7.0",