Sandbox Commands, Streaming Output, File Watch, and Code Interpreter
How to run commands in a remote sandbox, stream live output, watch files with inotify, and execute Python or JavaScript with persistent contexts.
This page summarises Cloudflare documentation on the Sandbox SDK and related container APIs: running shell commands, sending output to callers in real time, watching the workspace filesystem, and running code through the Code Interpreter. The same platform also offers lower-level container.exec() inside Durable Object–backed containers when you build Workers without the full SDK helpers.
Execute commands and stream output. Run scripts, manage background processes, and capture execution results.
— Cloudflare, API reference
exec(), execStream(), and startProcess(): which API to use
Section titled “exec(), execStream(), and startProcess(): which API to use”Cloudflare exposes several ways to run work inside a sandbox. The choice depends on whether the job finishes quickly, must stream while it runs, or should keep running after the HTTP request ends.
| Situation | Method | Output behaviour |
|---|---|---|
| Builds, installs, one-off scripts | exec() |
Full result when the command exits |
| Long jobs where users need live logs | execStream() or container streaming patterns |
Server-Sent Events (SSE) while the command runs |
| Servers, dev tools, watchers | startProcess() |
Process stays up; logs via streamProcessLogs() or files |
| Short Python/JS with rich results | createCodeContext() + runCode() |
Structured execution result; state can persist in the context |
The SDK provides multiple approaches for running commands: exec() - Run a command and wait for complete result. Best for one-time commands like builds, installations, and scripts. execStream() - Stream output in real-time. Best for long-running commands where you need immediate feedback. startProcess() - Start a background process. Best for web servers, databases, and services that need to keep running.
— Cloudflare, Execute commands
At the container layer, Run commands in a sandbox groups recipes by how output reaches the caller: buffered response after exit, SSE while the command runs, log files for background work, or an interactive browser terminal. For every exec() option on the container, see Execute commands in the Containers documentation.
exec(): buffered runs, stdin, and success checks
Section titled “exec(): buffered runs, stdin, and success checks”exec() runs a command and returns success, stdout, stderr, and exitCode. You can pass stdin without shell interpolation, set env and cwd, or enable stream: true with onOutput for incremental callbacks on the same call. See the Commands API for parameters.
All command execution methods support passing data to a command’s standard input via the stdin option. This enables secure processing of user input without shell injection risks.
— Cloudflare, Commands
Always check result.success and result.exitCode before treating output as success, as described in Execute commands.
startProcess(): when the request must not wait for exit
Section titled “startProcess(): when the request must not wait for exit”Use startProcess() for HTTP servers, databases, dev servers with hot reload, or any workload that must survive after the initiating request. The returned process object supports kill(), getLogs(), waitForPort(), and related helpers. See Background processes and Run background processes.
Command timeouts: precedence and what actually stops
Section titled “Command timeouts: precedence and what actually stops”Sandbox command timeouts are limits on the caller connection, not a guaranteed kill of the process inside the container.
When a command times out, the SDK raises an error on the caller side and closes the connection. The underlying process continues running inside the container. To stop a timed-out process, delete the session with deleteSession() or destroy the sandbox with destroy().
— Cloudflare, Commands
Timeout precedence (most specific wins):
- Per-command
timeoutonexec() - Session-level
commandTimeoutMsoncreateSession() - Global
COMMAND_TIMEOUT_MSenvironment variable
If none are set, commands run without a timeout. Details appear in Environment variables and Sessions.
Container exec() has no built-in timeout; you call kill() and await exitCode, or use GNU timeout in the argv to stop a shell script and its child processes—see Execute commands.
Streaming command output: execStream(), SSE, and SDK 1.0 migration
Section titled “Streaming command output: execStream(), SSE, and SDK 1.0 migration”Streaming fits builds, tests, installs, and demos where waiting with no feedback is unacceptable.
Use streaming when you need: Real-time feedback - Show progress as it happens. Long-running operations - Builds, tests, installations that take time.
— Cloudflare, Stream output
execStream() and parseSSEStream() in the Sandbox SDK
Section titled “execStream() and parseSSEStream() in the Sandbox SDK”execStream() returns a ReadableStream of ExecEvent values (stdout, stderr, complete, error). Consume it with parseSSEStream() from @cloudflare/sandbox:
import { parseSSEStream } from "@cloudflare/sandbox";
const stream = await sandbox.execStream("npm install");
for await (const event of parseSSEStream(stream)) { switch (event.type) { case "stdout": console.log(event.data); break; case "complete": console.log("Exit code:", event.exitCode); break; }}Full event handling patterns are in the Commands API and Stream output.
You can return the stream directly to browsers with Content-Type: text/event-stream and Cache-Control: no-cache, as shown in Stream output.
Stream command output from container.exec() in a Worker
Section titled “Stream command output from container.exec() in a Worker”For Sandboxes built on Durable Objects and containers, Stream command output runs container.exec(), forwards stdout and stderr concurrently as named SSE events, sends a terminal exit event, and calls process.kill() when the client disconnects (with a periodic : keep-alive comment so idle streams still detect disconnects).
Browser clients should use EventSource, append decoded chunk text (events may split lines), and call close() on exit so EventSource does not reconnect and re-run the command.
Change execStream() when migrating to Sandbox SDK 1.0
Section titled “Change execStream() when migrating to Sandbox SDK 1.0”Older SDK versions exposed execStream() or exec() with stream: true differently from container-based 1.0:
To replace execStream(), or exec() with stream: true and onOutput, return stdout from the process as a response body… 0.12 sent JSON events that parseSSEStream() decoded. The 1.0 body holds the output of the command. Read it with fetch() and a stream reader instead of EventSource.
— Cloudflare, Change command calls
With stderr: "combined", merged stdout and stderr do not guarantee line ordering when both streams write at once; the migration guide suggests shell redirection such as ["sh", "-c", "npm test 2>&1"] when order matters.
Follow output from a background process
Section titled “Follow output from a background process”If the process outlives the request that started it, output may land in sandbox log files. Follow a background process streams those logs with SSE (follow query parameter), using tail while running or cat after exit.
Code Interpreter: persistent contexts and when not to use it
Section titled “Code Interpreter: persistent contexts and when not to use it”The Code Interpreter runs Python, JavaScript, or TypeScript inside the sandbox with optional rich outputs (charts, tables, formatted data).
Create persistent code contexts with support for rich visual + structured outputs.
— Cloudflare, Code interpreter
createCodeContext() and runCode()
Section titled “createCodeContext() and runCode()”createCodeContext() returns a persistent CodeContext (id, language, cwd, timestamps). runCode() returns logs, results, error, and executionCount. Reuse the same context across calls so variables persist—recommended for production rather than relying on the auto-created default context. See Code interpreter and Use code interpreter.
Use the Code Interpreter API for simple, direct code execution with minimal setup… Use exec() for advanced or custom workflows: System operations - Install packages, manage files, run builds.
— Cloudflare, Use code interpreter
JavaScript and TypeScript contexts support top-level await and persistent const / let / var across executions in the same context.
Streaming code output in SDK 1.0
Section titled “Streaming code output in SDK 1.0”When upgrading, note that kernel-style streaming for cells does not map one-to-one to 1.0:
The kernel returns the output of a cell when the cell finishes, so runCodeStream(), onStdout, onStderr, and onResult have no 1.0 version. To send output while code runs, run the code as a command with python3 -, pass it on standard input, and return stdout from the process.
— Cloudflare, Replace the code interpreter
Free resources with deleteCodeContext(contextId) when a workflow ends.
watch(): real-time file changes with inotify
Section titled “watch(): real-time file changes with inotify”File watching uses Linux inotify to drive hot reload, test-on-save, and incremental indexing.
Monitor real-time filesystem changes using native inotify. Build development tools, hot-reload systems, and responsive file processing.
— Cloudflare, API reference
watch() streams and FileWatchSSEEvent types
Section titled “watch() streams and FileWatchSSEEvent types”watch(path, options) resolves only after the server-side watcher is active. It returns an SSE ReadableStream you can proxy to clients or parse in the Worker:
Pass a directory path and optional filters. The returned stream is a standard ReadableStream you can proxy directly to a browser client or consume server-side.
— Cloudflare, Real-time file watching in Sandboxes
Lifecycle envelope types (watching, event, error, stopped) and filesystem eventType values (create, modify, delete, move_from, move_to, attrib) are documented in File watching. Cancel with AbortSignal passed to parseSSEStream()—aborting cleans up the watcher server-side.
watch() options, paths, and container lifecycle
Section titled “watch() options, paths, and container lifecycle”| Option | Role |
|---|---|
recursive |
Watch subdirectories (default true in API reference) |
include |
Glob allowlist; cannot combine with exclude |
exclude |
Glob blocklist; default patterns include .git, node_modules, .DS_Store |
Paths must exist and stay under /workspace. Watchers stop when the sandbox sleeps or is destroyed; re-establish watches after wake. Patterns and pitfalls (debouncing, server-side filtering vs client filtering) are in Watch filesystem changes.
Pair watching with exec() for auto-rebuild or auto-test flows, as in the Automated testing pipeline tutorial next steps (streaming output, background processes, Sessions API).
container.exec(): argv arrays, streams, and SDK wrappers
Section titled “container.exec(): argv arrays, streams, and SDK wrappers”Inside a running container, exec(cmd, options) starts the executable directly—no implicit shell unless you pass ["sh", "-c", "..."] or ["bash", "-lc", "..."].
exec() starts the executable directly with the provided arguments. It does not start a shell or interpret pipes, redirects, expansion, or other shell syntax.
— Cloudflare, Durable Object Container API
Use stdin: "pipe" or a ReadableStream, stderr: "combined" only with stdout: "pipe", and prefer concurrent stream reads over output() for large stdout/stderr to avoid buffering entire output in Durable Object memory. The Container class points to the same execution guides.
The HTTP bridge documents argv escaping and SSE payload shapes (stdout/stderr as Base64 chunks, terminal exit and error events) in the HTTP API reference.
Common mistakes
Section titled “Common mistakes”- Treating a sandbox timeout error as proof the process stopped—it may still run until the session or sandbox is torn down.
- Using
output()on large command output instead of drainingstdout/stderrstreams concurrently (Execute commands). - Assuming client disconnect stops child processes from a shell wrapper; use
timeoutor explicit process-group handling where needed (Stream command output). - Passing both
includeandexcludetowatch()—the API rejects that combination (File watching). - Filtering file events only in JavaScript when
include/excludecould filter at the inotify layer (Watch filesystem changes). - Calling
kill()or abortingsignalafterexitCodehas already resolved on container processes (Durable Object Container API). - Expecting
runCodeStream()or streaming callbacks on Code Interpreter after a 1.0 migration without switching to command-based streaming (Replace the code interpreter).
How to check this on your site
Section titled “How to check this on your site”-
Deploy a Worker that uses sandbox command or watch routes following Stream command output or your own
execStream()handler, usingnpx wrangler deployas shown in that guide. -
Trigger a known command (for example the sample build argv in Stream command output) with
curl … --no-bufferand confirmstdout,stderr, and a finalexitevent with the expected exit code. -
If you use background processes, start a process via your Worker API, then call the follow route from Follow a background process and verify incremental SSE chunks until an
exitevent. -
Start
watch()on an existing directory under/workspace, change a file matching yourincludepattern, and confirmeventpayloads viaparseSSEStream()as in File watching. -
You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page does not match the official behaviour you see, email yimasynthetic@gmail.com with the page URL and the exact sentence you think is wrong or unclear, and we will correct or expand it.