@cloudflare/sandbox 0.13.0-next.651.1 → 0.13.0-next.709.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 (67) hide show
  1. package/Dockerfile +12 -17
  2. package/README.md +48 -2
  3. package/dist/bridge/index.d.ts.map +1 -1
  4. package/dist/bridge/index.js +1365 -1054
  5. package/dist/bridge/index.js.map +1 -1
  6. package/dist/{contexts-BS0Bs6IU.d.ts → contexts-1EsLHByO.d.ts} +240 -15
  7. package/dist/contexts-1EsLHByO.d.ts.map +1 -0
  8. package/dist/{dist-DF8sudAg.js → dist-Duor5GbS.js} +38 -147
  9. package/dist/dist-Duor5GbS.js.map +1 -0
  10. package/dist/errors/index.d.ts +4 -0
  11. package/dist/errors/index.js +4 -0
  12. package/dist/{errors-BG6NZiPD.js → errors-CXR0xBpw.js} +82 -13
  13. package/dist/errors-CXR0xBpw.js.map +1 -0
  14. package/dist/errors-QYlSkVGz.js +893 -0
  15. package/dist/errors-QYlSkVGz.js.map +1 -0
  16. package/dist/extensions/index.d.ts +4 -74
  17. package/dist/extensions/index.js +5 -152
  18. package/dist/extensions-CFB2xHqY.js +1023 -0
  19. package/dist/extensions-CFB2xHqY.js.map +1 -0
  20. package/dist/filesystem-BWAZCZER.d.ts +732 -0
  21. package/dist/filesystem-BWAZCZER.d.ts.map +1 -0
  22. package/dist/git/index.d.ts +63 -0
  23. package/dist/git/index.d.ts.map +1 -0
  24. package/dist/git/index.js +338 -0
  25. package/dist/git/index.js.map +1 -0
  26. package/dist/index-Bs4bqXDR.d.ts +438 -0
  27. package/dist/index-Bs4bqXDR.d.ts.map +1 -0
  28. package/dist/index-HNYBk-az.d.ts +444 -0
  29. package/dist/index-HNYBk-az.d.ts.map +1 -0
  30. package/dist/index.d.ts +487 -181
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +12 -43
  33. package/dist/index.js.map +1 -1
  34. package/dist/interpreter/index.d.ts +311 -0
  35. package/dist/interpreter/index.d.ts.map +1 -0
  36. package/dist/interpreter/index.js +292 -0
  37. package/dist/interpreter/index.js.map +1 -0
  38. package/dist/openai/index.d.ts +5 -4
  39. package/dist/openai/index.d.ts.map +1 -1
  40. package/dist/openai/index.js +11 -6
  41. package/dist/openai/index.js.map +1 -1
  42. package/dist/opencode/index.d.ts +133 -161
  43. package/dist/opencode/index.d.ts.map +1 -1
  44. package/dist/opencode/index.js +284 -203
  45. package/dist/opencode/index.js.map +1 -1
  46. package/dist/process-types-GStiZ8f8.d.ts +73 -0
  47. package/dist/process-types-GStiZ8f8.d.ts.map +1 -0
  48. package/dist/sandbox-Auuwfnur.js +10010 -0
  49. package/dist/sandbox-Auuwfnur.js.map +1 -0
  50. package/dist/sandbox-BbAabq93.d.ts +42 -0
  51. package/dist/sandbox-BbAabq93.d.ts.map +1 -0
  52. package/dist/xterm/index.d.ts +11 -7
  53. package/dist/xterm/index.d.ts.map +1 -1
  54. package/dist/xterm/index.js +61 -18
  55. package/dist/xterm/index.js.map +1 -1
  56. package/package.json +28 -4
  57. package/dist/contexts-BS0Bs6IU.d.ts.map +0 -1
  58. package/dist/dist-DF8sudAg.js.map +0 -1
  59. package/dist/errors-BG6NZiPD.js.map +0 -1
  60. package/dist/extensions/index.d.ts.map +0 -1
  61. package/dist/extensions/index.js.map +0 -1
  62. package/dist/rpc-types-PBUY-xXM.d.ts +0 -1679
  63. package/dist/rpc-types-PBUY-xXM.d.ts.map +0 -1
  64. package/dist/sandbox-BgwMBQ7S.js +0 -8273
  65. package/dist/sandbox-BgwMBQ7S.js.map +0 -1
  66. package/dist/sandbox-D_MMqExx.d.ts +0 -1077
  67. package/dist/sandbox-D_MMqExx.d.ts.map +0 -1
package/dist/index.d.ts CHANGED
@@ -1,131 +1,14 @@
1
- import { n as Sandbox, r as getSandbox, t as ContainerProxy } from "./sandbox-D_MMqExx.js";
2
- import { A as ExecResult, B as ListFilesOptions, C as BucketProvider, D as DirectoryBackup, F as FileMetadata, G as MountBucketOptions, H as LocalMountBucketOptions, I as FileStreamEvent, J as ProcessOptions, L as FileWatchSSEEvent, M as FileChunk, O as ExecEvent, Q as RemoteMountBucketOptions, R as GitCheckoutResult, S as BucketCredentials, T as CheckChangesResult, U as LogEvent, Y as ProcessStatus, _t as RunCodeOptions, at as WaitForLogResult, b as BackupOptions, dt as isProcessStatus, et as RestoreBackupResult, f as SandboxInterpreterAPI, ft as PtyOptions, gt as ExecutionResult, ht as Execution, i as QuickTunnelInfo, it as StreamOptions, j as ExecutionSession, k as ExecOptions, lt as isExecResult, mt as CreateContextOptions, ot as WaitForPortOptions, pt as CodeContext, q as Process, r as NamedTunnelInfo, rt as SessionOptions, st as WatchOptions, tt as SandboxOptions, ut as isProcess, v as TunnelInfo, w as CheckChangesOptions, x as BaseExecOptions, y as TunnelOptions, z as ISandbox } from "./rpc-types-PBUY-xXM.js";
3
- import { a as ContainerUnavailableContext, c as ProcessExitedBeforeReadyContext, d as RPCTransportErrorKind, f as SessionTerminatedContext, h as ErrorCode, i as BackupRestoreContext, l as ProcessReadyTimeoutContext, m as OperationType, n as BackupExpiredContext, o as InvalidBackupConfigContext, p as ErrorResponse, r as BackupNotFoundContext, t as BackupCreateContext, u as RPCTransportContext } from "./contexts-BS0Bs6IU.js";
1
+ import { H as RPCTransportErrorKind, V as RPCTransportContext, Z as ErrorCode } from "./contexts-1EsLHByO.js";
2
+ import { c as WaitForLogResult, i as ProcessLogEvent, n as ProcessFailure, o as ProcessStatus, r as ProcessLogCursor, s as SandboxCommand, t as ProcessExit } from "./process-types-GStiZ8f8.js";
3
+ import { A as CreateTerminalOptions, C as BucketCredentials, D as MountBucketOptions, E as LocalMountBucketOptions, F as TerminalOutputOptions, G as ProcessTextOutputOptions, H as ProcessLogsOptions, I as TerminalOutputSubscriptionAPI, J as WaitForExitOptions, K as SandboxOptions, L as TerminalSnapshot, M as Terminal, N as TerminalOutputCursor, O as RemoteMountBucketOptions, P as TerminalOutputEvent, R as ExecOptions, S as BackupOptions, T as DirectoryBackup, U as ProcessOutput, W as ProcessOutputOptions, X as WaitForPortOptions, Y as WaitForLogOptions, _ as RenameFileResult, a as FileChunk, b as WriteFileResult, c as FileMetadata, d as ListFilesOptions, f as ListFilesResult, g as ReadFileStreamResult, h as ReadFileResult, i as DeleteFileResult, k as RestoreBackupResult, l as FileStreamEvent, m as MoveFileResult, o as FileEncoding, p as MkdirResult, q as SandboxProcess, r as CheckChangesResult, s as FileExistsResult, t as CheckChangesOptions, u as FileWatchSSEEvent, v as WatchOptions, w as BucketProvider } from "./filesystem-BWAZCZER.js";
4
+ import { t as ISandbox } from "./sandbox-BbAabq93.js";
5
+ import { _ as QuickTunnelInfo, d as sandboxRuntimeCall, f as ProcessPullSubscriptionRPC, g as NamedTunnelInfo, n as ExtensionRuntimeCall, p as ProcessRPCDescriptor, s as HTTPAuthInterceptorParams, v as TunnelInfo, y as TunnelOptions } from "./index-Bs4bqXDR.js";
6
+ import { $ as TerminalNotFoundError, G as ContainerUnavailableError, H as BackupExpiredError, J as InvalidTerminalCwdError, K as InvalidBackupConfigError, Q as TerminalControlError, U as BackupNotFoundError, V as BackupCreateError, W as BackupRestoreError, X as RPCTransportError, Y as OperationInterruptedError, Z as StaleTerminalHandleError, a as InvalidProcessCursorError, c as ProcessAbortedError, d as ProcessExitedBeforeReadyError, f as ProcessNotFoundError, g as StaleProcessHandleError, h as ProcessWaitTimeoutError, l as ProcessError, m as ProcessSpawnFailedError, n as RuntimeControlProtocolError, o as InvalidProcessCwdError, p as ProcessReadyTimeoutError, q as InvalidTerminalCursorError, s as InvalidProcessEnvironmentError, t as RuntimeIdentityInactiveError, u as ProcessExitedBeforeLogError } from "./index-HNYBk-az.js";
7
+ import { Container, ContainerProxy as ContainerProxy$1, ContainerStartConfigOptions } from "@cloudflare/containers";
8
+ import { RpcTarget, RpcTransport } from "capnweb";
4
9
 
5
- //#region src/errors/classes.d.ts
6
-
7
- /**
8
- * Base SDK error that wraps ErrorResponse
9
- * Preserves all error information from container
10
- */
11
- declare class SandboxError<TContext = Record<string, unknown>> extends Error {
12
- readonly errorResponse: ErrorResponse<TContext>;
13
- constructor(errorResponse: ErrorResponse<TContext>, options?: {
14
- cause?: unknown;
15
- });
16
- get code(): ErrorCode;
17
- get context(): TContext;
18
- get httpStatus(): number;
19
- get operation(): OperationType | undefined;
20
- get suggestion(): string | undefined;
21
- get timestamp(): string;
22
- get documentation(): string | undefined;
23
- toJSON(): {
24
- name: string;
25
- message: string;
26
- code: ErrorCode;
27
- context: TContext;
28
- httpStatus: number;
29
- operation: OperationType | undefined;
30
- suggestion: string | undefined;
31
- timestamp: string;
32
- documentation: string | undefined;
33
- stack: string | undefined;
34
- };
35
- }
36
- /**
37
- * Error thrown when a session's underlying shell exited without an explicit
38
- * `destroy()` call (user ran `exit`, the shell crashed, or a child process
39
- * took the shell down). The session-local state is gone, but the next call
40
- * with the same sessionId will transparently start a fresh session.
41
- */
42
- declare class SessionTerminatedError extends SandboxError<SessionTerminatedContext> {
43
- constructor(errorResponse: ErrorResponse<SessionTerminatedContext>);
44
- get sessionId(): string;
45
- get exitCode(): number | null;
46
- }
47
- /**
48
- * Error thrown when a process does not become ready within the timeout period
49
- */
50
- declare class ProcessReadyTimeoutError extends SandboxError<ProcessReadyTimeoutContext> {
51
- constructor(errorResponse: ErrorResponse<ProcessReadyTimeoutContext>);
52
- get processId(): string;
53
- get command(): string;
54
- get condition(): string;
55
- get timeout(): number;
56
- }
57
- /**
58
- * Error thrown when a process exits before becoming ready
59
- */
60
- declare class ProcessExitedBeforeReadyError extends SandboxError<ProcessExitedBeforeReadyContext> {
61
- constructor(errorResponse: ErrorResponse<ProcessExitedBeforeReadyContext>);
62
- get processId(): string;
63
- get command(): string;
64
- get condition(): string;
65
- get exitCode(): number;
66
- }
67
- /**
68
- * Error thrown when a backup is not found in R2
69
- */
70
- declare class BackupNotFoundError extends SandboxError<BackupNotFoundContext> {
71
- constructor(errorResponse: ErrorResponse<BackupNotFoundContext>);
72
- get backupId(): string;
73
- }
74
- /**
75
- * Error thrown when a backup has expired (past its TTL)
76
- */
77
- declare class BackupExpiredError extends SandboxError<BackupExpiredContext> {
78
- constructor(errorResponse: ErrorResponse<BackupExpiredContext>);
79
- get backupId(): string;
80
- get expiredAt(): string | undefined;
81
- }
82
- /**
83
- * Error thrown when backup configuration or inputs are invalid
84
- */
85
- declare class InvalidBackupConfigError extends SandboxError<InvalidBackupConfigContext> {
86
- constructor(errorResponse: ErrorResponse<InvalidBackupConfigContext>);
87
- get reason(): string;
88
- }
89
- /**
90
- * Error thrown when backup creation fails
91
- */
92
- declare class BackupCreateError extends SandboxError<BackupCreateContext> {
93
- constructor(errorResponse: ErrorResponse<BackupCreateContext>);
94
- get dir(): string;
95
- get backupId(): string | undefined;
96
- }
97
- /**
98
- * Error thrown when backup restoration fails
99
- */
100
- declare class BackupRestoreError extends SandboxError<BackupRestoreContext> {
101
- constructor(errorResponse: ErrorResponse<BackupRestoreContext>);
102
- get dir(): string;
103
- get backupId(): string;
104
- }
105
- declare class ContainerUnavailableError extends SandboxError<ContainerUnavailableContext> {
106
- constructor(errorResponse: ErrorResponse<ContainerUnavailableContext>);
107
- }
108
- /**
109
- * Raised when the capnweb WebSocket session itself fails on the SDK side.
110
- * Unlike the rest of the SandboxError tree, the container never produces
111
- * this error — it is synthesised by `translateRPCError` from the plain
112
- * Errors capnweb / DeferredTransport raise when the connection dies.
113
- *
114
- * `kind` distinguishes the failure mode (peer close, upgrade failed, etc.)
115
- * so callers can branch on a structured code instead of substring-matching
116
- * on the message.
117
- *
118
- * Always retryable: the SDK opens a fresh connection on the next call.
119
- */
120
- declare class RPCTransportError extends SandboxError<RPCTransportContext> {
121
- constructor(errorResponse: ErrorResponse<RPCTransportContext>, options?: {
122
- cause?: unknown;
123
- });
124
- get kind(): RPCTransportErrorKind;
125
- get originalMessage(): string;
126
- }
127
- //#endregion
128
10
  //#region src/file-stream.d.ts
11
+
129
12
  /**
130
13
  * Stream a file from the sandbox with automatic base64 decoding for binary files
131
14
  *
@@ -166,39 +49,495 @@ declare function collectFile(stream: ReadableStream<Uint8Array>): Promise<{
166
49
  metadata: FileMetadata;
167
50
  }>;
168
51
  //#endregion
169
- //#region src/interpreter.d.ts
170
- declare class CodeInterpreter {
171
- private getInterpreterClient;
172
- private contexts;
173
- constructor(interpreterClient: SandboxInterpreterAPI | (() => SandboxInterpreterAPI));
52
+ //#region src/platform-errors.d.ts
53
+ /**
54
+ * Whether an error was raised because the current Durable Object isolate was
55
+ * superseded by a deploy/code update. In-process retries are futile for this
56
+ * class because the invocation keeps running on the old isolate; callers
57
+ * should return control to the platform or retry from a fresh request.
58
+ */
59
+ declare function isDurableObjectCodeUpdateReset(error: unknown): boolean;
60
+ /**
61
+ * Whether an error represents a transient platform lifecycle/storage failure,
62
+ * not an application-level sandbox failure.
63
+ */
64
+ declare function isPlatformTransientError(error: unknown): boolean;
65
+ //#endregion
66
+ //#region src/pty/rpc-types.d.ts
67
+ interface TerminalCapabilityRPC {
68
+ getSnapshot(): Promise<TerminalSnapshot | null>;
69
+ openOutput(options?: Omit<TerminalOutputOptions, 'signal'>): Promise<ProcessPullSubscriptionRPC<TerminalOutputEvent>>;
70
+ write(data: Uint8Array): Promise<void>;
71
+ resize(cols: number, rows: number): Promise<void>;
72
+ interrupt(): Promise<void>;
73
+ terminate(): Promise<void>;
74
+ authorizeConnection(): Promise<string>;
75
+ }
76
+ interface TerminalRPCDescriptor {
77
+ snapshot: TerminalSnapshot;
78
+ runtimeIncarnationID: string;
79
+ capability: TerminalCapabilityRPC;
80
+ }
81
+ //#endregion
82
+ //#region src/pty/proxy.d.ts
83
+ interface TerminalHandleStub {
84
+ get(id: string): Promise<TerminalSnapshot | null>;
85
+ output(id: string, options?: Omit<TerminalOutputOptions, 'signal'>): Promise<TerminalOutputSubscriptionAPI | ProcessPullSubscriptionRPC<TerminalOutputEvent>>;
86
+ write(id: string, data: Uint8Array): Promise<void>;
87
+ resize(id: string, cols: number, rows: number): Promise<void>;
88
+ interrupt(id: string): Promise<void>;
89
+ terminate(id: string): Promise<void>;
90
+ fetch(request: Request): Promise<Response>;
91
+ }
92
+ declare function proxyTerminal(stub: Pick<TerminalHandleStub, 'fetch'>, terminalId: string, request: Request, options: {
93
+ cursor?: TerminalOutputCursor;
94
+ cols?: number;
95
+ rows?: number;
96
+ runtimeIncarnationID: string;
97
+ }): Promise<Response>;
98
+ //#endregion
99
+ //#region src/backup/restore-fault-injection.d.ts
100
+ type BackupRestoreFaultPhase = 'after_archive_ready';
101
+ type BackupRestoreTestFault = {
102
+ phase: BackupRestoreFaultPhase;
103
+ mode: 'transport_disposed';
104
+ times: number;
105
+ };
106
+ //#endregion
107
+ //#region src/storage-mount/errors.d.ts
108
+ /**
109
+ * Base error for bucket mounting operations
110
+ */
111
+ declare class BucketMountError extends Error {
112
+ readonly code: ErrorCode;
113
+ constructor(message: string, code?: ErrorCode);
114
+ }
115
+ /**
116
+ * Thrown when S3FS mount command fails
117
+ */
118
+ declare class S3FSMountError extends BucketMountError {
119
+ constructor(message: string);
120
+ }
121
+ /**
122
+ * Thrown when fusermount -u fails to unmount a FUSE filesystem
123
+ */
124
+ declare class BucketUnmountError extends BucketMountError {
125
+ constructor(message: string);
126
+ }
127
+ /**
128
+ * Thrown when no credentials found in environment
129
+ */
130
+ declare class MissingCredentialsError extends BucketMountError {
131
+ constructor(message: string);
132
+ }
133
+ /**
134
+ * Thrown when bucket name, mount path, or options are invalid
135
+ */
136
+ declare class InvalidMountConfigError extends BucketMountError {
137
+ constructor(message: string);
138
+ }
139
+ //#endregion
140
+ //#region src/storage-mount/outbound/container-proxy.d.ts
141
+ declare class ContainerProxy extends ContainerProxy$1 {
142
+ fetch(request: Request): Promise<Response>;
143
+ }
144
+ //#endregion
145
+ //#region src/tunnels/tunnel-service.d.ts
146
+ interface TunnelsHandler {
147
+ get(port: number, options?: TunnelOptions): Promise<TunnelInfo>;
148
+ list(): Promise<TunnelInfo[]>;
149
+ destroy(portOrInfo: number | TunnelInfo): Promise<void>;
150
+ }
151
+ //#endregion
152
+ //#region src/sandbox.d.ts
153
+ type SandboxConfiguration = {
154
+ sandboxName?: {
155
+ name: string;
156
+ normalizeId?: boolean;
157
+ };
158
+ sleepAfter?: string | number;
159
+ keepAlive?: boolean;
160
+ containerTimeouts?: NonNullable<SandboxOptions['containerTimeouts']>;
161
+ };
162
+ type InternalSandboxRPCMethod = 'authorizePortRequest';
163
+ type SandboxClient<T> = Omit<T, keyof ISandbox | InternalSandboxRPCMethod> & ISandbox;
164
+ type CancellationOptions = {
165
+ abort?: AbortSignal;
166
+ instanceGetTimeoutMS?: number;
167
+ portReadyTimeoutMS?: number;
168
+ waitInterval?: number;
169
+ };
170
+ type StartAndWaitForPortsOptions = {
171
+ startOptions?: ContainerStartConfigOptions;
172
+ ports?: number | number[];
173
+ cancellationOptions?: CancellationOptions;
174
+ };
175
+ declare function getSandbox<T extends Sandbox<any>>(ns: DurableObjectNamespace<T>, id: string, options?: SandboxOptions): SandboxClient<T>;
176
+ declare class Sandbox<Env = unknown> extends Container<Env> {
177
+ #private;
178
+ defaultPort: number;
179
+ sleepAfter: string | number;
180
+ private runtimeSessions;
181
+ private runtimeLifecycle;
182
+ private runtimeRunner;
183
+ private sandboxName;
184
+ private tunnelServiceHandle;
185
+ private tunnelsHandler;
186
+ private tunnelExitHandler;
187
+ private readonly controlCallback;
188
+ private normalizeId;
189
+ envVars: Record<string, string>;
190
+ private readonly portRequestTokens;
191
+ private logger;
192
+ private keepAliveEnabled;
193
+ private bucketMounts;
194
+ private currentLifetime;
195
+ private backupService;
196
+ private previewService;
197
+ private resourceActivityGate;
198
+ private r2AccessKeyId;
199
+ private r2SecretAccessKey;
200
+ private namedTunnelConfigResolver;
201
+ /**
202
+ * Default container startup timeouts (conservative for production)
203
+ * Based on Cloudflare docs: "Containers take several minutes to provision"
204
+ */
205
+ private readonly DEFAULT_CONTAINER_TIMEOUTS;
206
+ /**
207
+ * Active container timeout configuration
208
+ * Can be set via options, env vars, or defaults
209
+ */
210
+ private containerTimeouts;
211
+ /**
212
+ * True once containerTimeouts has been written to storage at least once
213
+ * (either via setContainerTimeouts or restored on cold start). Gates the
214
+ * idempotency check in setContainerTimeouts so a first explicit call
215
+ * persists even when the requested values already equal the in-memory
216
+ * defaults, distinguishing "user intent recorded" from "running on
217
+ * env/SDK defaults".
218
+ */
219
+ private hasStoredContainerTimeouts;
220
+ /**
221
+ * Dispatch method for tunnel operations.
222
+ * Called by the client-side proxy created in getSandbox() to provide
223
+ * the `sandbox.tunnels` API without relying on RPC pipelining through
224
+ * property getters, which vite-plugin does not currently support. This
225
+ * local method dispatch uses standard function application, so new
226
+ * Workers RPC pipelining traits on `TunnelsRpcTarget` also need an
227
+ * explicit path here before the proxy can expose them.
228
+ */
229
+ callTunnels(method: string, args: unknown[]): Promise<unknown>;
230
+ callExtension(extensionName: string, method: string, args: unknown[]): Promise<unknown>;
231
+ private renewActivityTimeoutIfAvailable;
232
+ private getRuntimePortStub;
233
+ constructor(ctx: DurableObjectState<{}>, env: Env);
234
+ setSandboxName(name: string, normalizeId?: boolean): Promise<void>;
235
+ configure(configuration: SandboxConfiguration): Promise<void>;
236
+ setSleepAfter(sleepAfter: string | number): Promise<void>;
237
+ setKeepAlive(keepAlive: boolean): Promise<void>;
238
+ setEnvVars(envVars: Record<string, string | undefined>): Promise<void>;
239
+ setContainerTimeouts(timeouts: NonNullable<SandboxOptions['containerTimeouts']>): Promise<void>;
240
+ private validateTimeout;
241
+ private getDefaultTimeouts;
242
+ /**
243
+ * Mount an S3-compatible bucket as a local directory.
244
+ */
245
+ mountBucket(bucket: string, mountPath: string, options: MountBucketOptions): Promise<void>;
246
+ /**
247
+ * Manually unmount a bucket filesystem.
248
+ */
249
+ unmountBucket(mountPath: string): Promise<void>;
250
+ /**
251
+ * In-flight `destroy()` promise. While set, concurrent callers coalesce
252
+ * onto the same teardown instead of triggering a second one. Cleared when
253
+ * the underlying work settles, so a later call that genuinely needs to
254
+ * recreate a destroyed sandbox still runs.
255
+ *
256
+ * If the underlying teardown hangs (e.g. `super.destroy()` never resolves
257
+ * because the Containers control plane is unresponsive), every coalesced
258
+ * caller hangs on the same promise until the Durable Object is evicted.
259
+ * This is deliberate: a second concurrent teardown would not make a stuck
260
+ * control plane unstuck, and spawning one would defeat the point of
261
+ * coalescing. Callers that need bounded waits must apply their own
262
+ * timeout around `destroy()`.
263
+ */
264
+ private inflightDestroy;
265
+ /**
266
+ * Cleanup and destroy the sandbox container.
267
+ *
268
+ * Concurrent calls coalesce: if a previous `destroy()` is still in flight,
269
+ * subsequent calls await the same underlying work instead of starting a
270
+ * second teardown. A canonical `sandbox.destroy.coalesced` event is logged
271
+ * per coalesced call so repeated destroy traffic is observable.
272
+ */
273
+ destroy(): Promise<void>;
274
+ private doDestroy;
275
+ private performRuntimeStop;
276
+ private runBoundedDestroyRuntimeCleanup;
277
+ private cleanupRuntimeBeforeDestroy;
278
+ private createTeardownTunnelsHandle;
279
+ private createDurableDestroyTunnelsHandle;
280
+ private createDestroyTunnelsHandle;
281
+ onStart(): Promise<void>;
282
+ start(options?: Parameters<Container<Env>['start']>[0]): Promise<void>;
283
+ startAndWaitForPorts(args: StartAndWaitForPortsOptions): Promise<void>;
284
+ startAndWaitForPorts(portsOrArgs?: number | number[] | StartAndWaitForPortsOptions, cancellationOptions?: CancellationOptions, startOptions?: ContainerStartConfigOptions): Promise<void>;
285
+ stop(signal?: Parameters<Container<Env>['stop']>[0]): Promise<void>;
286
+ onStop(): Promise<void>;
287
+ onError(error: unknown): void;
288
+ /**
289
+ * Override Container.containerFetch to route direct forwarding through runtime admission.
290
+ */
291
+ containerFetch(requestOrUrl: Request | string | URL, portOrInit?: number | RequestInit, portParam?: number): Promise<Response>;
292
+ private containerStartupErrorResponse;
293
+ /**
294
+ * Helper: Check if error is "no container instance available"
295
+ * This indicates the container VM is still being provisioned.
296
+ */
297
+ private isNoInstanceError;
298
+ /**
299
+ * Helper: Check if error is a transient startup error that should trigger retry
300
+ *
301
+ * These errors occur during normal container startup and are recoverable:
302
+ * - Port not yet mapped (container starting, app not listening yet)
303
+ * - Connection refused (port mapped but app not ready)
304
+ * - Timeouts during startup (recoverable with retry)
305
+ * - Network transients (temporary connectivity issues)
306
+ *
307
+ * Errors NOT included (permanent failures):
308
+ * - "no such image" - missing Docker image
309
+ * - "container already exists" - name collision
310
+ * - Configuration errors
311
+ */
312
+ private isTransientStartupError;
313
+ /**
314
+ * Helper: Check if error is a permanent startup failure that will never recover
315
+ *
316
+ * These errors indicate resource exhaustion, misconfiguration, or missing images.
317
+ * Retrying will never succeed, so the SDK should fail fast with HTTP 500.
318
+ *
319
+ * Error sources (traced from platform internals):
320
+ * - Container runtime: OOM, PID limit
321
+ * - Scheduling/provisioning: no matching app, no namespace configured
322
+ * - workerd container-client.c++: no such image
323
+ * - @cloudflare/containers: did not call start
324
+ */
325
+ private isPermanentStartupError;
326
+ /**
327
+ * Helper: Parse containerFetch arguments (supports multiple signatures)
328
+ */
329
+ private parseContainerFetchArgs;
330
+ onActivityExpired(): Promise<void>;
331
+ private getPreviewForwardingContainer;
332
+ fetch(request: Request): Promise<Response>;
333
+ wsConnect(request: Request, port: number): Promise<Response>;
334
+ authorizePortRequest(port: number, path: string): Promise<string>;
335
+ private connectWebSocket;
336
+ createTerminal(options: CreateTerminalOptions): Promise<TerminalRPCDescriptor>;
337
+ getTerminal(id: string): Promise<TerminalRPCDescriptor | null>;
338
+ listTerminals(): Promise<TerminalRPCDescriptor[]>;
339
+ private terminalDescriptor;
340
+ private terminalStub;
341
+ private determinePort;
342
+ exec(command: SandboxCommand, options?: ExecOptions): Promise<ProcessRPCDescriptor>;
343
+ private processDescriptor;
344
+ private processCapabilityLifecycle;
345
+ /** Internal bridge liveness read that neither starts nor renews a runtime. */
346
+ isRuntimeActive(): Promise<boolean>;
347
+ getProcess(id: string): Promise<ProcessRPCDescriptor | null>;
348
+ listProcesses(): Promise<ProcessStatus[]>;
349
+ mkdir(path: string, options?: {
350
+ recursive?: boolean;
351
+ }): Promise<MkdirResult>;
352
+ writeFile(path: string, content: string | ReadableStream<Uint8Array>, options?: {
353
+ encoding?: string;
354
+ }): Promise<{
355
+ success: boolean;
356
+ path: string;
357
+ bytesWritten: number;
358
+ timestamp: string;
359
+ } | WriteFileResult>;
360
+ deleteFile(path: string): Promise<DeleteFileResult>;
361
+ renameFile(oldPath: string, newPath: string): Promise<RenameFileResult>;
362
+ moveFile(sourcePath: string, destinationPath: string): Promise<MoveFileResult>;
363
+ /**
364
+ * Read a file from the sandbox.
365
+ *
366
+ * @param encoding - How to encode the returned content:
367
+ * - `undefined` (default): auto-detect from MIME type (text → UTF-8 string, binary → base64 string)
368
+ * - `'utf-8'` / `'utf8'`: always return as UTF-8 string
369
+ * - `'base64'`: always return as base64-encoded string
370
+ * - `'none'`: return a result whose `content` is a raw binary `ReadableStream<Uint8Array>`
371
+ * with no encoding overhead.
372
+ */
373
+ readFile(path: string, options: {
374
+ encoding: 'none';
375
+ }): Promise<ReadFileStreamResult>;
376
+ readFile(path: string, options?: {
377
+ encoding?: Exclude<FileEncoding, 'none'>;
378
+ }): Promise<ReadFileResult>;
379
+ /**
380
+ * Stream a file from the sandbox using Server-Sent Events
381
+ * Returns a ReadableStream that can be consumed with streamFile() or collectFile() utilities
382
+ * @param path - Path to the file to stream
383
+ */
384
+ createWorkspaceArchive(options?: {
385
+ root: string;
386
+ excludes?: readonly string[];
387
+ }): Promise<string>;
388
+ extractWorkspaceArchive(options: {
389
+ root: string;
390
+ archivePath: string;
391
+ }): Promise<void>;
392
+ cleanupWorkspaceArchive(archivePath: string): Promise<void>;
393
+ cleanupMountDirectory(mountPath: string): Promise<void>;
394
+ readFileStream(path: string): Promise<ReadableStream<Uint8Array>>;
395
+ listFiles(path: string, options?: ListFilesOptions): Promise<ListFilesResult>;
396
+ exists(path: string): Promise<FileExistsResult>;
397
+ /**
398
+ * Watch a directory for file system changes using native inotify.
399
+ *
400
+ * The returned promise resolves only after the watcher is established on the
401
+ * filesystem, so callers can immediately perform actions that depend on the
402
+ * watch being active. The returned stream contains the full event sequence
403
+ * starting with the `watching` event.
404
+ *
405
+ * Consume the stream with `parseSSEStream<FileWatchSSEEvent>(stream)`.
406
+ *
407
+ * @param path - Path to watch (absolute or relative to /workspace)
408
+ * @param options - Watch options
409
+ */
410
+ watch(path: string, options?: WatchOptions): Promise<ReadableStream<Uint8Array>>;
411
+ /**
412
+ * Check whether a path changed while this caller was disconnected.
413
+ *
414
+ * Pass the `version` returned from a prior call in `options.since` to learn
415
+ * whether the path is unchanged, changed, or needs a full resync because the
416
+ * retained change state was reset.
417
+ *
418
+ * @param path - Path to check (absolute or relative to /workspace)
419
+ * @param options - Change-check options
420
+ */
421
+ checkChanges(path: string, options?: CheckChangesOptions): Promise<CheckChangesResult>;
422
+ /**
423
+ * Expose a port and get a preview URL for accessing services running in the sandbox
424
+ *
425
+ * Preview URL authorization survives transient container restarts, but
426
+ * forwarding is active only for the runtime where `exposePort()` was last
427
+ * called. Call `exposePort()` again after a restart to reactivate an
428
+ * existing URL for the current runtime.
429
+ *
430
+ * @param port - Port number to expose (1024-65535)
431
+ * @param options - Configuration options
432
+ * @param options.hostname - Your Worker's domain name (required for preview URL construction)
433
+ * @param options.name - Optional friendly name for the port
434
+ * @param options.token - Optional custom token for the preview URL (1-16 characters: lowercase letters, numbers, underscores)
435
+ * If not provided, a random 16-character token will be generated automatically
436
+ * @returns Preview URL information including the full URL, port number, and optional name
437
+ *
438
+ * @example
439
+ * // With auto-generated token
440
+ * const { url } = await sandbox.exposePort(8080, { hostname: 'example.com' });
441
+ * // url: https://8080-sandbox-id-abc123random4567.example.com
442
+ *
443
+ * @example
444
+ * // With custom token for stable URLs across deployments
445
+ * const { url } = await sandbox.exposePort(8080, {
446
+ * hostname: 'example.com',
447
+ * token: 'my_token_v1'
448
+ * });
449
+ * // url: https://8080-sandbox-id-my_token_v1.example.com
450
+ */
451
+ private runWakingComposite;
452
+ [sandboxRuntimeCall]: ExtensionRuntimeCall;
453
+ exposePort(port: number, options: {
454
+ name?: string;
455
+ hostname: string;
456
+ token?: string;
457
+ }): Promise<{
458
+ url: string;
459
+ port: number;
460
+ name?: string;
461
+ }>;
462
+ /**
463
+ * Revoke preview URL authorization and current-runtime activation for a port.
464
+ *
465
+ * Revocation is idempotent: calling this for a port with no preview state is
466
+ * still successful. The operation clears Durable Object-owned preview state
467
+ * only and does not contact, probe, wake, or clean up the container runtime.
468
+ */
469
+ unexposePort(port: number): Promise<void>;
174
470
  /**
175
- * Create a new code execution context
471
+ * Returns preview URLs that are currently forwardable in the active runtime.
472
+ * Durable authorization without current-runtime activation is omitted.
176
473
  */
177
- createCodeContext(options?: CreateContextOptions): Promise<CodeContext>;
474
+ getExposedPorts(hostname: string): Promise<{
475
+ url: string;
476
+ port: number;
477
+ status: "active";
478
+ }[]>;
178
479
  /**
179
- * Run code with optional context
480
+ * Returns whether a port is currently preview-forwardable.
481
+ * This checks Durable Object-owned auth and runtime activation without
482
+ * contacting or waking the container.
180
483
  */
181
- runCode(code: string, options?: RunCodeOptions): Promise<Execution>;
484
+ isPortExposed(port: number): Promise<boolean>;
182
485
  /**
183
- * Run code and return a streaming response
486
+ * Checks durable preview URL authorization for a port/token pair.
487
+ *
488
+ * This does not check whether the port is activated for the current runtime
489
+ * and is not sufficient to decide whether preview traffic may forward.
184
490
  */
185
- runCodeStream(code: string, options?: RunCodeOptions): Promise<ReadableStream>;
491
+ validatePortToken(port: number, token: string): Promise<boolean>;
186
492
  /**
187
- * List all code contexts
493
+ * Namespaced tunnel API. Quick tunnels are zero-config preview URLs
494
+ * backed by Cloudflare's trycloudflare service. Named tunnels bind a
495
+ * stable hostname under the configured Cloudflare zone.
496
+ *
497
+ * - `tunnels.get(port)` — idempotent. Returns the cached tunnel for
498
+ * `port` if one exists in DO storage, otherwise spawns a fresh
499
+ * cloudflared process and persists the record.
500
+ * - `tunnels.list()` — returns tunnels currently usable through this
501
+ * sandbox runtime.
502
+ * - `tunnels.destroy(portOrInfo)` — tear down by port number or by
503
+ * the record returned from `get()`.
504
+ *
505
+ * Container restarts drop quick-tunnel records because their
506
+ * `*.trycloudflare.com` URLs are tied to the dead cloudflared process.
507
+ * Named-tunnel records stay in storage and are marked for respawn so the
508
+ * next `get(port, { name })` call reuses the Cloudflare tunnel and DNS
509
+ * record while starting a fresh cloudflared process.
188
510
  */
189
- listCodeContexts(): Promise<CodeContext[]>;
511
+ get tunnels(): TunnelsHandler;
190
512
  /**
191
- * Delete a code context
513
+ * Lazily construct the tunnel subsystem handle. Called from the
514
+ * `tunnels` getter on first access and from sandbox lifecycle hooks
515
+ * when tunnel reconciliation or cleanup is needed.
192
516
  */
193
- deleteCodeContext(contextId: string): Promise<void>;
194
- private getOrCreateDefaultContext;
517
+ private ensureTunnelsBuilt;
518
+ /**
519
+ * Create a backup of a directory and upload it to R2.
520
+ *
521
+ * The returned DirectoryBackup handle is serializable. Store it anywhere
522
+ * (KV, D1, DO storage) and pass it to restoreBackup() later.
523
+ *
524
+ * Concurrent backup/restore calls on the same sandbox are serialized.
525
+ */
526
+ createBackup(options: BackupOptions): Promise<DirectoryBackup>;
527
+ /**
528
+ * Restore a backup from R2 into a directory.
529
+ *
530
+ * Production restores use a FUSE overlay mount. Local-bucket restores stream
531
+ * the archive through the R2 binding and extract it with unsquashfs.
532
+ *
533
+ * Concurrent backup/restore calls on the same sandbox are serialized.
534
+ */
535
+ restoreBackup(backup: DirectoryBackup): Promise<RestoreBackupResult>;
536
+ __setBackupRestoreFaultForTesting(fault: BackupRestoreTestFault | null): Promise<void>;
537
+ registerGitAuthInterceptor(params: HTTPAuthInterceptorParams): Promise<void>;
538
+ private getMountOutboundHost;
195
539
  }
196
540
  //#endregion
197
- //#region src/pty/proxy.d.ts
198
- declare function proxyTerminal(stub: {
199
- fetch: (request: Request) => Promise<Response>;
200
- }, sessionId: string, request: Request, options?: PtyOptions): Promise<Response>;
201
- //#endregion
202
541
  //#region src/request-handler.d.ts
203
542
  interface SandboxEnv<T extends Sandbox<any> = Sandbox<any>> {
204
543
  Sandbox: DurableObjectNamespace<T>;
@@ -233,38 +572,5 @@ declare function asyncIterableToSSEStream<T>(events: AsyncIterable<T>, options?:
233
572
  serialize?: (event: T) => string;
234
573
  }): ReadableStream<Uint8Array>;
235
574
  //#endregion
236
- //#region src/storage-mount/errors.d.ts
237
- /**
238
- * Base error for bucket mounting operations
239
- */
240
- declare class BucketMountError extends Error {
241
- readonly code: ErrorCode;
242
- constructor(message: string, code?: ErrorCode);
243
- }
244
- /**
245
- * Thrown when S3FS mount command fails
246
- */
247
- declare class S3FSMountError extends BucketMountError {
248
- constructor(message: string);
249
- }
250
- /**
251
- * Thrown when fusermount -u fails to unmount a FUSE filesystem
252
- */
253
- declare class BucketUnmountError extends BucketMountError {
254
- constructor(message: string);
255
- }
256
- /**
257
- * Thrown when no credentials found in environment
258
- */
259
- declare class MissingCredentialsError extends BucketMountError {
260
- constructor(message: string);
261
- }
262
- /**
263
- * Thrown when bucket name, mount path, or options are invalid
264
- */
265
- declare class InvalidMountConfigError extends BucketMountError {
266
- constructor(message: string);
267
- }
268
- //#endregion
269
- export { BackupCreateError, BackupExpiredError, BackupNotFoundError, type BackupOptions, BackupRestoreError, type BaseExecOptions, type BucketCredentials, BucketMountError, type BucketProvider, BucketUnmountError, type CheckChangesOptions, type CheckChangesResult, type CodeContext, CodeInterpreter, ContainerProxy, ContainerUnavailableError, type CreateContextOptions, type DirectoryBackup, type ExecEvent, type ExecOptions, type ExecResult, type ExecutionResult, type ExecutionSession, type FileChunk, type FileMetadata, type FileStreamEvent, type FileWatchSSEEvent, type GitCheckoutResult, type ISandbox, InvalidBackupConfigError, InvalidMountConfigError, type ListFilesOptions, type LocalMountBucketOptions, type LogEvent, MissingCredentialsError, type MountBucketOptions, type NamedTunnelInfo, type Process, ProcessExitedBeforeReadyError, type ProcessOptions, ProcessReadyTimeoutError, type ProcessStatus, type PtyOptions, type QuickTunnelInfo, type RPCTransportContext, RPCTransportError, type RPCTransportErrorKind, type RemoteMountBucketOptions, type RestoreBackupResult, type RunCodeOptions, S3FSMountError, Sandbox, type SandboxEnv, type SandboxOptions, type SessionOptions, SessionTerminatedError, type StreamOptions, type TunnelInfo, type TunnelOptions, type WaitForLogResult, type WaitForPortOptions, type WatchOptions, asyncIterableToSSEStream, collectFile, getSandbox, isExecResult, isProcess, isProcessStatus, parseSSEStream, proxyTerminal, proxyToSandbox, responseToAsyncIterable, streamFile };
575
+ export { BackupCreateError, BackupExpiredError, BackupNotFoundError, type BackupOptions, BackupRestoreError, type BucketCredentials, BucketMountError, type BucketProvider, BucketUnmountError, type CheckChangesOptions, type CheckChangesResult, ContainerProxy, ContainerUnavailableError, type CreateTerminalOptions, type DirectoryBackup, type ExecOptions, type FileChunk, type FileMetadata, type FileStreamEvent, type FileWatchSSEEvent, type ISandbox, InvalidBackupConfigError, InvalidMountConfigError, InvalidProcessCursorError, InvalidProcessCwdError, InvalidProcessEnvironmentError, InvalidTerminalCursorError, InvalidTerminalCwdError, type ListFilesOptions, type LocalMountBucketOptions, MissingCredentialsError, type MountBucketOptions, type NamedTunnelInfo, OperationInterruptedError, ProcessAbortedError, ProcessError, type ProcessExit, ProcessExitedBeforeLogError, ProcessExitedBeforeReadyError, type ProcessFailure, type ProcessLogCursor, type ProcessLogEvent, type ProcessLogsOptions, ProcessNotFoundError, type ProcessOutput, type ProcessOutputOptions, ProcessReadyTimeoutError, ProcessSpawnFailedError, type ProcessStatus, type ProcessTextOutputOptions, ProcessWaitTimeoutError, type QuickTunnelInfo, type RPCTransportContext, RPCTransportError, type RPCTransportErrorKind, type RemoteMountBucketOptions, type RestoreBackupResult, RuntimeControlProtocolError, RuntimeIdentityInactiveError, S3FSMountError, Sandbox, type SandboxCommand, type SandboxEnv, type SandboxOptions, type SandboxProcess, StaleProcessHandleError, StaleTerminalHandleError, type Terminal, TerminalControlError, TerminalNotFoundError, type TerminalOutputCursor, type TerminalOutputEvent, type TerminalOutputOptions, type TerminalSnapshot, type TunnelInfo, type TunnelOptions, type WaitForExitOptions, type WaitForLogOptions, type WaitForLogResult, type WaitForPortOptions, type WatchOptions, asyncIterableToSSEStream, collectFile, getSandbox, isDurableObjectCodeUpdateReset, isPlatformTransientError, parseSSEStream, proxyTerminal, proxyToSandbox, responseToAsyncIterable, streamFile };
270
576
  //# sourceMappingURL=index.d.ts.map