Skip to content

Sandbox SDK 0.x API map

Last updated View as MarkdownAgent setup

This page maps each public API of @cloudflare/sandbox 0.12 to its replacement: a 1.0 class, a platform API, another Cloudflare product, or code that you write. Some APIs are no longer needed. For the migration steps, refer to Migrate from Sandbox SDK 0.x.

In the tables, container is this.ctx.container in your Durable Object, and files is a Files instance. The Kind column uses these values:

Kind Meaning
Native Call container or another platform API directly.
Package Use a class from @cloudflare/sandbox 1.0, such as Files.
Pattern Write it yourself. When a page shows how, the note links it.
Product Use another Cloudflare product.
Removed Not needed. The note says what to do instead.

Class, identity, and lifetime

For the steps, refer to Replace the Sandbox class. These APIs create a sandbox and control how long its container runs:

0.12 Kind Replacement Notes
class X extends Sandbox, export { Sandbox } Removed class X extends DurableObject Construct the classes of the package from container.
getSandbox(ns, id, options) Native env.NS.getByName(id) Validate names yourself.
normalizeId, setSandboxName() Removed Lowercase names yourself Needed only when names become hostnames.
sleepAfter, setSleepAfter() Native container.setInactivityTimeout(ms) At most 6 hours. Call it after start(), and again in the constructor.
keepAlive, setKeepAlive() Pattern An alarm that sends the container a request while work remains Refer to Sandbox lifetime.
renewActivityTimeout() Native Any request to the Durable Object The timeout counts from when the Durable Object becomes inactive.
containerTimeouts, setContainerTimeouts() Removed AbortSignal
transport, setTransport(), SANDBOX_TRANSPORT Removed Not needed container.exec() and Files reach the container directly. Remove the setting.
labels, setLabels() Native container.start({ labels })
configure() Removed Options on each call
setEnvVars(), class envVars Native container.start({ env }) or container.exec(argv, { env }) exec() does not inherit start() variables, except PATH.
Class entrypoint, enableInternet Native container.start({ entrypoint, enableInternet }) enableInternet defaults to false. It defaulted to true in 0.12.
Class defaultPort, requiredPorts Native container.getTcpPort(port)
start() Native container.start({ image }) Does not wait for the container.
startAndWaitForPorts(), waitForPort() Pattern Retry getTcpPort(port).fetch() Preview a web application shows a readiness check.
stop(), destroy() Native container.signal(), container.destroy()
getState() Native container.running, container.monitor()
getContainerPlacementId() Pattern Read CLOUDFLARE_PLACEMENT_ID from /proc/1/environ with container.exec() The main process of the container has the variable. Commands do not.
onStart, onStop, onError, onActivityExpired Pattern Your code around start() and monitor()
schedule(), listSchedules(), getSchedule(), deleteSchedules(), alarm() Native Durable Object alarms One alarm per object. Store your own schedule if you need several.
fetch(), containerFetch() Native container.getTcpPort(port).fetch()

Commands

For the steps, refer to Change command calls. These APIs run commands:

0.12 Kind Replacement Notes
exec(command, options) Native container.exec(argv, options) output() returns bytes and exitCode. success is exitCode === 0.
stream, onOutput, onComplete, onError Native Read stdout and stderr, and await exitCode
execStream() Native The stdout stream from container.exec(argv) Set Content-Type: text/event-stream on the response. Refer to Stream output.
timeout, signal Native Run the command under timeout, or pass signal from a timer you clear Exit code 124 means the time passed. Refer to Replace timeouts.
cwd, env Native The same options Pass cwd: "/workspace" and env, which 0.12 set by default.
encoding Removed Decode bytes yourself
isExecResult(), isProcess(), isProcessStatus() Removed Not needed exec() returns an ExecProcess. TypeScript types replace the guards.

Processes

For the steps, refer to Move background processes. Each replacement builds on the process directories from Run background processes. These APIs run and manage background processes:

0.12 Kind Replacement Notes
startProcess() Pattern startProcess(id, argv), which writes the process ID, output, and exit code to files Pass cwd: "/workspace" and env, which 0.12 set. Refer to Add the process methods.
Process.getStatus(), getProcess(), listProcesses() Pattern status(), and a listProcesses() method over the process directories
getProcessLogs(), Process.getLogs() Pattern logs() for each stream
streamProcessLogs() Pattern follow(), which streams tail -F --pid Named stdout, stderr, and exit events, not LogEvent objects.
Process.waitForLog() Pattern waitForLog(), which polls the log files with grep -E Escape 0.12 string patterns. Refer to Wait for output or exit.
Process.waitForExit() Pattern A waitForExit() method that calls status() until the process ends
Process.waitForPort() Pattern Retry getTcpPort(port).fetch() Preview a web application shows a readiness check.
Process.kill(), killProcess() Pattern stop(), which sends SIGTERM to the process group 0.12 sent SIGKILL 5 seconds later.
killAllProcesses() Pattern stop() for each process that listProcesses() returns
cleanupCompletedProcesses(), autoCleanup Removed Not needed Both did nothing in 0.12. Delete ended process directories with rm -rf.
onStart, onOutput, onError Pattern Code after startProcess(), follow(), and a start that throws or returns false
onExit Pattern The alarm that checks each process every minute Refer to Replace callbacks.

Sessions

For the steps, refer to Replace sessions. These APIs keep state between commands:

0.12 Kind Replacement Notes
createSession(), getSession(), deleteSession() Removed cwd and env on each call
enableDefaultSession Removed cwd and env on each call cd and export do not carry over.
isolation Removed Separate sandboxes
commandTimeoutMs Removed timeout in each command

ExecutionSession methods map like the top-level methods.

Files

For the steps, refer to Change file calls. These APIs read and write files:

0.12 Kind Replacement Notes
readFile(), readFileStream() Package files.readFile() Returns a Response. Use .text(), .arrayBuffer(), or the body.
writeFile() Package files.writeFile() Create missing parent directories with mkdir() first. Pass bytes instead of base64.
mkdir() Package files.mkdir()
deleteFile() Package files.remove() Also removes directories with recursive: true.
renameFile(), moveFile() Package files.rename() Fails with EXDEV across filesystems.
listFiles() Package files.readDirectory() One level. Includes hidden entries.
listFiles({ recursive: true }) Pattern Walk readDirectory() Refer to List files.
exists() Package files.stat() Catch SandboxFileError with ENOENT.
File metadata Package files.stat(), files.lstat()
watch(), checkChanges() Pattern inotifywait -m through container.exec() Refer to Replace file watching.
collectFile(), streamFile() Removed The Response body
parseSSEStream(), responseToAsyncIterable(), asyncIterableToSSEStream() Removed The ReadableStream objects on ExecProcess To send output to a browser as server-sent events, refer to Stream command output.
WriteFileResult, ReadFileResult, and other result types Removed void, Response, or SandboxFileStat Failures throw SandboxFileError.

Ports, preview URLs, and tunnels

For the steps, refer to Move preview URLs and Move tunnels. These APIs make a server in the container reachable from outside it:

0.12 Kind Replacement Notes
exposePort(), unexposePort(), getExposedPorts(), isPortExposed() Pattern Methods over the 0.12 portTokens key URLs that 0.12 issued keep working. Refer to Replace the preview calls.
validatePortToken() Pattern A constant-time check of the stored token
proxyToSandbox(), SandboxEnv Pattern Route <port>-<name>-<token> hostnames to getByName()
wsConnect(request, port) Native container.getTcpPort(port).fetch(request) Bridge the WebSocket to keep the container running.
tunnels.get(port), tunnels.list(), tunnels.destroy(port) Pattern openTunnel(), listTunnels(), and closeTunnel(), which run cloudflared Needs enableInternet: true. Refer to Run cloudflared from your Durable Object.
tunnels.get(port, { name }) Pattern resumeTunnel() and deleteTunnel() over the 0.12 tunnels key Hostnames that 0.12 created keep working. Refer to Keep named tunnels that 0.12 created.
CLOUDFLARE_API_TOKEN Pattern The same secret Keep it while you run or delete named tunnels that 0.12 created.
CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_TUNNEL_ACCOUNT_ID, CLOUDFLARE_ZONE_ID Removed Not needed The code reads the account and zone that 0.12 stored.

Terminals

For the steps, refer to Move browser terminals. These APIs connect a browser terminal to a shell:

0.12 Kind Replacement Notes
terminal(), session.terminal() Pattern getByName(name).fetch(request), and a handler that attaches a tmux client with exec(argv, { pty }) Start the shell in /workspace with env, which 0.12 set. Refer to Attach terminals to tmux.
proxyTerminal() Pattern The same fetch() call, with the session in the query string Refer to Forward the WebSocket.
cwd and env of a session that a terminal opens Pattern The -c and -e options of tmux new-session tmux applies them when it creates the session.
shell option Pattern A command after the session name in the tmux command
@cloudflare/sandbox/xterm, SandboxAddon, SandboxAddonOptions, ConnectionState, ConnectionTarget Pattern xterm.js with a WebSocket that the page reopens Send {"type":"ready"} so that pages loaded before the switch keep working. Refer to Replace SandboxAddon.
Terminal reconnect and replay Pattern tmux keeps the session and redraws the screen Earlier output stays in the tmux history. Refer to What changes at the terminal.

Outbound network and Git

For the steps, refer to Move outbound rules. These APIs control the requests that code in the container sends:

0.12 Kind Replacement Notes
allowedHosts, deniedHosts, outbound, outboundByHost, outboundHandlers, outboundProxies, outboundProxy Pattern A WorkerEntrypoint that applies the rules in the 0.12 order Handlers take (request, env, params). Refer to Apply the rules in an entrypoint.
outboundByHost handlers that read Workers bindings Pattern A WorkerEntrypoint for each hostname Refer to Reach Workers bindings from the container.
interceptHttps Native container.interceptOutboundHttps("*", fetcher) for every sandbox Add the certificate to the system bundle, and set NODE_EXTRA_CA_CERTS and REQUESTS_CA_BUNDLE. 0.12 checked HTTPS only with interceptHttps = true. Refer to What changes for requests.
setAllowedHosts(), setDeniedHosts(), allowHost(), denyHost(), removeAllowedHost(), removeDeniedHost(), setOutboundHandler(), setOutboundByHost(), setOutboundByHosts(), removeOutboundByHost() Pattern Methods that update the OUTBOUND_CONFIGURATION key and register the entrypoint again Rules that 0.12 stored keep applying. Refer to Replace the runtime setters.
ContainerProxy Removed Export your own entrypoint Remove it from the exports of your Worker.
gitCheckout() Pattern exec() of git clone --filter=blob:none in /workspace Refer to Replace gitCheckout(). For private repositories, refer to Clone a private repository.

Bucket mounts

For the steps, refer to Move bucket mounts. These APIs mount object storage in the container:

0.12 Kind Replacement Notes
mountBucket() with an S3 endpoint Package S3Mount.mount(), with S3Gateway exported from your Worker Credentials stay in the Worker. Refer to Mount the bucket.
mountBucket() with an R2 binding Package S3Mount.mount() with the R2 S3 endpoint Needs an R2 API token for the bucket. 1.0 cannot mount through a binding.
prefix, readOnly, s3fsOptions Package keyPrefix, access, s3fsOptions keyPrefix has no leading /, access is required, and s3fsOptions is an object.
credentials, R2_* and AWS_* variables Package source.credentials Not read from the environment.
credentialProxy, provider Removed Not needed S3Gateway signs every request. S3Mount always sets nomixupload, which 0.12 added only for R2.
localBucket Package S3Mount under wrangler dev with a local S3-compatible server Needs Wrangler 4.137.0 or later. Refer to Replace localBucket.
unmountBucket() Package S3Mount.unmount() Throws S3_MOUNT_BUSY while a process uses the path.
BucketMountError, BucketUnmountError, InvalidMountConfigError, MissingCredentialsError, S3FSMountError Package SandboxS3MountError An invalid request throws TypeError.
Mounts next to outbound rules Pattern Mount before interceptAllOutboundHttp() A mount registered after the catch-all intercept fails. Refer to If you moved outbound rules.

Backups

For the steps, refer to Move backups. These APIs save and restore directories:

0.12 Kind Replacement Notes
createBackup(), restoreBackup() Package DirectoryBackup backup() and restore() Your Durable Object stores the record. For the whole filesystem, use container.snapshotContainer().
name, gitignore Package The DirectoryBackup options with the same names gitignore does not need git in the image.
excludes Package exclude .gitignore syntax. A pattern that starts with / matches only at the top, as 0.12 patterns did.
ttl Pattern An expiry time stored in the bucket next to the backup 0.12 refused expired restores and kept the objects.
multipart, localBucket, compression Removed Not needed Every backup goes through the R2 binding in parts.
BACKUP_BUCKET Native An R2 binding Pass its name as the binding of DirectoryBackup.
BACKUP_BUCKET_NAME, BACKUP_BUCKET_ENDPOINT, R2 access keys Removed The R2 binding The container never holds bucket credentials.
BackupNotFoundError Package SandboxBackupError with the code BACKUP_NOT_FOUND
BackupExpiredError Pattern The error that your expiry check throws
InvalidBackupConfigError Removed TypeError
BackupCreateError, BackupRestoreError Package SandboxFileError or SandboxBackupError Refer to DirectoryBackup errors.
Backups made by 0.12 Pattern unsquashfs on backups/<id>/data.sqsh, then backup() Refer to Convert backups that 0.12 created.

Code interpreter and subpath packages

These APIs came from the code interpreter and the subpath exports of the package:

0.12 Kind Replacement Notes
runCode(), createCodeContext(), listCodeContexts(), deleteCodeContext(), CodeInterpreter Pattern An IPython kernel for each context, or a Dynamic Worker for JavaScript Refer to Replace the code interpreter.
runCodeStream(), onStdout, onStderr, onResult Pattern A command with python3 - and its stdout Refer to Replace streaming output.
@cloudflare/sandbox/opencode, createOpencode(), createOpencodeServer(), OpencodeOptions, OpencodeResult, OpencodeServer, OpencodeStartupError Pattern opencode serve and an OpenCode SDK client Refer to Start an OpenCode server.
proxyToOpencode(), proxyToOpencodeServer() Pattern fetch() in your Durable Object, which forwards to the server port Refer to Start an OpenCode server.
@cloudflare/sandbox/openai, Shell, Editor, CommandResult, FileOperationResult Pattern Your own Shell and Editor ShellResult and ApplyPatchResult from @openai/agents replace the result types. Refer to Give OpenAI agents a shell and an editor.
@cloudflare/sandbox/bridge, bridge(), resolveWorkspacePath(), shellQuote(), BridgeConfig, BridgeEnv, WorkerHandlers Pattern Your own Worker routes Refer to Replace the bridge.
WarmPool, WarmPoolConfig, PoolStats Removed Start each sandbox when a request needs it Refer to Remove WarmPool.

Images

0.12 published container images for the Sandbox class to build on:

0.12 Kind Replacement Notes
cloudflare/sandbox, -python, -opencode, and -musl images Removed Your own linux/amd64 image Copy sandbox-shim into it if you use Files or S3Mount. Refer to Requirements.
docker:dind-rootless with USER root Pattern docker:dind with --ip-forward=false Refer to Run Docker inside the sandbox.

Errors and clients

These APIs report failures and talk to the container:

0.12 Kind Replacement Notes
ContainerUnavailableError, OperationInterruptedError, RPCTransportError, SessionTerminatedError Removed Native errors from container Not wrapped.
ProcessExitedBeforeReadyError, ProcessReadyTimeoutError Pattern The results of your readiness check Refer to Preview a web application.
isPlatformTransientError(), isDurableObjectCodeUpdateReset() Removed error.retryable and error.overloaded Retry idempotent calls with a new stub when retryable is true, and never when overloaded is true. The package does not retry. Refer to Error handling.
SandboxClient, BackupClient, CommandClient, FileClient, GitClient, InterpreterClient, PortClient, ProcessClient, UtilityClient Removed container and Files Call them from your Durable Object.
SANDBOX_LOG_LEVEL, SANDBOX_LOG_FORMAT Removed Your own logs The package does not log. Log from your Worker and read the logs in Workers Logs.

Types

These 0.12 types describe the options and results of the methods in the earlier sections. Each type goes where its method goes:

0.12 Kind Replacement Notes
SandboxOptions, SandboxTransport, ISandbox, ContainerStub Removed Your class Refer to Class, identity, and lifetime.
BaseExecOptions, ExecOptions, StreamOptions, ExecResult, ExecEvent, ExecuteRequest, CommandExecuteResponse, CommandsResponse Native ContainerExecOptions, ExecProcess, ExecOutput wrangler types generates them.
PtyOptions Native ContainerExecPtyOptions Pass it as pty to container.exec(). The shell goes in the command.
SessionOptions, SessionRequest, CreateSessionRequest, CreateSessionResponse, DeleteSessionRequest, DeleteSessionResponse Removed cwd and env on each call
ProcessOptions, ProcessStatus, ProcessStartResult, ProcessListResult, ProcessInfoResult, ProcessKillResult, ProcessLogsResult, ProcessCleanupResult, StartProcessRequest, WaitForLogResult, WaitForPortOptions Pattern The types of your process methods Refer to Move background processes.
ReadFileRequest, WriteFileRequest, FileOperationRequest, MkdirRequest, ListFilesOptions Package FileOperationOptions, MkdirOptions, RemoveOptions, FileContent
FileMetadata, FileChunk, FileStreamEvent Removed The Response from files.readFile()
WatchOptions, FileWatchSSEEvent, CheckChangesOptions, CheckChangesResult Pattern The events that your inotifywait reader returns Refer to Replace file watching.
TunnelOptions, TunnelInfo, QuickTunnelInfo, NamedTunnelInfo Pattern The types of your tunnel methods Refer to Move tunnels.
GitCheckoutRequest, GitCheckoutResult Pattern The arguments and output of your git clone command Refer to Replace gitCheckout().
MountBucketOptions, RemoteMountBucketOptions, LocalMountBucketOptions, BucketCredentials, BucketProvider Package S3MountRequest
BackupOptions, DirectoryBackup, RestoreBackupResult Package DirectoryBackupOptions, DirectoryBackupRecord, DirectoryRestoreOptions DirectoryBackupRecord adds size, name, sha256, and format, and drops localBucket. restore() returns nothing. In 1.0, DirectoryBackup is the class that saves and restores backups.
CodeContext, CreateContextOptions, RunCodeOptions, ExecutionCallbacks, ExecutionResult Pattern The CodeContext and Execution types of your kernel Refer to Replace the code interpreter.
ContainerUnavailableContext, ContainerUnavailableReason, OperationInterruptedContext, OperationInterruptedReason, RPCTransportContext, RPCTransportErrorKind Removed Not needed Their errors are removed.
SandboxClientOptions, RequestConfig, ResponseHandler, BaseApiResponse, ErrorResponse, PingResponse Removed Not needed The clients are removed.

Was this helpful?