@cloudflare/sandbox 0.12.1 → 0.13.0-next.632.1

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,5 +1,5 @@
1
1
  import { Container, ContainerProxy } from "@cloudflare/containers";
2
- import "capnweb";
2
+ import { RpcTarget } from "capnweb";
3
3
 
4
4
  //#region ../shared/dist/logger/types.d.ts
5
5
 
@@ -688,7 +688,6 @@ interface SessionOptions {
688
688
  */
689
689
  commandTimeoutMs?: number;
690
690
  }
691
- type SandboxTransport = 'http' | 'websocket' | 'rpc';
692
691
  interface SandboxOptions {
693
692
  /**
694
693
  * Duration after which the sandbox instance will sleep if no requests are received
@@ -786,25 +785,6 @@ interface SandboxOptions {
786
785
  */
787
786
  waitIntervalMS?: number;
788
787
  };
789
- /**
790
- * Transport/control path for communication between the Sandbox DO and the
791
- * container runtime.
792
- *
793
- * - `"http"` (default): Route-based HTTP compatibility path.
794
- * - `"websocket"`: Route-based compatibility path multiplexed over a custom
795
- * WebSocket connection.
796
- * - `"rpc"`: Primary container-control path over capnweb RPC.
797
- *
798
- * When set via `getSandbox()` options, this overrides the `SANDBOX_TRANSPORT` env var.
799
- *
800
- * **Important:** Set this once at creation time and pass the same value on every
801
- * subsequent `getSandbox()` call for a given sandbox ID. Changing the transport after
802
- * the sandbox is in use disconnects the active client, which drops any in-flight
803
- * requests and resets WebSocket connections.
804
- *
805
- * @default "http"
806
- */
807
- transport?: SandboxTransport;
808
788
  }
809
789
  /**
810
790
  * Execution session - isolated execution context within a sandbox
@@ -829,7 +809,7 @@ interface WriteFileResult {
829
809
  *
830
810
  * - `'utf-8'` / `'utf8'` — treat content as text.
831
811
  * - `'base64'` — treat content as base64-encoded binary.
832
- * - `'none'` — RPC-only streaming variant of `readFile`, returns a
812
+ * - `'none'` — streaming variant of `readFile`, returns a
833
813
  * `ReadableStream<Uint8Array>` of raw bytes (see `ReadFileStreamResult`).
834
814
  */
835
815
  type FileEncoding = 'utf-8' | 'utf8' | 'base64' | 'none';
@@ -857,11 +837,10 @@ interface ReadFileResult {
857
837
  size?: number;
858
838
  }
859
839
  /**
860
- * Result of `readFile()` with `encoding: 'none'` on the RPC transport.
840
+ * Result of `readFile()` with `encoding: 'none'`.
861
841
  *
862
842
  * `content` is a raw binary `ReadableStream<Uint8Array>` delivered directly
863
843
  * over the capnp channel — no base64 encoding, no SSE framing, no buffering.
864
- * Only supported on the `rpc` transport; HTTP/WebSocket transports throw.
865
844
  */
866
845
  interface ReadFileStreamResult {
867
846
  success: true;
@@ -1456,79 +1435,6 @@ declare function isProcess(value: any): value is Process;
1456
1435
  declare function isProcessStatus(value: string): value is ProcessStatus;
1457
1436
  //#endregion
1458
1437
  //#region ../shared/dist/request-types.d.ts
1459
- /**
1460
- * Request types for API calls to the container
1461
- * Single source of truth for the contract between SDK clients and container handlers
1462
- */
1463
- /**
1464
- * Request to execute a command
1465
- */
1466
- interface ExecuteRequest {
1467
- command: string;
1468
- sessionId?: string;
1469
- background?: boolean;
1470
- timeoutMs?: number;
1471
- env?: Record<string, string | undefined>;
1472
- cwd?: string;
1473
- origin?: 'user' | 'internal';
1474
- }
1475
- /**
1476
- * Request to start a background process
1477
- * Uses flat structure consistent with other endpoints
1478
- */
1479
- interface StartProcessRequest {
1480
- command: string;
1481
- sessionId?: string;
1482
- processId?: string;
1483
- timeoutMs?: number;
1484
- env?: Record<string, string | undefined>;
1485
- cwd?: string;
1486
- encoding?: string;
1487
- autoCleanup?: boolean;
1488
- origin?: 'user' | 'internal';
1489
- }
1490
- /**
1491
- * Request to create a backup archive from a directory.
1492
- * The container creates a squashfs archive at archivePath.
1493
- * The DO then reads it and uploads to R2.
1494
- */
1495
- interface CreateBackupRequest {
1496
- /** Directory to back up */
1497
- dir: string;
1498
- /** Path where the container should write the archive */
1499
- archivePath: string;
1500
- /** Respect git ignore rules when the directory is inside a git repository */
1501
- gitignore?: boolean;
1502
- /** Glob patterns to exclude from the backup */
1503
- excludes?: string[];
1504
- compression?: BackupCompressionOptions;
1505
- sessionId?: string;
1506
- }
1507
- /**
1508
- * A single part to upload in a multipart upload.
1509
- * The container reads the byte range from the local archive and PUTs it
1510
- * to the presigned URL.
1511
- */
1512
- interface UploadPart {
1513
- partNumber: number;
1514
- /** Presigned PUT URL for this part */
1515
- url: string;
1516
- /** Byte offset within the archive file */
1517
- offset: number;
1518
- /** Number of bytes in this part */
1519
- size: number;
1520
- }
1521
- /**
1522
- * Request to upload parts of a backup archive directly from the container to R2.
1523
- * Used for parallel multipart upload of large archives.
1524
- */
1525
- interface UploadPartsRequest {
1526
- /** Path to the archive file in the container */
1527
- archivePath: string;
1528
- /** Parts to upload in parallel */
1529
- parts: UploadPart[];
1530
- sessionId?: string;
1531
- }
1532
1438
  /**
1533
1439
  * Result for a single uploaded part (ETag returned by R2).
1534
1440
  */
@@ -1756,693 +1662,23 @@ interface SandboxTunnelsAPI {
1756
1662
  /** List tunnels currently running inside the container. */
1757
1663
  listTunnels(): Promise<TunnelInfo[]>;
1758
1664
  }
1759
- //#endregion
1760
- //#region src/clients/types.d.ts
1761
1665
  /**
1762
- * Minimal interface for container fetch functionality
1763
- */
1764
- interface ContainerStub {
1765
- containerFetch(url: string, options: RequestInit, port?: number): Promise<Response>;
1766
- /**
1767
- * Fetch that can handle WebSocket upgrades (routes through parent Container class).
1768
- * Required for WebSocket transport to establish control plane connections.
1769
- */
1770
- fetch(request: Request): Promise<Response>;
1771
- }
1772
- /**
1773
- * Shared HTTP client configuration options
1774
- */
1775
- interface HttpClientOptions {
1776
- logger?: Logger;
1777
- baseUrl?: string;
1778
- port?: number;
1779
- stub?: ContainerStub;
1780
- onCommandComplete?: (success: boolean, exitCode: number, stdout: string, stderr: string, command: string) => void;
1781
- onError?: (error: string, command?: string) => void;
1782
- /**
1783
- * Route-based transport mode: 'http' (default) or 'websocket'.
1784
- * WebSocket mode multiplexes HTTP API requests over a single connection.
1785
- */
1786
- transportMode?: RouteTransportMode;
1787
- /**
1788
- * WebSocket URL for WebSocket transport mode.
1789
- * Required when transportMode is 'websocket'.
1790
- */
1791
- wsUrl?: string;
1792
- /**
1793
- * Shared transport instance (for internal use).
1794
- * When provided, clients will use this transport instead of creating their own.
1795
- */
1796
- transport?: ITransport;
1797
- /**
1798
- * Total retry budget in milliseconds for retryable transport responses.
1799
- * Used for WebSocket upgrade retries and HTTP 503 startup retries.
1800
- * Passed through to the transport layer. Defaults to 120_000 (2 minutes).
1801
- */
1802
- retryTimeoutMs?: number;
1803
- /**
1804
- * Headers merged into every outgoing container request.
1805
- * Used to propagate stable context (e.g. sandboxId) from the Durable Object
1806
- * to the container so container logs carry the same identifiers as DO logs.
1807
- */
1808
- defaultHeaders?: Record<string, string>;
1809
- }
1810
- /**
1811
- * Base response interface for all API responses
1812
- */
1813
- interface BaseApiResponse {
1814
- success: boolean;
1815
- timestamp: string;
1816
- }
1817
- /**
1818
- * Legacy error response interface - deprecated, use ApiErrorResponse
1819
- */
1820
- interface ErrorResponse {
1821
- error: string;
1822
- details?: string;
1823
- code?: string;
1824
- }
1825
- /**
1826
- * HTTP request configuration
1827
- */
1828
- interface RequestConfig extends RequestInit {
1829
- endpoint: string;
1830
- data?: Record<string, any>;
1831
- }
1832
- /**
1833
- * Typed response handler
1834
- */
1835
- type ResponseHandler<T> = (response: Response) => Promise<T>;
1836
- /**
1837
- * Common session-aware request interface
1838
- */
1839
- interface SessionRequest {
1840
- sessionId?: string;
1841
- }
1842
- //#endregion
1843
- //#region src/clients/transport/types.d.ts
1844
- /**
1845
- * Transport modes supported by the route-based compatibility layer.
1846
- */
1847
- type RouteTransportMode = 'http' | 'websocket';
1848
- interface TransportRequestInit extends RequestInit {
1849
- /** Override the non-streaming request timeout for this single request. */
1850
- requestTimeoutMs?: number;
1851
- }
1852
- /**
1853
- * Route transport interface.
1666
+ * RPC surface the Sandbox DO exposes to the container over the existing
1667
+ * capnweb session. The container reaches it via
1668
+ * `session.getRemoteMain<SandboxControlCallback>()` and invokes methods
1669
+ * to push control-plane events (today: tunnel exits) back to the DO.
1854
1670
  *
1855
- * Provides a unified abstraction over the route-based HTTP and custom
1856
- * WebSocket compatibility paths. Both transports support fetch-compatible
1857
- * requests and streaming.
1671
+ * One stable target per sandbox; not per-tunnel. Reusable seam for
1672
+ * future container→DO events.
1858
1673
  */
1859
- interface ITransport {
1860
- /**
1861
- * Make a fetch-compatible request
1862
- * @returns Standard Response object
1863
- */
1864
- fetch(path: string, options?: TransportRequestInit): Promise<Response>;
1865
- /**
1866
- * Make a streaming request
1867
- * @returns ReadableStream for consuming SSE/streaming data
1868
- */
1869
- fetchStream(path: string, body?: unknown, method?: 'GET' | 'POST', headers?: Record<string, string>): Promise<ReadableStream<Uint8Array>>;
1674
+ interface SandboxControlCallback {
1870
1675
  /**
1871
- * Get the transport mode
1676
+ * Called by the container when a `cloudflared` process exits for any
1677
+ * reason — SIGTERM from `destroyTunnel`, container-initiated SIGKILL,
1678
+ * network failure, segfault. `exitCode` is `null` if the process was
1679
+ * signalled rather than exited cleanly.
1872
1680
  */
1873
- getMode(): RouteTransportMode;
1874
- /**
1875
- * Connect the transport (no-op for HTTP)
1876
- */
1877
- connect(): Promise<void>;
1878
- /**
1879
- * Disconnect the transport (no-op for HTTP)
1880
- */
1881
- disconnect(): void;
1882
- /**
1883
- * Check if connected (always true for HTTP)
1884
- */
1885
- isConnected(): boolean;
1886
- /**
1887
- * Update the upgrade retry budget without recreating the transport
1888
- */
1889
- setRetryTimeoutMs(ms: number): void;
1890
- }
1891
- //#endregion
1892
- //#region src/clients/base-client.d.ts
1893
- /**
1894
- * Abstract base class for route-based HTTP/WebSocket compatibility clients.
1895
- *
1896
- * Requests go through the Transport abstraction layer, which handles:
1897
- * - HTTP and WebSocket route-based modes transparently
1898
- * - Automatic retry for 503 errors while the container is starting
1899
- * - Streaming responses for the existing route API
1900
- *
1901
- * DO-to-container control-channel capabilities live in `container-control/`.
1902
- * This layer supports the route-based compatibility API.
1903
- */
1904
- declare abstract class BaseHttpClient {
1905
- protected options: HttpClientOptions;
1906
- protected logger: Logger;
1907
- protected transport: ITransport;
1908
- constructor(options?: HttpClientOptions);
1909
- /**
1910
- * Update the transport's 503 retry budget
1911
- */
1912
- setRetryTimeoutMs(ms: number): void;
1913
- /**
1914
- * Check if using WebSocket transport
1915
- */
1916
- protected isWebSocketMode(): boolean;
1917
- /**
1918
- * Core fetch method - delegates to Transport which handles retry logic
1919
- */
1920
- protected doFetch(path: string, options?: TransportRequestInit): Promise<Response>;
1921
- /**
1922
- * Make a POST request with JSON body
1923
- */
1924
- protected post<T>(endpoint: string, data: unknown, responseHandler?: ResponseHandler<T>, requestOptions?: Pick<TransportRequestInit, 'requestTimeoutMs'>): Promise<T>;
1925
- /**
1926
- * Make a GET request
1927
- */
1928
- protected get<T>(endpoint: string, responseHandler?: ResponseHandler<T>): Promise<T>;
1929
- /**
1930
- * Make a DELETE request
1931
- */
1932
- protected delete<T>(endpoint: string, responseHandler?: ResponseHandler<T>): Promise<T>;
1933
- /**
1934
- * Handle HTTP response with error checking and parsing
1935
- */
1936
- protected handleResponse<T>(response: Response, customHandler?: ResponseHandler<T>): Promise<T>;
1937
- /**
1938
- * Handle error responses with consistent error throwing
1939
- */
1940
- protected handleErrorResponse(response: Response): Promise<never>;
1941
- /**
1942
- * Create a streaming response handler for Server-Sent Events
1943
- */
1944
- protected handleStreamResponse(response: Response): Promise<ReadableStream<Uint8Array>>;
1945
- /**
1946
- * Stream request handler
1947
- *
1948
- * HTTP mode uses doFetch + handleStreamResponse for typed error handling.
1949
- * For WebSocket mode, uses Transport's streaming support.
1950
- *
1951
- * @param path - The API path to call
1952
- * @param body - Optional request body (for POST requests)
1953
- * @param method - HTTP method (default: POST, use GET for process logs)
1954
- */
1955
- protected doStreamFetch(path: string, body?: unknown, method?: 'GET' | 'POST'): Promise<ReadableStream<Uint8Array>>;
1956
- }
1957
- //#endregion
1958
- //#region src/clients/backup-client.d.ts
1959
- /**
1960
- * Client for backup operations.
1961
- *
1962
- * Handles communication with the container's backup endpoints.
1963
- * The container creates/extracts squashfs archives locally.
1964
- * R2 upload/download is handled by the Sandbox DO, not by this client.
1965
- */
1966
- declare class BackupClient extends BaseHttpClient implements SandboxBackupAPI {
1967
- /**
1968
- * Tell the container to create a squashfs archive from a directory.
1969
- * @param dir - Directory to back up
1970
- * @param archivePath - Where the container should write the archive
1971
- * @param sessionId - Session context
1972
- */
1973
- createArchive(dir: string, archivePath: string, sessionId: string, options?: {
1974
- excludes?: string[];
1975
- gitignore?: boolean;
1976
- compression?: CreateBackupRequest['compression'];
1977
- }): Promise<CreateBackupResponse>;
1978
- /**
1979
- * Tell the container to restore a squashfs archive into a directory.
1980
- * @param dir - Target directory
1981
- * @param archivePath - Path to the archive file in the container
1982
- * @param sessionId - Session context
1983
- */
1984
- restoreArchive(dir: string, archivePath: string, sessionId: string): Promise<RestoreBackupResponse>;
1985
- uploadParts(request: UploadPartsRequest, sessionId?: string): Promise<UploadPartsResponse>;
1986
- }
1987
- //#endregion
1988
- //#region src/clients/command-client.d.ts
1989
- /**
1990
- * Response interface for command execution
1991
- */
1992
- interface ExecuteResponse extends BaseApiResponse {
1993
- stdout: string;
1994
- stderr: string;
1995
- exitCode: number;
1996
- command: string;
1997
- }
1998
- /**
1999
- * Client for command execution operations
2000
- */
2001
- declare class CommandClient extends BaseHttpClient implements SandboxCommandsAPI {
2002
- /**
2003
- * Execute a command and return the complete result
2004
- * @param command - The command to execute
2005
- * @param sessionId - The session ID for this command execution
2006
- * @param timeoutMs - Optional timeout in milliseconds (unlimited by default)
2007
- * @param env - Optional environment variables for this command
2008
- * @param cwd - Optional working directory for this command
2009
- */
2010
- execute(command: string, sessionId: string, options?: {
2011
- timeoutMs?: number;
2012
- env?: Record<string, string | undefined>;
2013
- cwd?: string;
2014
- origin?: 'user' | 'internal';
2015
- }): Promise<ExecuteResponse>;
2016
- /**
2017
- * Execute a command and return a stream of events
2018
- * @param command - The command to execute
2019
- * @param sessionId - The session ID for this command execution
2020
- * @param options - Optional per-command execution settings
2021
- */
2022
- executeStream(command: string, sessionId: string, options?: {
2023
- timeoutMs?: number;
2024
- env?: Record<string, string | undefined>;
2025
- cwd?: string;
2026
- origin?: 'user' | 'internal';
2027
- }): Promise<ReadableStream<Uint8Array>>;
2028
- }
2029
- //#endregion
2030
- //#region src/clients/file-client.d.ts
2031
- /**
2032
- * Request interface for creating directories
2033
- */
2034
- interface MkdirRequest extends SessionRequest {
2035
- path: string;
2036
- recursive?: boolean;
2037
- }
2038
- /**
2039
- * Request interface for writing files
2040
- */
2041
- interface WriteFileRequest extends SessionRequest {
2042
- path: string;
2043
- content: string;
2044
- encoding?: string;
2045
- }
2046
- /**
2047
- * Request interface for reading files
2048
- */
2049
- interface ReadFileRequest extends SessionRequest {
2050
- path: string;
2051
- encoding?: string;
2052
- }
2053
- /**
2054
- * Request interface for file operations (delete, rename, move)
2055
- */
2056
- interface FileOperationRequest extends SessionRequest {
2057
- path: string;
2058
- newPath?: string;
2059
- }
2060
- /**
2061
- * Client for file system operations
2062
- */
2063
- declare class FileClient extends BaseHttpClient implements SandboxFilesAPI {
2064
- /**
2065
- * Create a directory
2066
- * @param path - Directory path to create
2067
- * @param sessionId - The session ID for this operation
2068
- * @param options - Optional settings (recursive)
2069
- */
2070
- mkdir(path: string, sessionId: string, options?: {
2071
- recursive?: boolean;
2072
- }): Promise<MkdirResult>;
2073
- /**
2074
- * Write content to a file
2075
- * @param path - File path to write to
2076
- * @param content - Content to write
2077
- * @param sessionId - The session ID for this operation
2078
- * @param options - Optional settings (encoding)
2079
- */
2080
- writeFile(path: string, content: string, sessionId: string, options?: {
2081
- encoding?: string;
2082
- }): Promise<WriteFileResult>;
2083
- /**
2084
- * Read content from a file.
2085
- *
2086
- * @param path - File path to read from
2087
- * @param sessionId - The session ID for this operation
2088
- * @param options - Optional settings (encoding)
2089
- *
2090
- * When `encoding` is `'none'`, returns a `ReadFileStreamResult` whose
2091
- * `content` is a raw `ReadableStream<Uint8Array>`. This variant only works
2092
- * on the `rpc` transport; HTTP and WebSocket transports throw at runtime.
2093
- */
2094
- readFile(path: string, sessionId: string, options: {
2095
- encoding: 'none';
2096
- }): Promise<ReadFileStreamResult>;
2097
- readFile(path: string, sessionId: string, options?: {
2098
- encoding?: Exclude<FileEncoding, 'none'>;
2099
- }): Promise<ReadFileResult>;
2100
- /**
2101
- * Stream a file using Server-Sent Events
2102
- * Returns a ReadableStream of SSE events containing metadata, chunks, and completion
2103
- * @param path - File path to stream
2104
- * @param sessionId - The session ID for this operation
2105
- */
2106
- readFileStream(path: string, sessionId: string): Promise<ReadableStream<Uint8Array>>;
2107
- /**
2108
- * Delete a file
2109
- * @param path - File path to delete
2110
- * @param sessionId - The session ID for this operation
2111
- */
2112
- deleteFile(path: string, sessionId: string): Promise<DeleteFileResult>;
2113
- /**
2114
- * Rename a file
2115
- * @param path - Current file path
2116
- * @param newPath - New file path
2117
- * @param sessionId - The session ID for this operation
2118
- */
2119
- renameFile(path: string, newPath: string, sessionId: string): Promise<RenameFileResult>;
2120
- /**
2121
- * Move a file
2122
- * @param path - Current file path
2123
- * @param newPath - Destination file path
2124
- * @param sessionId - The session ID for this operation
2125
- */
2126
- moveFile(path: string, newPath: string, sessionId: string): Promise<MoveFileResult>;
2127
- /**
2128
- * List files in a directory
2129
- * @param path - Directory path to list
2130
- * @param sessionId - The session ID for this operation
2131
- * @param options - Optional settings (recursive, includeHidden)
2132
- */
2133
- listFiles(path: string, sessionId: string, options?: ListFilesOptions): Promise<ListFilesResult>;
2134
- /**
2135
- * Check if a file or directory exists
2136
- * @param path - Path to check
2137
- * @param sessionId - The session ID for this operation
2138
- */
2139
- exists(path: string, sessionId: string): Promise<FileExistsResult>;
2140
- /**
2141
- * Write a file via a raw binary stream over the RPC transport.
2142
- * Throws on HTTP and WebSocket transports — use writeFile() with a string instead.
2143
- */
2144
- writeFileStream(_path: string, _content: ReadableStream<Uint8Array>, _sessionId: string): Promise<{
2145
- success: boolean;
2146
- path: string;
2147
- bytesWritten: number;
2148
- timestamp: string;
2149
- }>;
2150
- }
2151
- //#endregion
2152
- //#region src/clients/git-client.d.ts
2153
- /**
2154
- * Request interface for Git checkout operations
2155
- */
2156
- interface GitCheckoutRequest extends SessionRequest {
2157
- repoUrl: string;
2158
- branch?: string;
2159
- targetDir?: string;
2160
- /** Clone depth for shallow clones (e.g., 1 for latest commit only) */
2161
- depth?: number;
2162
- /** Maximum wall-clock time for the git clone subprocess in milliseconds */
2163
- timeoutMs?: number;
2164
- }
2165
- /**
2166
- * Client for Git repository operations
2167
- */
2168
- declare class GitClient extends BaseHttpClient implements SandboxGitAPI {
2169
- private static readonly REQUEST_TIMEOUT_BUFFER_MS;
2170
- constructor(options?: HttpClientOptions);
2171
- /**
2172
- * Clone a Git repository
2173
- * @param repoUrl - URL of the Git repository to clone
2174
- * @param sessionId - The session ID for this operation
2175
- * @param options - Optional settings (branch, targetDir, depth, timeoutMs)
2176
- */
2177
- checkout(repoUrl: string, sessionId: string, options?: {
2178
- branch?: string;
2179
- targetDir?: string;
2180
- /** Clone depth for shallow clones (e.g., 1 for latest commit only) */
2181
- depth?: number;
2182
- /** Maximum wall-clock time for the git clone subprocess in milliseconds */
2183
- timeoutMs?: number;
2184
- }): Promise<GitCheckoutResult>;
2185
- }
2186
- //#endregion
2187
- //#region src/clients/interpreter-client.d.ts
2188
- interface ExecutionCallbacks {
2189
- onStdout?: (output: OutputMessage) => void | Promise<void>;
2190
- onStderr?: (output: OutputMessage) => void | Promise<void>;
2191
- onResult?: (result: Result) => void | Promise<void>;
2192
- onError?: (error: ExecutionError) => void | Promise<void>;
2193
- }
2194
- declare class InterpreterClient extends BaseHttpClient implements SandboxInterpreterAPI {
2195
- private readonly maxRetries;
2196
- private readonly retryDelayMs;
2197
- createCodeContext(options?: CreateContextOptions): Promise<CodeContext>;
2198
- runCodeStream(contextId: string | undefined, code: string, language: string | undefined, callbacks: ExecutionCallbacks, timeoutMs?: number): Promise<void>;
2199
- listCodeContexts(): Promise<CodeContext[]>;
2200
- deleteCodeContext(contextId: string): Promise<void>;
2201
- /**
2202
- * Get a raw stream for code execution.
2203
- * Used by CodeInterpreter.runCodeStreaming() for direct stream access.
2204
- */
2205
- streamCode(contextId: string, code: string, language?: string): Promise<ReadableStream<Uint8Array>>;
2206
- /**
2207
- * Execute an operation with automatic retry for transient errors
2208
- */
2209
- private executeWithRetry;
2210
- private isRetryableError;
2211
- private parseErrorResponse;
2212
- private readLines;
2213
- private parseExecutionResult;
2214
- }
2215
- //#endregion
2216
- //#region src/clients/port-client.d.ts
2217
- /**
2218
- * Client for port readiness operations.
2219
- */
2220
- declare class PortClient extends BaseHttpClient {
2221
- /**
2222
- * Watch a port for readiness via SSE stream
2223
- * @param request - Port watch configuration
2224
- * @returns SSE stream that emits PortWatchEvent objects
2225
- */
2226
- watchPort(request: PortWatchRequest): Promise<ReadableStream<Uint8Array>>;
2227
- }
2228
- //#endregion
2229
- //#region src/clients/process-client.d.ts
2230
- /**
2231
- * Client for background process management
2232
- */
2233
- declare class ProcessClient extends BaseHttpClient implements SandboxProcessesAPI {
2234
- /**
2235
- * Start a background process
2236
- * @param command - Command to execute as a background process
2237
- * @param sessionId - The session ID for this operation
2238
- * @param options - Optional settings (processId)
2239
- */
2240
- startProcess(command: string, sessionId: string, options?: {
2241
- processId?: string;
2242
- timeoutMs?: number;
2243
- env?: Record<string, string | undefined>;
2244
- cwd?: string;
2245
- encoding?: string;
2246
- autoCleanup?: boolean;
2247
- origin?: 'user' | 'internal';
2248
- }): Promise<ProcessStartResult>;
2249
- /**
2250
- * List all processes (sandbox-scoped, not session-scoped)
2251
- */
2252
- listProcesses(): Promise<ProcessListResult>;
2253
- /**
2254
- * Get information about a specific process (sandbox-scoped, not session-scoped)
2255
- * @param processId - ID of the process to retrieve
2256
- */
2257
- getProcess(processId: string): Promise<ProcessInfoResult>;
2258
- /**
2259
- * Kill a specific process (sandbox-scoped, not session-scoped)
2260
- * @param processId - ID of the process to kill
2261
- */
2262
- killProcess(processId: string): Promise<ProcessKillResult>;
2263
- /**
2264
- * Kill all running processes (sandbox-scoped, not session-scoped)
2265
- */
2266
- killAllProcesses(): Promise<ProcessCleanupResult>;
2267
- /**
2268
- * Get logs from a specific process (sandbox-scoped, not session-scoped)
2269
- * @param processId - ID of the process to get logs from
2270
- */
2271
- getProcessLogs(processId: string): Promise<ProcessLogsResult>;
2272
- /**
2273
- * Stream logs from a specific process (sandbox-scoped, not session-scoped)
2274
- * @param processId - ID of the process to stream logs from
2275
- */
2276
- streamProcessLogs(processId: string): Promise<ReadableStream<Uint8Array>>;
2277
- }
2278
- //#endregion
2279
- //#region src/clients/utility-client.d.ts
2280
- /**
2281
- * Response interface for ping operations
2282
- */
2283
- interface PingResponse extends BaseApiResponse {
2284
- message: string;
2285
- uptime?: number;
2286
- }
2287
- /**
2288
- * Response interface for getting available commands
2289
- */
2290
- interface CommandsResponse extends BaseApiResponse {
2291
- availableCommands: string[];
2292
- count: number;
2293
- }
2294
- /**
2295
- * Request interface for creating sessions
2296
- */
2297
- interface CreateSessionRequest {
2298
- id: string;
2299
- env?: Record<string, string | undefined>;
2300
- cwd?: string;
2301
- commandTimeoutMs?: number;
2302
- }
2303
- /**
2304
- * Response interface for creating sessions.
2305
- *
2306
- * `containerPlacementId` carries the container's `CLOUDFLARE_PLACEMENT_ID` at session
2307
- * creation time so the DO can capture it without a separate request. It is
2308
- * `null` when the environment variable is not set, such as in local dev.
2309
- */
2310
- interface CreateSessionResponse extends BaseApiResponse {
2311
- id: string;
2312
- message: string;
2313
- containerPlacementId?: string | null;
2314
- }
2315
- /**
2316
- * Request interface for deleting sessions
2317
- */
2318
- interface DeleteSessionRequest {
2319
- sessionId: string;
2320
- }
2321
- /**
2322
- * Response interface for deleting sessions
2323
- */
2324
- interface DeleteSessionResponse extends BaseApiResponse {
2325
- sessionId: string;
2326
- }
2327
- /**
2328
- * Client for health checks and utility operations
2329
- */
2330
- declare class UtilityClient extends BaseHttpClient implements SandboxUtilsAPI {
2331
- /**
2332
- * Ping the sandbox to check if it's responsive
2333
- */
2334
- ping(): Promise<string>;
2335
- /**
2336
- * Get list of available commands in the sandbox environment
2337
- */
2338
- getCommands(): Promise<string[]>;
2339
- /**
2340
- * Create a new execution session
2341
- * @param options - Session configuration (id, env, cwd)
2342
- */
2343
- createSession(options: CreateSessionRequest): Promise<CreateSessionResponse>;
2344
- /**
2345
- * Delete an execution session
2346
- * @param sessionId - Session ID to delete
2347
- */
2348
- deleteSession(sessionId: string): Promise<DeleteSessionResponse>;
2349
- /**
2350
- * Get the container version
2351
- * Returns the version embedded in the Docker image during build
2352
- */
2353
- getVersion(): Promise<string>;
2354
- listSessions(): Promise<{
2355
- sessions: string[];
2356
- }>;
2357
- }
2358
- //#endregion
2359
- //#region src/clients/watch-client.d.ts
2360
- /**
2361
- * Client for file watch operations
2362
- * Uses inotify under the hood for native filesystem event notifications
2363
- *
2364
- * @internal This client is used internally by the SDK.
2365
- * Users should use `sandbox.watch()` or `sandbox.checkChanges()` instead.
2366
- */
2367
- declare class WatchClient extends BaseHttpClient implements SandboxWatchAPI {
2368
- /**
2369
- * Check whether a path changed since a previously returned version.
2370
- */
2371
- checkChanges(request: CheckChangesRequest): Promise<CheckChangesResult>;
2372
- /**
2373
- * Start watching a directory for changes.
2374
- * The returned promise resolves only after the watcher is established
2375
- * on the filesystem (i.e. the `watching` SSE event has been received).
2376
- * The returned stream still contains the `watching` event so consumers
2377
- * using `parseSSEStream` will see the full event sequence.
2378
- *
2379
- * @param request - Watch request with path and options
2380
- */
2381
- watch(request: WatchRequest): Promise<ReadableStream<Uint8Array>>;
2382
- /**
2383
- * Read SSE chunks until the `watching` event appears, then return a
2384
- * wrapper stream that replays the buffered chunks followed by the
2385
- * remaining original stream data.
2386
- */
2387
- private waitForReadiness;
2388
- }
2389
- //#endregion
2390
- //#region src/clients/sandbox-client.d.ts
2391
- /**
2392
- * Route-based compatibility sandbox client that composes all domain-specific
2393
- * HTTP API clients.
2394
- *
2395
- * This client supports the route-based HTTP and custom WebSocket transports.
2396
- * The primary DO-to-container control path is ContainerControlClient under
2397
- * `container-control/`. This client supports route-based compatibility,
2398
- * debugging, local development, and fallback behavior.
2399
- */
2400
- declare class SandboxClient {
2401
- readonly backup: BackupClient;
2402
- readonly commands: CommandClient;
2403
- readonly files: FileClient;
2404
- readonly processes: ProcessClient;
2405
- readonly ports: PortClient;
2406
- readonly git: GitClient;
2407
- readonly interpreter: InterpreterClient;
2408
- readonly utils: UtilityClient;
2409
- readonly watch: WatchClient;
2410
- /**
2411
- * Tunnels are RPC-only — the route-based transport does not implement them.
2412
- * This getter exists so the `PublicKeys<SandboxClient> satisfies
2413
- * PublicKeys<SandboxAPI>` compile-time check holds. Calling any method on
2414
- * the returned proxy throws a clear `RPC transport required` error.
2415
- */
2416
- readonly tunnels: never;
2417
- private transport;
2418
- constructor(options: HttpClientOptions);
2419
- /**
2420
- * Update the transport retry budget without recreating the client.
2421
- *
2422
- * In WebSocket mode a single shared transport is used, so one update covers
2423
- * every sub-client. In HTTP mode each sub-client owns its own transport, so
2424
- * all of them are updated individually.
2425
- */
2426
- setRetryTimeoutMs(ms: number): void;
2427
- /**
2428
- * Get the current transport mode
2429
- */
2430
- getTransportMode(): RouteTransportMode;
2431
- /**
2432
- * Check if WebSocket is connected (only relevant in WebSocket mode)
2433
- */
2434
- isWebSocketConnected(): boolean;
2435
- /**
2436
- * Connect WebSocket transport (no-op in HTTP mode)
2437
- * Called automatically on first request, but can be called explicitly
2438
- * to establish connection upfront.
2439
- */
2440
- connect(): Promise<void>;
2441
- /**
2442
- * Disconnect WebSocket transport (no-op in HTTP mode)
2443
- * Should be called when the sandbox is destroyed.
2444
- */
2445
- disconnect(): void;
1681
+ onTunnelExit(id: string, port: number, exitCode: number | null): Promise<void>;
2446
1682
  }
2447
1683
  //#endregion
2448
1684
  //#region src/container-control/connection.d.ts
@@ -2456,8 +1692,8 @@ interface ContainerControlConnectionOptions {
2456
1692
  logger?: Logger;
2457
1693
  /**
2458
1694
  * Total retry budget (ms) for retryable upgrade responses while the
2459
- * container is unavailable. Defaults to 120 000 (2 minutes), matching the
2460
- * route-based `WebSocketTransport`. Set to 0 to disable retries.
1695
+ * container is unavailable. Defaults to 120 000 (2 minutes). Set to 0 to
1696
+ * disable retries.
2461
1697
  */
2462
1698
  retryTimeoutMs?: number;
2463
1699
  /**
@@ -2467,7 +1703,7 @@ interface ContainerControlConnectionOptions {
2467
1703
  * (e.g. notifying the DO when a tunnel's cloudflared process has
2468
1704
  * exited). When omitted, the container sees an empty remote main.
2469
1705
  */
2470
- localMain?: any;
1706
+ localMain?: SandboxControlCallback & RpcTarget;
2471
1707
  /**
2472
1708
  * Invoked when an active WebSocket transitions to closed/errored.
2473
1709
  * Fired at most once per successful connection from the WS event
@@ -2475,8 +1711,10 @@ interface ContainerControlConnectionOptions {
2475
1711
  * signal so recovery doesn't depend on a periodic poller running
2476
1712
  * inside what may be an idle isolate.
2477
1713
  *
2478
- * Not fired for `doConnect` failures (the rejected `connect()`
2479
- * promise is the signal in that case) nor for `disconnect()`.
1714
+ * Also fired for `doConnect` failures after the deferred transport is
1715
+ * aborted. A failed upgrade poisons the transport, so owners must discard
1716
+ * the connection and create a fresh one for subsequent calls. Not fired for
1717
+ * `disconnect()`.
2480
1718
  */
2481
1719
  onClose?: () => void;
2482
1720
  }
@@ -2496,8 +1734,9 @@ interface ContainerControlClientOptions extends ContainerControlConnectionOption
2496
1734
  /**
2497
1735
  * Fires once when the capnweb session transitions from idle to busy
2498
1736
  * (an RPC call was started or a stream return is now in flight). The
2499
- * Sandbox DO wires this to `inflightRequests++`, which makes
2500
- * `isActivityExpired()` skip the sleepAfter comparison.
1737
+ * Sandbox DO wires this to increment the Container base class's
1738
+ * in-flight request counter, which makes `isActivityExpired()` skip the
1739
+ * sleepAfter comparison.
2501
1740
  */
2502
1741
  onSessionBusy?: () => void;
2503
1742
  /**
@@ -2510,7 +1749,7 @@ interface ContainerControlClientOptions extends ContainerControlConnectionOption
2510
1749
  onSessionIdle?: () => void;
2511
1750
  }
2512
1751
  /**
2513
- * SandboxClient-compatible facade backed by direct capnweb RPC.
1752
+ * Sandbox control facade backed by direct capnweb RPC.
2514
1753
  *
2515
1754
  * All operations call the container's SandboxAPI control interface directly
2516
1755
  * over capnweb, bypassing the HTTP handler/router layer entirely.
@@ -2580,7 +1819,6 @@ declare class ContainerControlClient {
2580
1819
  * client is torn down and reconnected.
2581
1820
  */
2582
1821
  setRetryTimeoutMs(ms: number): void;
2583
- getTransportMode(): SandboxTransport;
2584
1822
  isWebSocketConnected(): boolean;
2585
1823
  connect(): Promise<void>;
2586
1824
  disconnect(): void;
@@ -2602,7 +1840,6 @@ type SandboxConfiguration = {
2602
1840
  sleepAfter?: string | number;
2603
1841
  keepAlive?: boolean;
2604
1842
  containerTimeouts?: NonNullable<SandboxOptions['containerTimeouts']>;
2605
- transport?: SandboxTransport;
2606
1843
  };
2607
1844
  /**
2608
1845
  * SDK-level ContainerProxy that directly dispatches SDK-internal mount hosts
@@ -2620,7 +1857,7 @@ declare function getSandbox<T extends Sandbox<any>>(ns: DurableObjectNamespace<T
2620
1857
  declare class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
2621
1858
  defaultPort: number;
2622
1859
  sleepAfter: string | number;
2623
- client: SandboxClient | ContainerControlClient;
1860
+ client: ContainerControlClient;
2624
1861
  private codeInterpreter;
2625
1862
  private sandboxName;
2626
1863
  private tunnelsHandler;
@@ -2637,14 +1874,6 @@ declare class Sandbox<Env = unknown> extends Container<Env> implements ISandbox
2637
1874
  private activeMounts;
2638
1875
  private mountOperationQueue;
2639
1876
  private currentRuntime;
2640
- private transport;
2641
- /**
2642
- * True once transport has been written to storage at least once (either
2643
- * via setTransport or restored on cold start). Gates the idempotency
2644
- * check so a first explicit call persists even when the requested value
2645
- * already equals the env-derived in-memory default.
2646
- */
2647
- private hasStoredTransport;
2648
1877
  private backupBucket;
2649
1878
  /**
2650
1879
  * Serializes backup operations to prevent concurrent create/restore on the same sandbox.
@@ -2705,26 +1934,18 @@ declare class Sandbox<Env = unknown> extends Container<Env> implements ISandbox
2705
1934
  */
2706
1935
  callTunnels(method: string, args: unknown[]): Promise<unknown>;
2707
1936
  /**
2708
- * Compute the transport retry budget from current container timeouts.
1937
+ * Compute the control-channel upgrade retry budget from current container
1938
+ * timeouts.
2709
1939
  *
2710
1940
  * The budget covers the full container startup window (instance provisioning
2711
- * + port readiness) plus a 30s margin for the maximum single backoff delay
2712
- * (capped at 30s in BaseTransport). The 120s floor preserves the previous
2713
- * default for short timeout configurations.
1941
+ * + port readiness) plus a 30s margin for the maximum single backoff delay.
1942
+ * The 120s floor preserves the default for short timeout configurations.
2714
1943
  */
2715
1944
  private computeRetryTimeoutMs;
2716
1945
  /**
2717
- * Create the route-based compatibility client with current HTTP/WebSocket
2718
- * transport settings.
2719
- */
2720
- private createSandboxClient;
2721
- /**
2722
- * Create the appropriate client for the configured control path.
2723
- *
2724
- * `rpc` currently selects the primary container-control client. `http` and
2725
- * `websocket` select the route-based compatibility client.
1946
+ * Create the single control-plane client used for all SDK operations.
2726
1947
  */
2727
- private createClientForTransport;
1948
+ private createClient;
2728
1949
  constructor(ctx: DurableObjectState<{}>, env: Env);
2729
1950
  setSandboxName(name: string, normalizeId?: boolean): Promise<void>;
2730
1951
  configure(configuration: SandboxConfiguration): Promise<void>;
@@ -2732,7 +1953,6 @@ declare class Sandbox<Env = unknown> extends Container<Env> implements ISandbox
2732
1953
  setKeepAlive(keepAlive: boolean): Promise<void>;
2733
1954
  setEnvVars(envVars: Record<string, string | undefined>): Promise<void>;
2734
1955
  setContainerTimeouts(timeouts: NonNullable<SandboxOptions['containerTimeouts']>): Promise<void>;
2735
- setTransport(transport: SandboxTransport): Promise<void>;
2736
1956
  private validateTimeout;
2737
1957
  private getDefaultTimeouts;
2738
1958
  /**
@@ -3064,7 +2284,7 @@ declare class Sandbox<Env = unknown> extends Container<Env> implements ISandbox
3064
2284
  * - `'utf-8'` / `'utf8'`: always return as UTF-8 string
3065
2285
  * - `'base64'`: always return as base64-encoded string
3066
2286
  * - `'none'`: return a result whose `content` is a raw binary `ReadableStream<Uint8Array>`
3067
- * with no encoding overhead. **Requires `SANDBOX_TRANSPORT=rpc`.** Throws on HTTP/WebSocket transports.
2287
+ * with no encoding overhead.
3068
2288
  */
3069
2289
  readFile(path: string, options: {
3070
2290
  encoding: 'none';
@@ -3167,7 +2387,8 @@ declare class Sandbox<Env = unknown> extends Container<Env> implements ISandbox
3167
2387
  }[]>;
3168
2388
  /**
3169
2389
  * Namespaced tunnel API. Quick tunnels are zero-config preview URLs
3170
- * backed by Cloudflare's trycloudflare service.
2390
+ * backed by Cloudflare's trycloudflare service. Named tunnels bind a
2391
+ * stable hostname under the configured Cloudflare zone.
3171
2392
  *
3172
2393
  * - `tunnels.get(port)` — idempotent. Returns the cached tunnel for
3173
2394
  * `port` if one exists in DO storage, otherwise spawns a fresh
@@ -3177,19 +2398,17 @@ declare class Sandbox<Env = unknown> extends Container<Env> implements ISandbox
3177
2398
  * - `tunnels.destroy(portOrInfo)` — tear down by port number or by
3178
2399
  * the record returned from `get()`.
3179
2400
  *
3180
- * Storage is cleared on container restart (`onStart`), so URLs do
3181
- * not survive a container restart the next `get(port)` call will
3182
- * spawn a fresh tunnel with a new URL.
3183
- *
3184
- * Requires the RPC transport. Calling this on a route-based transport
3185
- * throws "RPC transport required".
2401
+ * Container restarts drop quick-tunnel records because their
2402
+ * `*.trycloudflare.com` URLs are tied to the dead cloudflared process.
2403
+ * Named-tunnel records stay in storage and are marked for respawn so the
2404
+ * next `get(port, { name })` call reuses the Cloudflare tunnel and DNS
2405
+ * record while starting a fresh cloudflared process.
3186
2406
  */
3187
2407
  get tunnels(): TunnelsHandler;
3188
2408
  /**
3189
2409
  * Lazily construct both the public tunnels handler and its sibling
3190
2410
  * exit-handler callback. Called from the `tunnels` getter on first
3191
- * access and on every access after a transport swap clears both
3192
- * fields.
2411
+ * access.
3193
2412
  */
3194
2413
  private ensureTunnelsBuilt;
3195
2414
  /**
@@ -3427,5 +2646,5 @@ declare class Sandbox<Env = unknown> extends Container<Env> implements ISandbox
3427
2646
  private configureS3CredentialProxyOutbound;
3428
2647
  }
3429
2648
  //#endregion
3430
- export { FileStreamEvent as $, RequestConfig as A, CreateContextOptions as At, BackupOptions as B, CommandClient as C, WaitForPortOptions as Ct, ContainerStub as D, isProcessStatus as Dt, BaseApiResponse as E, isProcess as Et, SandboxInterpreterAPI as F, CheckChangesResult as G, BucketCredentials as H, TunnelInfo as I, ExecOptions as J, DirectoryBackup as K, TunnelOptions as L, SessionRequest as M, ExecutionResult as Mt, NamedTunnelInfo as N, RunCodeOptions as Nt, ErrorResponse as O, PtyOptions as Ot, QuickTunnelInfo as P, FileMetadata as Q, ExecuteRequest as R, WriteFileRequest as S, WaitForLogResult as St, BackupClient as T, isExecResult as Tt, BucketProvider as U, BaseExecOptions as V, CheckChangesOptions as W, ExecutionSession as X, ExecResult as Y, FileChunk as Z, GitClient as _, RestoreBackupResult as _t, CommandsResponse as a, LogEvent as at, MkdirRequest as b, SessionOptions as bt, DeleteSessionRequest as c, ProcessCleanupResult as ct, UtilityClient as d, ProcessListResult as dt, FileWatchSSEEvent as et, ProcessClient as f, ProcessLogsResult as ft, GitCheckoutRequest as g, RemoteMountBucketOptions as gt, InterpreterClient as h, ProcessStatus as ht, SandboxClient as i, LocalMountBucketOptions as it, ResponseHandler as j, Execution as jt, HttpClientOptions as k, CodeContext as kt, DeleteSessionResponse as l, ProcessInfoResult as lt, ExecutionCallbacks as m, ProcessStartResult as mt, Sandbox as n, ISandbox as nt, CreateSessionRequest as o, MountBucketOptions as ot, PortClient as p, ProcessOptions as pt, ExecEvent as q, getSandbox as r, ListFilesOptions as rt, CreateSessionResponse as s, Process as st, ContainerProxy$1 as t, GitCheckoutResult as tt, PingResponse as u, ProcessKillResult as ut, FileClient as v, SandboxOptions as vt, ExecuteResponse as w, WatchOptions as wt, ReadFileRequest as x, StreamOptions as xt, FileOperationRequest as y, SandboxTransport as yt, StartProcessRequest as z };
3431
- //# sourceMappingURL=sandbox-C8l-pMlL.d.ts.map
2649
+ export { Process as A, WatchOptions as B, FileWatchSSEEvent as C, LocalMountBucketOptions as D, ListFilesOptions as E, SandboxOptions as F, CodeContext as G, isProcess as H, SessionOptions as I, ExecutionResult as J, CreateContextOptions as K, StreamOptions as L, ProcessStatus as M, RemoteMountBucketOptions as N, LogEvent as O, RestoreBackupResult as P, WaitForLogResult as R, FileStreamEvent as S, ISandbox as T, isProcessStatus as U, isExecResult as V, PtyOptions as W, RunCodeOptions as Y, ExecOptions as _, QuickTunnelInfo as a, FileChunk as b, TunnelOptions as c, BucketCredentials as d, BucketProvider as f, ExecEvent as g, DirectoryBackup as h, NamedTunnelInfo as i, ProcessOptions as j, MountBucketOptions as k, BackupOptions as l, CheckChangesResult as m, Sandbox as n, SandboxInterpreterAPI as o, CheckChangesOptions as p, Execution as q, getSandbox as r, TunnelInfo as s, ContainerProxy$1 as t, BaseExecOptions as u, ExecResult as v, GitCheckoutResult as w, FileMetadata as x, ExecutionSession as y, WaitForPortOptions as z };
2650
+ //# sourceMappingURL=sandbox-Cz8DRoAm.d.ts.map