@cloudflare/sandbox 0.13.0-next.649.1 → 0.13.0-next.651.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.
Files changed (35) hide show
  1. package/dist/bridge/index.d.ts.map +1 -1
  2. package/dist/bridge/index.js +3 -3
  3. package/dist/{contexts-DPFhc2nR.d.ts → contexts-BS0Bs6IU.d.ts} +1 -1
  4. package/dist/{contexts-DPFhc2nR.d.ts.map → contexts-BS0Bs6IU.d.ts.map} +1 -1
  5. package/dist/{dist-mAH_7Ui7.js → dist-DF8sudAg.js} +19 -2
  6. package/dist/dist-DF8sudAg.js.map +1 -0
  7. package/dist/{errors-CpoDEfUZ.js → errors-BG6NZiPD.js} +1 -1
  8. package/dist/{errors-CpoDEfUZ.js.map → errors-BG6NZiPD.js.map} +1 -1
  9. package/dist/extensions/index.d.ts +74 -0
  10. package/dist/extensions/index.d.ts.map +1 -0
  11. package/dist/extensions/index.js +153 -0
  12. package/dist/extensions/index.js.map +1 -0
  13. package/dist/index.d.ts +3 -2
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +3 -3
  16. package/dist/openai/index.d.ts +2 -2
  17. package/dist/openai/index.d.ts.map +1 -1
  18. package/dist/openai/index.js +1 -1
  19. package/dist/opencode/index.d.ts +3 -2
  20. package/dist/opencode/index.d.ts.map +1 -1
  21. package/dist/opencode/index.js +2 -2
  22. package/dist/{sandbox-44kEJjAc.d.ts → rpc-types-PBUY-xXM.d.ts} +97 -1070
  23. package/dist/rpc-types-PBUY-xXM.d.ts.map +1 -0
  24. package/dist/{sandbox-B-FLGbkP.js → sandbox-BgwMBQ7S.js} +7 -4
  25. package/dist/sandbox-BgwMBQ7S.js.map +1 -0
  26. package/dist/sandbox-D_MMqExx.d.ts +1077 -0
  27. package/dist/sandbox-D_MMqExx.d.ts.map +1 -0
  28. package/dist/sidecar/index.d.ts +77 -0
  29. package/dist/sidecar/index.d.ts.map +1 -0
  30. package/dist/sidecar/index.js +201 -0
  31. package/dist/sidecar/index.js.map +1 -0
  32. package/package.json +11 -1
  33. package/dist/dist-mAH_7Ui7.js.map +0 -1
  34. package/dist/sandbox-44kEJjAc.d.ts.map +0 -1
  35. package/dist/sandbox-B-FLGbkP.js.map +0 -1
@@ -1,107 +1,3 @@
1
- import { Container, ContainerProxy } from "@cloudflare/containers";
2
- import { RpcTarget } from "capnweb";
3
-
4
- //#region ../shared/dist/logger/types.d.ts
5
-
6
- type LogComponent = 'container' | 'sandbox-do' | 'executor';
7
- /**
8
- * Context metadata included in every log entry
9
- */
10
- interface LogContext {
11
- /**
12
- * Unique trace ID for request correlation across distributed components
13
- * Format: "tr_" + 16 hex chars (e.g., "tr_7f3a9b2c4e5d6f1a")
14
- */
15
- traceId: string;
16
- /**
17
- * Component that generated the log
18
- */
19
- component: LogComponent;
20
- /**
21
- * Sandbox identifier (which sandbox instance)
22
- */
23
- sandboxId?: string;
24
- /**
25
- * Session identifier (which session within sandbox)
26
- */
27
- sessionId?: string;
28
- /**
29
- * Process identifier (which background process)
30
- */
31
- processId?: string;
32
- /**
33
- * Command identifier (which command execution)
34
- */
35
- commandId?: string;
36
- /**
37
- * Duration in milliseconds
38
- */
39
- durationMs?: number;
40
- /**
41
- * Service version (from SANDBOX_VERSION env var)
42
- */
43
- serviceVersion?: string;
44
- /**
45
- * Instance identifier (hostname or container ID)
46
- */
47
- instanceId?: string;
48
- /**
49
- * Extensible for additional metadata
50
- */
51
- [key: string]: unknown;
52
- }
53
- /**
54
- * Logger interface for structured logging
55
- *
56
- * All methods accept optional context that gets merged with the logger's base context.
57
- */
58
- interface Logger {
59
- /**
60
- * Log debug-level message (most verbose, typically disabled in production)
61
- *
62
- * @param message Human-readable message
63
- * @param context Optional additional context
64
- */
65
- debug(message: string, context?: Partial<LogContext>): void;
66
- /**
67
- * Log info-level message (normal operational events)
68
- *
69
- * @param message Human-readable message
70
- * @param context Optional additional context
71
- */
72
- info(message: string, context?: Partial<LogContext>): void;
73
- /**
74
- * Log warning-level message (recoverable issues, degraded state)
75
- *
76
- * @param message Human-readable message
77
- * @param context Optional additional context
78
- */
79
- warn(message: string, context?: Partial<LogContext>): void;
80
- /**
81
- * Log error-level message (failures, exceptions)
82
- *
83
- * @param message Human-readable message
84
- * @param error Optional Error object to include
85
- * @param context Optional additional context
86
- */
87
- error(message: string, error?: Error, context?: Partial<LogContext>): void;
88
- /**
89
- * Create a child logger with additional context
90
- *
91
- * The child logger inherits all context from the parent and adds new context.
92
- * This is useful for adding request-specific context without passing through parameters.
93
- *
94
- * @param context Additional context to merge
95
- * @returns New logger instance with merged context
96
- *
97
- * @example
98
- * const logger = createLogger({ component: 'sandbox-do', traceId: 'tr_abc123' });
99
- * const execLogger = logger.child({ commandId: 'cmd-456' });
100
- * execLogger.info('Command started'); // Includes all context: component, traceId, commandId
101
- */
102
- child(context: Partial<LogContext>): Logger;
103
- }
104
- //#endregion
105
1
  //#region ../shared/dist/interpreter-types.d.ts
106
2
  interface CreateContextOptions {
107
3
  /**
@@ -1469,6 +1365,19 @@ interface RestoreBackupResponse {
1469
1365
  }
1470
1366
  //#endregion
1471
1367
  //#region ../shared/dist/rpc-types.d.ts
1368
+ interface SandboxAPI {
1369
+ commands: SandboxCommandsAPI;
1370
+ files: SandboxFilesAPI;
1371
+ processes: SandboxProcessesAPI;
1372
+ ports: SandboxPortsAPI;
1373
+ git: SandboxGitAPI;
1374
+ interpreter: SandboxInterpreterAPI;
1375
+ utils: SandboxUtilsAPI;
1376
+ backup: SandboxBackupAPI;
1377
+ watch: SandboxWatchAPI;
1378
+ tunnels: SandboxTunnelsAPI;
1379
+ extensions: SandboxExtensionsAPI;
1380
+ }
1472
1381
  interface SandboxCommandsAPI {
1473
1382
  execute(command: string, sessionId: string, options?: {
1474
1383
  timeoutMs?: number;
@@ -1663,990 +1572,108 @@ interface SandboxTunnelsAPI {
1663
1572
  listTunnels(): Promise<TunnelInfo[]>;
1664
1573
  }
1665
1574
  /**
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.
1575
+ * Author-facing description of a sidecar extension. An extension is an
1576
+ * npm-style package: an `.tgz` whose embedded `package.json` declares the
1577
+ * sidecar entrypoint (via `bin`) and any extension metadata (under the
1578
+ * `sandboxExtension` key).
1670
1579
  *
1671
- * One stable target per sandbox; not per-tunnel. Reusable seam for
1672
- * future container→DO events.
1580
+ * The SDK ships the tarball bytes; the container hashes them, provisions a
1581
+ * dedicated directory keyed by content hash, derives identity from the
1582
+ * embedded `package.json`, installs the package with `bun add`, and spawns
1583
+ * the declared bin under Bun.
1584
+ *
1585
+ * `ExtensionPackage` carries tarball bytes produced by an extension build.
1586
+ * The SDK sends those bytes only when the container has not provisioned the
1587
+ * package hash yet.
1673
1588
  */
1674
- interface SandboxControlCallback {
1589
+ interface ExtensionPackage {
1590
+ /** Raw `.tgz` bytes. */
1591
+ tarball: Uint8Array;
1675
1592
  /**
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.
1593
+ * Bin entry to run when the embedded `package.json` declares more than one.
1594
+ * Defaults to the value of `sandboxExtension.bin` in `package.json`, then
1595
+ * to the single bin entry if there is exactly one.
1680
1596
  */
1681
- onTunnelExit(id: string, port: number, exitCode: number | null): Promise<void>;
1682
- }
1683
- //#endregion
1684
- //#region src/container-control/connection.d.ts
1685
- /** Stub that can issue a WebSocket-upgrade fetch through the DO's Container base class. */
1686
- interface ContainerFetchStub {
1687
- fetch(request: Request): Promise<Response>;
1688
- }
1689
- interface ContainerControlConnectionOptions {
1690
- stub: ContainerFetchStub;
1691
- port?: number;
1692
- logger?: Logger;
1693
- /**
1694
- * Total retry budget (ms) for retryable upgrade responses while the
1695
- * container is unavailable. Defaults to 120 000 (2 minutes). Set to 0 to
1696
- * disable retries.
1697
- */
1698
- retryTimeoutMs?: number;
1699
- /**
1700
- * Optional `localMain` exposed to the container side of the capnweb
1701
- * session. The container reaches it via
1702
- * `session.getRemoteMain()` and uses it for control-plane callbacks
1703
- * (e.g. notifying the DO when a tunnel's cloudflared process has
1704
- * exited). When omitted, the container sees an empty remote main.
1705
- */
1706
- localMain?: SandboxControlCallback & RpcTarget;
1707
- /**
1708
- * Invoked when an active WebSocket transitions to closed/errored.
1709
- * Fired at most once per successful connection from the WS event
1710
- * handlers in `doConnect`. Gives owners a synchronous teardown
1711
- * signal so recovery doesn't depend on a periodic poller running
1712
- * inside what may be an idle isolate.
1713
- *
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()`.
1718
- */
1719
- onClose?: () => void;
1720
- }
1721
- //#endregion
1722
- //#region src/container-control/client.d.ts
1723
- interface ContainerControlClientOptions extends ContainerControlConnectionOptions {
1724
- /** Idle timeout before disconnecting the WebSocket (ms). Defaults to 1 000. */
1725
- idleDisconnectMs?: number;
1726
- /** Busy/idle poll interval (ms). Defaults to 1 000. */
1727
- busyPollIntervalMs?: number;
1597
+ bin?: string;
1728
1598
  /**
1729
- * Renew the DO's activity timeout. Fires at the start of every RPC call
1730
- * and on every busy-poll tick while the session has work in flight.
1731
- * Mirrors what `containerFetch()` does at the top of each HTTP request.
1599
+ * Max time to wait for the sidecar to accept a capnweb connection on its
1600
+ * unix socket. Falls back to `sandboxExtension.readinessTimeoutMs` in
1601
+ * `package.json`, then to a host default.
1732
1602
  */
1733
- onActivity?: () => void;
1603
+ readinessTimeoutMs?: number;
1734
1604
  /**
1735
- * Fires once when the capnweb session transitions from idle to busy
1736
- * (an RPC call was started or a stream return is now in flight). The
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.
1605
+ * Run lifecycle scripts during `bun add`. Defaults to false provisioning
1606
+ * happens before the sidecar is supervised, so install-time side effects
1607
+ * are deliberately opt-in.
1740
1608
  */
1741
- onSessionBusy?: () => void;
1742
- /**
1743
- * Fires once when the session transitions from busy back to idle
1744
- * (all RPC promises settled and all stream exports released). The
1745
- * Sandbox DO wires this to `inflightRequests = max(0, n-1)` and a
1746
- * final `renewActivityTimeout()`, matching containerFetch's finally
1747
- * block.
1748
- */
1749
- onSessionIdle?: () => void;
1609
+ allowInstallScripts?: boolean;
1610
+ }
1611
+ /** Health snapshot for a provisioned extension. */
1612
+ interface ExtensionHealth {
1613
+ packageHash: string;
1614
+ id: string;
1615
+ version: string;
1616
+ /** Tarball is on disk and the package.json has been read. */
1617
+ provisioned: boolean;
1618
+ /** Sidecar process is currently running. */
1619
+ running: boolean;
1620
+ pid: number | null;
1621
+ /** Whether a `__ping__` round-tripped over capnweb. */
1622
+ responsive: boolean;
1750
1623
  }
1751
1624
  /**
1752
- * Sandbox control facade backed by direct capnweb RPC.
1753
- *
1754
- * All operations call the container's SandboxAPI control interface directly
1755
- * over capnweb, bypassing the HTTP handler/router layer entirely.
1756
- *
1757
- * Manages its own WebSocket lifecycle: a fresh `ContainerControlConnection` is
1758
- * created on demand and torn down after `idleDisconnectMs` of inactivity.
1759
- * Busy/idle detection relies on `RpcSession.getStats()` which tracks all
1760
- * in-flight RPC calls and stream exports — including long-lived streaming
1761
- * RPCs that would be invisible to a simple per-call request counter (see
1762
- * the file-level comment for the full rationale).
1625
+ * Connect request payload. The SDK hashes the tarball locally and first sends
1626
+ * only the hash. If the current host process has not provisioned that hash,
1627
+ * it responds with an `ExtensionTarballRequired` error and the SDK retries
1628
+ * with `tarball` populated.
1763
1629
  */
1764
- declare class ContainerControlClient {
1765
- private readonly connOptions;
1766
- private readonly idleDisconnectMs;
1767
- private readonly busyPollIntervalMs;
1768
- private readonly logger;
1769
- private readonly onActivity;
1770
- private readonly onSessionBusy;
1771
- private readonly onSessionIdle;
1772
- private conn;
1773
- private idleTimer;
1774
- private busyPollTimer;
1775
- /** Tracks whether we currently believe the session is busy. */
1776
- private busy;
1777
- constructor(options: ContainerControlClientOptions);
1778
- /**
1779
- * Return the current connection, creating one when the client is disconnected.
1780
- * Starts the busy-poll timer the first time a connection is materialized.
1781
- */
1782
- private getConnection;
1783
- /**
1784
- * Called synchronously at the start of each RPC method invocation.
1785
- * Renews the DO activity timeout so the sleepAfter alarm is pushed
1786
- * forward before the container processes the call.
1787
- */
1788
- private renewActivity;
1789
- /**
1790
- * Sample `getStats()` and update busy/idle state. While busy, renews the
1791
- * activity timeout each tick so an in-flight stream keeps pushing the
1792
- * sleepAfter deadline forward. On the busy → idle edge, fires
1793
- * `onSessionIdle` and schedules the WebSocket disconnect.
1794
- *
1795
- * If the WebSocket has dropped underneath us (container crash, network
1796
- * blip) we tear the connection down here. `destroyConnection()` fires
1797
- * `onSessionIdle` if we were busy, so the DO's inflight counter doesn't
1798
- * stay pinned forever waiting for a peer that's never going to reply.
1799
- */
1800
- private pollBusyState;
1801
- private startBusyPoll;
1802
- private stopBusyPoll;
1803
- private scheduleIdleDisconnect;
1804
- private clearIdleTimer;
1805
- private destroyConnection;
1806
- get commands(): SandboxCommandsAPI;
1807
- get files(): SandboxFilesAPI;
1808
- get processes(): SandboxProcessesAPI;
1809
- get ports(): SandboxPortsAPI;
1810
- get git(): SandboxGitAPI;
1811
- get utils(): SandboxUtilsAPI;
1812
- get backup(): SandboxBackupAPI;
1813
- get watch(): SandboxWatchAPI;
1814
- get tunnels(): SandboxTunnelsAPI;
1815
- get interpreter(): SandboxInterpreterAPI;
1816
- /**
1817
- * Update the upgrade retry budget. Applies to the current connection
1818
- * (if any) and is remembered for any future connections created after the
1819
- * client is torn down and reconnected.
1820
- */
1821
- setRetryTimeoutMs(ms: number): void;
1822
- isWebSocketConnected(): boolean;
1823
- connect(): Promise<void>;
1824
- disconnect(): void;
1825
- }
1826
- //#endregion
1827
- //#region src/tunnels/tunnels-handler.d.ts
1828
- interface TunnelsHandler {
1829
- get(port: number, options?: TunnelOptions): Promise<TunnelInfo>;
1830
- list(): Promise<TunnelInfo[]>;
1831
- destroy(portOrInfo: number | TunnelInfo): Promise<void>;
1630
+ interface ExtensionConnectRequest {
1631
+ packageHash: string;
1632
+ /** Only sent when the host has not seen this hash yet. */
1633
+ tarball?: Uint8Array;
1634
+ bin?: string;
1635
+ readinessTimeoutMs?: number;
1636
+ allowInstallScripts?: boolean;
1832
1637
  }
1833
- //#endregion
1834
- //#region src/sandbox.d.ts
1835
- type SandboxConfiguration = {
1836
- sandboxName?: {
1837
- name: string;
1838
- normalizeId?: boolean;
1839
- };
1840
- sleepAfter?: string | number;
1841
- keepAlive?: boolean;
1842
- containerTimeouts?: NonNullable<SandboxOptions['containerTimeouts']>;
1843
- };
1844
1638
  /**
1845
- * SDK-level ContainerProxy that directly dispatches SDK-internal mount hosts
1846
- * (r2.internal, s3-credential-proxy.internal) without relying on
1847
- * outboundHandlersRegistry lookups, which are NOT shared between the Durable
1848
- * Object's execution context and the ContainerProxy WorkerEntrypoint context.
1639
+ * Control surface for container sidecar extensions.
1849
1640
  *
1850
- * Users must export this class from their Worker entrypoint so the Sandbox DO
1851
- * can create outbound-interception fetchers that reference it.
1641
+ * `connect` is the only entry point: it provisions on first use, supervises
1642
+ * lazily, and returns the sidecar's capnweb remote main as a stub. Calls on
1643
+ * the stub are proxied through the container's capnweb session to the
1644
+ * sidecar's capnweb session — callback parameters (including streaming
1645
+ * handlers) round-trip across both hops.
1852
1646
  */
1853
- declare class ContainerProxy$1 extends ContainerProxy {
1854
- fetch(request: Request): Promise<Response>;
1855
- }
1856
- declare function getSandbox<T extends Sandbox<any>>(ns: DurableObjectNamespace<T>, id: string, options?: SandboxOptions): T;
1857
- declare class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
1858
- defaultPort: number;
1859
- sleepAfter: string | number;
1860
- client: ContainerControlClient;
1861
- private codeInterpreter;
1862
- private sandboxName;
1863
- private tunnelsHandler;
1864
- private tunnelExitHandler;
1865
- private destroyAllTunnels;
1866
- private readonly controlCallback;
1867
- private normalizeId;
1868
- private defaultSession;
1869
- private containerGeneration;
1870
- private defaultSessionInit;
1871
- envVars: Record<string, string>;
1872
- private logger;
1873
- private keepAliveEnabled;
1874
- private activeMounts;
1875
- private mountOperationQueue;
1876
- private currentRuntime;
1877
- private backupBucket;
1878
- /**
1879
- * Serializes backup operations to prevent concurrent create/restore on the same sandbox.
1880
- *
1881
- * This is in-memory state — it resets if the Durable Object is evicted and
1882
- * re-instantiated (e.g. after sleep). This is acceptable because the container
1883
- * filesystem is also lost on eviction, so there is no archive to race on.
1884
- */
1885
- private backupInProgress;
1886
- /**
1887
- * R2 presigned URL credentials for direct container-to-R2 transfers.
1888
- * All four fields plus the R2 binding must be configured for backup to work.
1889
- */
1890
- private r2AccessKeyId;
1891
- private r2SecretAccessKey;
1892
- private r2AccountId;
1893
- private backupBucketName;
1894
- private backupBucketEndpoint;
1895
- private r2Client;
1896
- /**
1897
- * Lazily-resolved Cloudflare account id for named-tunnel provisioning.
1898
- * Resolved on first access via `tunnels/credentials.ts` and cached for
1899
- * the lifetime of this DO instance. See the credentials helper for
1900
- * the precedence chain.
1901
- */
1902
- private tunnelAccountIdPromise;
1903
- /**
1904
- * Lazily-resolved Cloudflare zone id for named-tunnel provisioning.
1905
- * Falls back to the single zone the token can see under the resolved
1906
- * account id when `CLOUDFLARE_ZONE_ID` is not set. Cached for the
1907
- * lifetime of this DO instance.
1908
- */
1909
- private tunnelZoneIdPromise;
1647
+ interface SandboxExtensionsAPI {
1910
1648
  /**
1911
- * Default container startup timeouts (conservative for production)
1912
- * Based on Cloudflare docs: "Containers take several minutes to provision"
1649
+ * Provision the package (if new) and return the sidecar's typed remote
1650
+ * main. The result is a capnweb stub whose methods correspond to the
1651
+ * sidecar's `RpcTarget` surface.
1913
1652
  */
1914
- private readonly DEFAULT_CONTAINER_TIMEOUTS;
1915
- /**
1916
- * Active container timeout configuration
1917
- * Can be set via options, env vars, or defaults
1918
- */
1919
- private containerTimeouts;
1920
- /**
1921
- * True once containerTimeouts has been written to storage at least once
1922
- * (either via setContainerTimeouts or restored on cold start). Gates the
1923
- * idempotency check in setContainerTimeouts so a first explicit call
1924
- * persists even when the requested values already equal the in-memory
1925
- * defaults, distinguishing "user intent recorded" from "running on
1926
- * env/SDK defaults".
1927
- */
1928
- private hasStoredContainerTimeouts;
1929
- /**
1930
- * Dispatch method for tunnel operations.
1931
- * Called by the client-side proxy created in getSandbox() to provide
1932
- * the `sandbox.tunnels` API without relying on RPC pipelining
1933
- * through property getters which is broken when using vite-plugin.
1934
- */
1935
- callTunnels(method: string, args: unknown[]): Promise<unknown>;
1936
- /**
1937
- * Compute the control-channel upgrade retry budget from current container
1938
- * timeouts.
1939
- *
1940
- * The budget covers the full container startup window (instance provisioning
1941
- * + port readiness) plus a 30s margin for the maximum single backoff delay.
1942
- * The 120s floor preserves the default for short timeout configurations.
1943
- */
1944
- private computeRetryTimeoutMs;
1945
- /**
1946
- * Create the single control-plane client used for all SDK operations.
1947
- */
1948
- private createClient;
1949
- constructor(ctx: DurableObjectState<{}>, env: Env);
1950
- setSandboxName(name: string, normalizeId?: boolean): Promise<void>;
1951
- configure(configuration: SandboxConfiguration): Promise<void>;
1952
- setSleepAfter(sleepAfter: string | number): Promise<void>;
1953
- setKeepAlive(keepAlive: boolean): Promise<void>;
1954
- setEnvVars(envVars: Record<string, string | undefined>): Promise<void>;
1955
- setContainerTimeouts(timeouts: NonNullable<SandboxOptions['containerTimeouts']>): Promise<void>;
1956
- private validateTimeout;
1957
- private getDefaultTimeouts;
1958
- /**
1959
- * Mount an S3-compatible bucket as a local directory.
1960
- *
1961
- * Requires explicit endpoint URL for production. Credentials are auto-detected from environment
1962
- * variables or can be provided explicitly.
1963
- *
1964
- * @param bucket - Bucket name (or R2 binding name when localBucket is true)
1965
- * @param mountPath - Absolute path in container to mount at
1966
- * @param options - Mount configuration
1967
- * @throws MissingCredentialsError if no credentials found in environment
1968
- * @throws S3FSMountError if S3FS mount command fails
1969
- * @throws InvalidMountConfigError if bucket name, mount path, or endpoint is invalid
1970
- */
1971
- mountBucket(bucket: string, mountPath: string, options: MountBucketOptions): Promise<void>;
1972
- private runMountOperation;
1973
- private mountBucketUnlocked;
1974
- /**
1975
- * Local dev mount: bidirectional sync via R2 binding + file/watch APIs
1976
- */
1977
- private mountBucketLocal;
1978
- private getR2EgressParams;
1979
- private validateProtectedS3fsOptions;
1980
- private getS3CredentialProxyParams;
1981
- private resolveCredentialProxyAuthStrategy;
1982
- /**
1983
- * Credential-less R2 mount: egress interception routes s3fs requests to the
1984
- * R2 binding. No S3 credentials are needed in the container or Worker env.
1985
- */
1986
- private mountBucketR2Egress;
1987
- /**
1988
- * Production mount: S3FS-FUSE inside the container
1989
- */
1990
- private mountBucketFuse;
1991
- /**
1992
- * Manually unmount a bucket filesystem
1993
- *
1994
- * @param mountPath - Absolute path where the bucket is mounted
1995
- * @throws InvalidMountConfigError if mount path doesn't exist or isn't mounted
1996
- */
1997
- unmountBucket(mountPath: string): Promise<void>;
1998
- private unmountBucketUnlocked;
1999
- /**
2000
- * Shared validation for mount path (absolute, not already in use).
2001
- */
2002
- private validateMountPath;
2003
- /**
2004
- * Validate mount options for remote (FUSE) mounts
2005
- */
2006
- private validateMountOptions;
2007
- /**
2008
- * Generate unique password file path for s3fs credentials
2009
- */
2010
- private generatePasswordFilePath;
2011
- /**
2012
- * Generate unique ahbe_conf file path for s3fs additional header config
2013
- */
2014
- private generateS3FSAdditionalHeaderFilePath;
2015
- /**
2016
- * Create s3fs ahbe_conf file that suppresses the Expect: 100-continue header.
2017
- * Restricted to 0600 so s3fs will accept it (same requirement as passwd files).
2018
- */
2019
- private createDisableExpectHeaderFile;
2020
- /**
2021
- * Create password file with s3fs credentials
2022
- * Format: bucket:accessKeyId:secretAccessKey
2023
- */
2024
- private createPasswordFile;
2025
- /**
2026
- * Delete password file
2027
- */
2028
- private deletePasswordFile;
2029
- private deleteAdditionalHeaderFile;
2030
- /**
2031
- * Execute S3FS mount command
2032
- */
2033
- private executeS3FSMount;
2034
- private unmountTrackedFuseMount;
2035
- /**
2036
- * In-flight `destroy()` promise. While set, concurrent callers coalesce
2037
- * onto the same teardown instead of triggering a second one. Cleared when
2038
- * the underlying work settles, so a later call that genuinely needs to
2039
- * recreate a destroyed sandbox still runs.
2040
- *
2041
- * If the underlying teardown hangs (e.g. `super.destroy()` never resolves
2042
- * because the Containers control plane is unresponsive), every coalesced
2043
- * caller hangs on the same promise until the Durable Object is evicted.
2044
- * This is deliberate: a second concurrent teardown would not make a stuck
2045
- * control plane unstuck, and spawning one would defeat the point of
2046
- * coalescing. Callers that need bounded waits must apply their own
2047
- * timeout around `destroy()`.
2048
- */
2049
- private inflightDestroy;
2050
- /**
2051
- * Cleanup and destroy the sandbox container.
2052
- *
2053
- * Concurrent calls coalesce: if a previous `destroy()` is still in flight,
2054
- * subsequent calls await the same underlying work instead of starting a
2055
- * second teardown. A canonical `sandbox.destroy.coalesced` event is logged
2056
- * per coalesced call so repeated destroy traffic is observable.
2057
- */
2058
- destroy(): Promise<void>;
2059
- private doDestroy;
2060
- onStart(): Promise<void>;
2061
- stop(signal?: Parameters<Container<Env>['stop']>[0]): Promise<void>;
2062
- /**
2063
- * Read the `portTokens` map from DO storage, normalizing the legacy
2064
- * string-valued format (just a token) to the current object format
2065
- * ({ token, name? }). The legacy format predates port-name persistence and
2066
- * can appear on any DO whose storage was written before that change.
2067
- */
2068
- private readPortTokens;
2069
- private readActivePreviewPorts;
2070
- private writeActivePreviewPorts;
2071
- private readPreviewState;
2072
- private clearActivePreviewPorts;
2073
- /**
2074
- * Check if the container version matches the SDK version
2075
- * Logs a warning if there's a mismatch
2076
- */
2077
- private checkVersionCompatibility;
2078
- onStop(): Promise<void>;
2079
- onError(error: unknown): void;
2080
- /**
2081
- * Override Container.containerFetch to use production-friendly timeouts
2082
- * Automatically starts container with longer timeouts if not running
2083
- */
2084
- containerFetch(requestOrUrl: Request | string | URL, portOrInit?: number | RequestInit, portParam?: number): Promise<Response>;
2085
- /**
2086
- * Helper: Check if error is "no container instance available"
2087
- * This indicates the container VM is still being provisioned.
2088
- */
2089
- private isNoInstanceError;
2090
- /**
2091
- * Helper: Check if error is a transient startup error that should trigger retry
2092
- *
2093
- * These errors occur during normal container startup and are recoverable:
2094
- * - Port not yet mapped (container starting, app not listening yet)
2095
- * - Connection refused (port mapped but app not ready)
2096
- * - Timeouts during startup (recoverable with retry)
2097
- * - Network transients (temporary connectivity issues)
2098
- *
2099
- * Errors NOT included (permanent failures):
2100
- * - "no such image" - missing Docker image
2101
- * - "container already exists" - name collision
2102
- * - Configuration errors
2103
- */
2104
- private isTransientStartupError;
2105
- /**
2106
- * Helper: Check if error is a permanent startup failure that will never recover
2107
- *
2108
- * These errors indicate resource exhaustion, misconfiguration, or missing images.
2109
- * Retrying will never succeed, so the SDK should fail fast with HTTP 500.
2110
- *
2111
- * Error sources (traced from platform internals):
2112
- * - Container runtime: OOM, PID limit
2113
- * - Scheduling/provisioning: no matching app, no namespace configured
2114
- * - workerd container-client.c++: no such image
2115
- * - @cloudflare/containers: did not call start
2116
- */
2117
- private isPermanentStartupError;
2118
- /**
2119
- * Helper: Parse containerFetch arguments (supports multiple signatures)
2120
- */
2121
- private parseContainerFetchArgs;
2122
- /**
2123
- * Override onActivityExpired to prevent automatic shutdown when keepAlive is enabled
2124
- * When keepAlive is disabled, calls parent implementation which stops the container
2125
- */
2126
- onActivityExpired(): Promise<void>;
2127
- private isPreviewProxyRequest;
2128
- private invalidPreviewTokenResponse;
2129
- private stalePreviewURLResponse;
2130
- private getPreviewForwardingContainer;
2131
- private beginPreviewForward;
2132
- private fetchPreviewIfRunning;
2133
- private buildPreviewProxyRequest;
2134
- private proxyPreviewRequest;
2135
- fetch(request: Request): Promise<Response>;
2136
- wsConnect(request: Request, port: number): Promise<Response>;
2137
- private determinePort;
2138
- /**
2139
- * Return the default session id, lazily creating the container session
2140
- * on first use. Called by every public method that needs a session.
2141
- * Concurrent callers that target the same sessionId share one
2142
- * in-flight initialization promise.
2143
- */
2144
- private ensureDefaultSession;
2145
- private getOrInitializeDefaultSession;
2146
- private isDefaultSessionInitContainerRestart;
2147
- private initializeDefaultSession;
2148
- /**
2149
- * Persist the container's placement ID in DO storage.
2150
- *
2151
- * Called from the session-create handshake so subsequent reads via
2152
- * `getContainerPlacementId()` do not require a round-trip to the container. The value
2153
- * is overwritten on every handshake so that container replacements (which
2154
- * assign a new placement ID) are reflected on the next session-create.
2155
- *
2156
- * A value of `undefined` means the handshake response omitted the field
2157
- * (older container, unexpected error shape) and the stored value is left
2158
- * untouched. `null` means the env var is not set in the container and is
2159
- * stored as-is so callers can distinguish "observed and absent" from "not
2160
- * yet observed."
2161
- */
2162
- private capturePlacementId;
2163
- private resolveExecution;
2164
- private validateExplicitSessionId;
2165
- private serializeExecutionContext;
2166
- private getPublicExecutionSessionId;
2167
- /**
2168
- * Resolves the session ID to annotate returned Process objects.
2169
- *
2170
- * Unlike `resolveExecution`, this is synchronous and never creates a
2171
- * session. When the default session hasn't been established yet, it returns
2172
- * `undefined` rather than triggering session creation. The resolved value is
2173
- * only used to populate `Process.sessionId` on the returned object — it is
2174
- * never sent to the container API.
2175
- */
2176
- private getProcessSessionBinding;
2177
- private resolveExecutionEnv;
2178
- private buildExecutionRequestOptions;
2179
- exec(command: string, options?: ExecOptions): Promise<ExecResult>;
2180
- execWithSessionToken(command: string, sessionId: string, options?: ExecOptions): Promise<ExecResult>;
2181
- /**
2182
- * Execute an infrastructure command (backup, mount, env setup, etc.)
2183
- * tagged with origin: 'internal' so logging demotes it to debug level.
2184
- */
2185
- private execInternal;
2186
- /**
2187
- * Internal session-aware exec implementation
2188
- * Used by both public exec() and session wrappers
2189
- */
2190
- private execWithSession;
2191
- private executeWithStreaming;
2192
- private mapExecuteResponseToExecResult;
2193
- /**
2194
- * Create a Process domain object from HTTP client DTO
2195
- * Centralizes process object creation with bound methods
2196
- * This eliminates duplication across startProcess, listProcesses, getProcess, and session wrappers
2197
- */
2198
- private createProcessFromDTO;
2199
- /**
2200
- * Wait for a log pattern to appear in process output
2201
- */
2202
- private waitForLogPattern;
2203
- /**
2204
- * Wait for a port to become available (for process readiness checking)
2205
- */
2206
- private waitForPortReady;
2207
- /**
2208
- * Wait for a process to exit
2209
- * Returns the exit code
2210
- */
2211
- private waitForProcessExit;
2212
- /**
2213
- * Match a pattern against text
2214
- */
2215
- private matchPattern;
2216
- /**
2217
- * Convert a log pattern to a human-readable string
2218
- */
2219
- private conditionToString;
2220
- /**
2221
- * Create a ProcessReadyTimeoutError
2222
- */
2223
- private createReadyTimeoutError;
2224
- /**
2225
- * Create a ProcessExitedBeforeReadyError
2226
- */
2227
- private createExitedBeforeReadyError;
2228
- startProcess(command: string, options?: ProcessOptions, sessionId?: string): Promise<Process>;
2229
- /**
2230
- * Start background streaming for process callbacks
2231
- * Opens SSE stream to container and routes events to callbacks
2232
- */
2233
- private startProcessCallbackStream;
2234
- listProcesses(sessionId?: string): Promise<Process[]>;
2235
- getProcess(id: string, sessionId?: string): Promise<Process | null>;
2236
- killProcess(id: string, signal?: string, sessionId?: string): Promise<void>;
2237
- killAllProcesses(sessionId?: string): Promise<number>;
2238
- cleanupCompletedProcesses(sessionId?: string): Promise<number>;
2239
- getProcessLogs(id: string, sessionId?: string): Promise<{
2240
- stdout: string;
2241
- stderr: string;
2242
- processId: string;
2243
- }>;
2244
- execStream(command: string, options?: StreamOptions): Promise<ReadableStream<Uint8Array>>;
2245
- execStreamWithSessionToken(command: string, sessionId: string, options?: StreamOptions): Promise<ReadableStream<Uint8Array>>;
2246
- /**
2247
- * Internal session-aware execStream implementation
2248
- */
2249
- private execStreamWithSession;
2250
- /**
2251
- * Stream logs from a background process as a ReadableStream.
2252
- */
2253
- streamProcessLogs(processId: string, options?: {
2254
- signal?: AbortSignal;
2255
- }): Promise<ReadableStream<Uint8Array>>;
2256
- gitCheckout(repoUrl: string, options?: {
2257
- branch?: string;
2258
- targetDir?: string;
2259
- sessionId?: string;
2260
- /** Clone depth for shallow clones (e.g., 1 for latest commit only) */
2261
- depth?: number;
2262
- /** Maximum wall-clock time for the git clone subprocess in milliseconds */
2263
- cloneTimeoutMs?: number;
2264
- }): Promise<GitCheckoutResult>;
2265
- mkdir(path: string, options?: {
2266
- recursive?: boolean;
2267
- sessionId?: string;
2268
- }): Promise<MkdirResult>;
2269
- writeFile(path: string, content: string | ReadableStream<Uint8Array>, options?: {
2270
- encoding?: string;
2271
- sessionId?: string;
2272
- }): Promise<{
2273
- success: boolean;
2274
- path: string;
2275
- bytesWritten: number;
2276
- timestamp: string;
2277
- } | WriteFileResult>;
2278
- deleteFile(path: string, sessionId?: string): Promise<DeleteFileResult>;
2279
- renameFile(oldPath: string, newPath: string, sessionId?: string): Promise<RenameFileResult>;
2280
- moveFile(sourcePath: string, destinationPath: string, sessionId?: string): Promise<MoveFileResult>;
2281
- /**
2282
- * Read a file from the sandbox.
2283
- *
2284
- * @param encoding - How to encode the returned content:
2285
- * - `undefined` (default): auto-detect from MIME type (text → UTF-8 string, binary → base64 string)
2286
- * - `'utf-8'` / `'utf8'`: always return as UTF-8 string
2287
- * - `'base64'`: always return as base64-encoded string
2288
- * - `'none'`: return a result whose `content` is a raw binary `ReadableStream<Uint8Array>`
2289
- * with no encoding overhead.
2290
- */
2291
- readFile(path: string, options: {
2292
- encoding: 'none';
2293
- sessionId?: string;
2294
- }): Promise<ReadFileStreamResult>;
2295
- readFile(path: string, options?: {
2296
- encoding?: Exclude<FileEncoding, 'none'>;
2297
- sessionId?: string;
2298
- }): Promise<ReadFileResult>;
2299
- /**
2300
- * Stream a file from the sandbox using Server-Sent Events
2301
- * Returns a ReadableStream that can be consumed with streamFile() or collectFile() utilities
2302
- * @param path - Path to the file to stream
2303
- * @param options - Optional session ID
2304
- */
2305
- readFileStream(path: string, options?: {
2306
- sessionId?: string;
2307
- }): Promise<ReadableStream<Uint8Array>>;
2308
- listFiles(path: string, options?: ListFilesOptions): Promise<ListFilesResult>;
2309
- exists(path: string, sessionId?: string): Promise<FileExistsResult>;
2310
- /**
2311
- * Watch a directory for file system changes using native inotify.
2312
- *
2313
- * The returned promise resolves only after the watcher is established on the
2314
- * filesystem, so callers can immediately perform actions that depend on the
2315
- * watch being active. The returned stream contains the full event sequence
2316
- * starting with the `watching` event.
2317
- *
2318
- * Consume the stream with `parseSSEStream<FileWatchSSEEvent>(stream)`.
2319
- *
2320
- * @param path - Path to watch (absolute or relative to /workspace)
2321
- * @param options - Watch options
2322
- */
2323
- watch(path: string, options?: WatchOptions): Promise<ReadableStream<Uint8Array>>;
2324
- /**
2325
- * Check whether a path changed while this caller was disconnected.
2326
- *
2327
- * Pass the `version` returned from a prior call in `options.since` to learn
2328
- * whether the path is unchanged, changed, or needs a full resync because the
2329
- * retained change state was reset.
2330
- *
2331
- * @param path - Path to check (absolute or relative to /workspace)
2332
- * @param options - Change-check options
2333
- */
2334
- checkChanges(path: string, options?: CheckChangesOptions): Promise<CheckChangesResult>;
2335
- /**
2336
- * Expose a port and get a preview URL for accessing services running in the sandbox
2337
- *
2338
- * Preview URL authorization survives transient container restarts, but
2339
- * forwarding is active only for the runtime where `exposePort()` was last
2340
- * called. Call `exposePort()` again after a restart to reactivate an
2341
- * existing URL for the current runtime.
2342
- *
2343
- * @param port - Port number to expose (1024-65535)
2344
- * @param options - Configuration options
2345
- * @param options.hostname - Your Worker's domain name (required for preview URL construction)
2346
- * @param options.name - Optional friendly name for the port
2347
- * @param options.token - Optional custom token for the preview URL (1-16 characters: lowercase letters, numbers, underscores)
2348
- * If not provided, a random 16-character token will be generated automatically
2349
- * @returns Preview URL information including the full URL, port number, and optional name
2350
- *
2351
- * @example
2352
- * // With auto-generated token
2353
- * const { url } = await sandbox.exposePort(8080, { hostname: 'example.com' });
2354
- * // url: https://8080-sandbox-id-abc123random4567.example.com
2355
- *
2356
- * @example
2357
- * // With custom token for stable URLs across deployments
2358
- * const { url } = await sandbox.exposePort(8080, {
2359
- * hostname: 'example.com',
2360
- * token: 'my_token_v1'
2361
- * });
2362
- * // url: https://8080-sandbox-id-my_token_v1.example.com
2363
- */
2364
- exposePort(port: number, options: {
2365
- name?: string;
2366
- hostname: string;
2367
- token?: string;
2368
- }): Promise<{
2369
- url: string;
2370
- port: number;
2371
- name: string | undefined;
2372
- }>;
2373
- /**
2374
- * Revoke preview URL authorization and current-runtime activation for a port.
2375
- *
2376
- * Revocation is idempotent: calling this for a port with no preview state is
2377
- * still successful. The operation clears Durable Object-owned preview state
2378
- * only and does not contact, probe, wake, or clean up the container runtime.
2379
- */
2380
- unexposePort(port: number): Promise<void>;
2381
- /**
2382
- * Returns preview URLs that are currently forwardable in the active runtime.
2383
- * Durable authorization without current-runtime activation is omitted.
2384
- */
2385
- getExposedPorts(hostname: string): Promise<{
2386
- url: string;
2387
- port: number;
2388
- status: "active";
2389
- }[]>;
2390
- /**
2391
- * Namespaced tunnel API. Quick tunnels are zero-config preview URLs
2392
- * backed by Cloudflare's trycloudflare service. Named tunnels bind a
2393
- * stable hostname under the configured Cloudflare zone.
2394
- *
2395
- * - `tunnels.get(port)` — idempotent. Returns the cached tunnel for
2396
- * `port` if one exists in DO storage, otherwise spawns a fresh
2397
- * cloudflared process and persists the record.
2398
- * - `tunnels.list()` — records currently known to this sandbox, from
2399
- * DO storage.
2400
- * - `tunnels.destroy(portOrInfo)` — tear down by port number or by
2401
- * the record returned from `get()`.
2402
- *
2403
- * Container restarts drop quick-tunnel records because their
2404
- * `*.trycloudflare.com` URLs are tied to the dead cloudflared process.
2405
- * Named-tunnel records stay in storage and are marked for respawn so the
2406
- * next `get(port, { name })` call reuses the Cloudflare tunnel and DNS
2407
- * record while starting a fresh cloudflared process.
2408
- */
2409
- get tunnels(): TunnelsHandler;
2410
- /**
2411
- * Lazily construct both the public tunnels handler and its sibling
2412
- * exit-handler callback. Called from the `tunnels` getter on first
2413
- * access.
2414
- */
2415
- private ensureTunnelsBuilt;
2416
- /**
2417
- * Resolve the Cloudflare account id used for named-tunnel provisioning.
2418
- *
2419
- * Memoised for the lifetime of this DO instance. The first call may hit
2420
- * `GET /user/tokens/verify` to derive the account id from the configured
2421
- * `CLOUDFLARE_API_TOKEN`; subsequent calls return the cached promise.
2422
- *
2423
- * Only successful resolutions are cached: a rejected lookup clears the
2424
- * slot so the next caller retries. Otherwise a transient failure on
2425
- * first use would permanently poison every later named-tunnel `get()`
2426
- * on this DO instance.
2427
- */
2428
- private getTunnelAccountId;
2429
- /**
2430
- * Resolve the Cloudflare zone id used for named-tunnel provisioning.
2431
- *
2432
- * Memoised for the lifetime of this DO instance. Falls back to the
2433
- * single zone the token can see under `accountId` via `GET /zones`
2434
- * when `CLOUDFLARE_ZONE_ID` is not set. Failed lookups clear the cache
2435
- * so the next caller retries — see `getTunnelAccountId` for the
2436
- * rationale.
2437
- */
2438
- private getTunnelZoneId;
2439
- /**
2440
- * Returns whether a port is currently preview-forwardable.
2441
- * This checks Durable Object-owned auth and runtime activation without
2442
- * contacting or waking the container.
2443
- */
2444
- isPortExposed(port: number): Promise<boolean>;
2445
- /**
2446
- * Checks durable preview URL authorization for a port/token pair.
2447
- *
2448
- * This does not check whether the port is activated for the current runtime
2449
- * and is not sufficient to decide whether preview traffic may forward.
2450
- */
2451
- validatePortToken(port: number, token: string): Promise<boolean>;
2452
- private validatePreviewURLForRuntime;
2453
- private getCurrentPreviewPorts;
2454
- private previewTokensMatch;
2455
- private validateCustomToken;
2456
- private generatePortToken;
2457
- private constructPreviewUrl;
2458
- /**
2459
- * Create isolated execution session for advanced use cases
2460
- * Returns ExecutionSession with full sandbox API bound to specific session
2461
- */
2462
- createSession(options?: SessionOptions): Promise<ExecutionSession>;
2463
- /**
2464
- * Get an existing session by ID
2465
- * Returns ExecutionSession wrapper bound to the specified session
2466
- *
2467
- * This is useful for retrieving sessions across different requests/contexts
2468
- * without storing the ExecutionSession object (which has RPC lifecycle limitations)
2469
- *
2470
- * @param sessionId - The ID of an existing session
2471
- * @returns ExecutionSession wrapper bound to the session
2472
- */
2473
- getSession(sessionId: string): Promise<ExecutionSession>;
2474
- /**
2475
- * Delete an execution session
2476
- * Cleans up session resources and removes it from the container
2477
- * Note: Cannot delete the default session. To reset the default session,
2478
- * use sandbox.destroy() to terminate the entire sandbox.
2479
- *
2480
- * @param sessionId - The ID of the session to delete
2481
- * @returns Result with success status, sessionId, and timestamp
2482
- * @throws Error if attempting to delete the default session
2483
- */
2484
- deleteSession(sessionId: string): Promise<SessionDeleteResult>;
2485
- /**
2486
- * Get the Cloudflare placement ID observed for the underlying container.
2487
- *
2488
- * The placement ID is captured during the first session-create handshake
2489
- * after a container start and stored in Durable Object storage, so this
2490
- * method returns the cached value without contacting the container. A new
2491
- * placement ID is captured on each subsequent session-create handshake,
2492
- * which occurs whenever the container has been replaced.
2493
- *
2494
- * Returns `null` when a handshake has completed but the container's
2495
- * `CLOUDFLARE_PLACEMENT_ID` environment variable is not set (for example,
2496
- * in local development).
2497
- *
2498
- * Returns `undefined` when no handshake has been observed yet on this
2499
- * sandbox. Call any method that triggers session creation (such as
2500
- * `exec()`) to populate the value.
2501
- */
2502
- getContainerPlacementId(): Promise<string | null | undefined>;
2503
- private getSessionWrapper;
2504
- createCodeContext(options?: CreateContextOptions): Promise<CodeContext>;
2505
- runCode(code: string, options?: RunCodeOptions): Promise<ExecutionResult>;
2506
- runCodeStream(code: string, options?: RunCodeOptions): Promise<ReadableStream>;
2507
- listCodeContexts(): Promise<CodeContext[]>;
2508
- deleteCodeContext(contextId: string): Promise<void>;
2509
- /** UUID v4 format validator for backup IDs */
2510
- private static readonly UUID_REGEX;
2511
- /**
2512
- * Validate that a directory path is safe for backup operations.
2513
- * Rejects empty, relative, traversal, null-byte, and unsupported-root paths.
2514
- */
2515
- private static validateBackupDir;
2516
- /**
2517
- * Returns the R2 bucket or throws if backup is not configured.
2518
- */
2519
- private requireBackupBucket;
2520
- private normalizeBackupExcludes;
2521
- private resolveBackupCompression;
2522
- private static readonly PRESIGNED_URL_EXPIRY_SECONDS;
2523
- /**
2524
- * Create a unique, dedicated session for a single backup operation.
2525
- * Each call produces a fresh session ID so concurrent or sequential
2526
- * operations never share shell state. Callers must destroy the session
2527
- * in a finally block via `client.utils.deleteSession()`.
2528
- */
2529
- private ensureBackupSession;
2530
- /**
2531
- * Returns validated presigned URL configuration or throws if not configured.
2532
- * All credential fields plus the R2 binding are required for backup to work.
2533
- */
2534
- private requirePresignedURLSupport;
2535
- private getBackupBucketEndpoint;
2536
- private getBackupObjectURL;
2537
- /**
2538
- * Generate a presigned GET URL for downloading an object from R2.
2539
- * The container can curl this URL directly without credentials.
2540
- */
2541
- private generatePresignedGetURL;
2542
- /**
2543
- * Generate a presigned PUT URL for uploading an object to R2.
2544
- * The container can curl PUT to this URL directly without credentials.
2545
- */
2546
- private generatePresignedPutURL;
2547
- /**
2548
- * Upload a backup archive via presigned PUT URL.
2549
- * The container curls the archive directly to R2, bypassing the DO.
2550
- * ~24 MB/s throughput vs ~0.6 MB/s for base64 readFile.
2551
- */
2552
- private uploadBackupPresigned;
2553
- /**
2554
- * Generate a presigned PUT URL for a single part in a multipart upload.
2555
- */
2556
- private generatePresignedPartURL;
2557
- /**
2558
- * Upload a backup archive to R2 using parallel multipart upload.
2559
- * Uses the S3-compatible API exclusively for create/complete/abort so that
2560
- * the uploadId is in the same namespace as the presigned part PUT URLs.
2561
- */
2562
- private uploadBackupMultipart;
2563
- /**
2564
- * Download a backup archive from R2 via presigned GET URL.
2565
- * For archives >= BACKUP_DOWNLOAD_PARALLEL_MIN_SIZE, uses BACKUP_DOWNLOAD_PARALLEL_PARTS
2566
- * concurrent curl processes (each downloading a byte-range) to maximise both
2567
- * network and disk-write throughput. Parts are written into a pre-sized file
2568
- * with dd using byte offsets, then atomically moved to the final path.
2569
- */
2570
- private downloadBackupParallel;
2571
- /**
2572
- * Serialize backup operations on this sandbox instance.
2573
- * Concurrent backup/restore calls are queued so the multi-step
2574
- * create-archive → read → upload (or mount → extract) flow
2575
- * is not interleaved with another backup operation on the same directory.
2576
- */
2577
- private enqueueBackupOp;
2578
- /**
2579
- * Create a backup of a directory and upload it to R2.
2580
- *
2581
- * Flow:
2582
- * 1. Container creates squashfs archive from the directory
2583
- * 2. Container uploads the archive directly to R2 via presigned URL
2584
- * 3. DO writes metadata to R2
2585
- * 4. Container cleans up the local archive
2586
- *
2587
- * The returned DirectoryBackup handle is serializable. Store it anywhere
2588
- * (KV, D1, DO storage) and pass it to restoreBackup() later.
2589
- *
2590
- * Concurrent backup/restore calls on the same sandbox are serialized.
2591
- *
2592
- * Partially-written files in the target directory may not be captured
2593
- * consistently. Completed writes are captured.
2594
- *
2595
- * NOTE: Expired backups are not automatically deleted from R2. Configure
2596
- * R2 lifecycle rules on the BACKUP_BUCKET to garbage-collect objects
2597
- * under the `backups/` prefix after the desired retention period.
2598
- */
2599
- createBackup(options: BackupOptions): Promise<DirectoryBackup>;
2600
- private doCreateBackup;
2601
- /**
2602
- * Local-dev implementation of createBackup.
2603
- * Uses the R2 binding directly instead of presigned URLs.
2604
- * Archive format is identical to production (squashfs + meta.json).
2605
- */
2606
- private doCreateBackupLocal;
2607
- /**
2608
- * Restore a backup from R2 into a directory.
2609
- *
2610
- * **Production flow** (`localBucket` not set):
2611
- * 1. DO reads metadata from R2 and checks TTL
2612
- * 2. Container mounts the backup archive from R2 via s3fs
2613
- * 3. Container mounts the squashfs archive with FUSE overlayfs
2614
- *
2615
- * The target directory becomes an overlay mount with the backup as a
2616
- * read-only lower layer and a writable upper layer for copy-on-write.
2617
- * Any processes writing to the directory should be stopped first.
2618
- *
2619
- * **Mount Lifecycle**: The FUSE overlay mount persists only while the
2620
- * container is running. When the sandbox sleeps or the container restarts,
2621
- * the mount is lost and the directory becomes empty. Re-restore from the
2622
- * backup handle to recover. This is an ephemeral restore, not a persistent
2623
- * extraction.
2624
- *
2625
- * **Local-dev flow** (`localBucket: true` on the originating `createBackup` call):
2626
- * 1. DO reads metadata and checks TTL via R2 binding
2627
- * 2. DO downloads the archive from R2 and writes it to the container
2628
- * 3. Container extracts the archive with `unsquashfs` (no FUSE needed)
2629
- *
2630
- * The backup is restored into `backup.dir`. This may differ from the
2631
- * directory that was originally backed up, allowing cross-directory restore.
2632
- *
2633
- * Overlapping backups are independent: restoring a parent directory
2634
- * overwrites everything inside it, including subdirectories that were
2635
- * backed up separately. When restoring both, restore the parent first.
2636
- *
2637
- * Concurrent backup/restore calls on the same sandbox are serialized.
2638
- */
2639
- restoreBackup(backup: DirectoryBackup): Promise<RestoreBackupResult>;
2640
- private doRestoreBackup;
1653
+ connect(req: ExtensionConnectRequest): Promise<unknown>;
1654
+ /** Health snapshot, probing the sidecar with a `__ping__` when running. */
1655
+ health(packageHash: string): Promise<ExtensionHealth>;
1656
+ /** Stop a sidecar and release its capnweb session. */
1657
+ stop(packageHash: string): Promise<void>;
1658
+ }
1659
+ /**
1660
+ * RPC surface the Sandbox DO exposes to the container over the existing
1661
+ * capnweb session. The container reaches it via
1662
+ * `session.getRemoteMain<SandboxControlCallback>()` and invokes methods
1663
+ * to push control-plane events (today: tunnel exits) back to the DO.
1664
+ *
1665
+ * One stable target per sandbox; not per-tunnel. Reusable seam for
1666
+ * future container→DO events.
1667
+ */
1668
+ interface SandboxControlCallback {
2641
1669
  /**
2642
- * Local-dev implementation of restoreBackup.
2643
- * Uses the R2 binding directly instead of presigned URLs, and
2644
- * unsquashfs for extraction instead of squashfuse + fuse-overlayfs.
1670
+ * Called by the container when a `cloudflared` process exits for any
1671
+ * reason SIGTERM from `destroyTunnel`, container-initiated SIGKILL,
1672
+ * network failure, segfault. `exitCode` is `null` if the process was
1673
+ * signalled rather than exited cleanly.
2645
1674
  */
2646
- private doRestoreBackupLocal;
2647
- private configureR2EgressOutbound;
2648
- private configureS3CredentialProxyOutbound;
1675
+ onTunnelExit(id: string, port: number, exitCode: number | null): Promise<void>;
2649
1676
  }
2650
1677
  //#endregion
2651
- 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 };
2652
- //# sourceMappingURL=sandbox-44kEJjAc.d.ts.map
1678
+ export { RenameFileResult as $, ExecResult as A, ListFilesOptions as B, BucketProvider as C, DirectoryBackup as D, DeleteFileResult as E, FileMetadata as F, MountBucketOptions as G, LocalMountBucketOptions as H, FileStreamEvent as I, ProcessOptions as J, MoveFileResult as K, FileWatchSSEEvent as L, FileChunk as M, FileEncoding as N, ExecEvent as O, FileExistsResult as P, RemoteMountBucketOptions as Q, GitCheckoutResult as R, BucketCredentials as S, CheckChangesResult as T, LogEvent as U, ListFilesResult as V, MkdirResult as W, ReadFileResult as X, ProcessStatus as Y, ReadFileStreamResult as Z, SandboxWatchAPI as _, RunCodeOptions as _t, SandboxAPI as a, WaitForLogResult as at, BackupOptions as b, SandboxControlCallback as c, WriteFileResult as ct, SandboxGitAPI as d, isProcessStatus as dt, RestoreBackupResult as et, SandboxInterpreterAPI as f, PtyOptions as ft, SandboxUtilsAPI as g, ExecutionResult as gt, SandboxTunnelsAPI as h, Execution as ht, QuickTunnelInfo as i, StreamOptions as it, ExecutionSession as j, ExecOptions as k, SandboxExtensionsAPI as l, isExecResult as lt, SandboxProcessesAPI as m, CreateContextOptions as mt, ExtensionPackage as n, SessionDeleteResult as nt, SandboxBackupAPI as o, WaitForPortOptions as ot, SandboxPortsAPI as p, CodeContext as pt, Process as q, NamedTunnelInfo as r, SessionOptions as rt, SandboxCommandsAPI as s, WatchOptions as st, ExtensionHealth as t, SandboxOptions as tt, SandboxFilesAPI as u, isProcess as ut, TunnelInfo as v, CheckChangesOptions as w, BaseExecOptions as x, TunnelOptions as y, ISandbox as z };
1679
+ //# sourceMappingURL=rpc-types-PBUY-xXM.d.ts.map